453 lines
16 KiB
TypeScript
453 lines
16 KiB
TypeScript
"use client";
|
||
|
||
import {
|
||
CheckIcon,
|
||
InfoIcon,
|
||
Loader2Icon,
|
||
PlusIcon,
|
||
SearchIcon,
|
||
UploadIcon,
|
||
XIcon,
|
||
} from "lucide-react";
|
||
import { useMemo, useRef, useState } from "react";
|
||
import { toast } from "sonner";
|
||
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import {
|
||
Select,
|
||
SelectContent,
|
||
SelectItem,
|
||
SelectTrigger,
|
||
SelectValue,
|
||
} from "@/components/ui/select";
|
||
import {
|
||
Sheet,
|
||
SheetContent,
|
||
SheetDescription,
|
||
SheetHeader,
|
||
SheetTitle,
|
||
} from "@/components/ui/sheet";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import {
|
||
skillDisplayLabel,
|
||
skillInitial,
|
||
skillSourceLabel,
|
||
} from "@/components/workspace/agents/enabled-skill-list";
|
||
import type { Skill } from "@/core/skills";
|
||
import {
|
||
useInstallSkillUpload,
|
||
useValidateSkillUpload,
|
||
} from "@/core/skills/hooks";
|
||
import { desensitize } from "@/lib/desensitize";
|
||
import { cn } from "@/lib/utils";
|
||
|
||
const ALL_CATEGORIES = "__all__";
|
||
|
||
type SourceFilter = "all" | "builtin" | "upload" | "agent";
|
||
|
||
const SOURCE_OPTIONS: { value: SourceFilter; label: string }[] = [
|
||
{ value: "all", label: "全部来源" },
|
||
{ value: "builtin", label: "内置技能" },
|
||
{ value: "upload", label: "用户上传" },
|
||
{ value: "agent", label: "对话沉淀" },
|
||
];
|
||
|
||
function matchesSource(skill: Skill, source: SourceFilter) {
|
||
switch (source) {
|
||
case "all":
|
||
return true;
|
||
case "builtin":
|
||
return !!skill.builtin;
|
||
case "upload":
|
||
return skill.source === "upload";
|
||
case "agent":
|
||
return skill.source === "agent";
|
||
}
|
||
}
|
||
|
||
function matchesQuery(skill: Skill, q: string) {
|
||
if (!q) return true;
|
||
return (
|
||
skill.name.toLowerCase().includes(q) ||
|
||
(skill.name_zh ?? "").toLowerCase().includes(q) ||
|
||
(skill.description ?? "").toLowerCase().includes(q)
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 技能选择器 — a secondary right-hand drawer opened from the agent detail
|
||
* panel's "添加技能" button. Search (中英文名称 + 描述), category tabs, source
|
||
* filter (内置 / 用户上传 / 对话沉淀), skill-pack upload, card grid with
|
||
* enable/disable switches, bulk add-filtered / clear-selected, and a footer
|
||
* showing the live selected count. Selection is controlled by the caller (the
|
||
* panel's local draft) — nothing here persists until the panel saves.
|
||
*/
|
||
export function SkillPickerSheet({
|
||
open,
|
||
onOpenChange,
|
||
skills,
|
||
isLoading,
|
||
selected,
|
||
onChange,
|
||
onViewDetail,
|
||
}: {
|
||
open: boolean;
|
||
onOpenChange: (open: boolean) => void;
|
||
/** Selectable pool (caller pre-filters by `enabled`). */
|
||
skills: Skill[];
|
||
isLoading?: boolean;
|
||
/** Currently selected skill names — the draft `skills: string[]`. */
|
||
selected: string[];
|
||
onChange: (next: string[]) => void;
|
||
onViewDetail?: (name: string) => void;
|
||
}) {
|
||
const [search, setSearch] = useState("");
|
||
const [category, setCategory] = useState<string>(ALL_CATEGORIES);
|
||
const [source, setSource] = useState<SourceFilter>("all");
|
||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||
|
||
const validateUpload = useValidateSkillUpload();
|
||
const installUpload = useInstallSkillUpload();
|
||
const isUploading = validateUpload.isPending || installUpload.isPending;
|
||
|
||
const selectedSet = useMemo(() => new Set(selected), [selected]);
|
||
|
||
const categories = useMemo(() => {
|
||
const set = new Set<string>();
|
||
for (const skill of skills) {
|
||
if (skill.category?.trim()) set.add(skill.category.trim());
|
||
}
|
||
return Array.from(set).sort((a, b) => a.localeCompare(b));
|
||
}, [skills]);
|
||
|
||
const query = search.trim().toLowerCase();
|
||
|
||
const filtered = useMemo(
|
||
() =>
|
||
skills.filter(
|
||
(skill) =>
|
||
matchesQuery(skill, query) &&
|
||
matchesSource(skill, source) &&
|
||
(category === ALL_CATEGORIES || skill.category?.trim() === category),
|
||
),
|
||
[skills, query, source, category],
|
||
);
|
||
|
||
const filteredUnselected = useMemo(
|
||
() => filtered.filter((skill) => !selectedSet.has(skill.name)),
|
||
[filtered, selectedSet],
|
||
);
|
||
|
||
function toggle(name: string) {
|
||
if (selectedSet.has(name)) {
|
||
onChange(selected.filter((n) => n !== name));
|
||
} else {
|
||
onChange([...selected, name]);
|
||
}
|
||
}
|
||
|
||
function addAllFiltered() {
|
||
if (filteredUnselected.length === 0) return;
|
||
onChange([...selected, ...filteredUnselected.map((s) => s.name)]);
|
||
}
|
||
|
||
function clearSelected() {
|
||
if (selected.length === 0) return;
|
||
onChange([]);
|
||
}
|
||
|
||
async function handleUploadFile(file: File) {
|
||
const lower = file.name.toLowerCase();
|
||
if (!lower.endsWith(".zip") && !lower.endsWith(".skill")) {
|
||
toast.error("仅支持 .zip / .skill 技能包");
|
||
return;
|
||
}
|
||
try {
|
||
const validation = await validateUpload.mutateAsync({
|
||
file,
|
||
targetCategory: "custom",
|
||
});
|
||
if (validation.conflict) {
|
||
const owner = validation.owner_username ?? validation.owner_user_id;
|
||
if (validation.owned_by_other && owner) {
|
||
toast.error(
|
||
`技能「${validation.skill_name}」已由用户「${owner}」上传,不能覆盖。`,
|
||
);
|
||
return;
|
||
}
|
||
if (validation.owned_by_me && validation.can_overwrite) {
|
||
toast.warning(
|
||
`您已上传过同名技能「${validation.skill_name}」,可到「技能」设置页重复上传并覆盖原版本。`,
|
||
);
|
||
return;
|
||
}
|
||
toast.warning(
|
||
`已存在同名技能「${validation.skill_name}」,当前不可覆盖。`,
|
||
);
|
||
return;
|
||
}
|
||
const result = await installUpload.mutateAsync({
|
||
file,
|
||
targetCategory: "custom",
|
||
});
|
||
// Auto-select the freshly installed skill so the user doesn't have to
|
||
// hunt for it in the refreshed pool.
|
||
if (!selectedSet.has(result.skill_name)) {
|
||
onChange([...selected, result.skill_name]);
|
||
}
|
||
toast.success(`技能「${result.skill_name}」已安装并加入已选`);
|
||
} catch (err) {
|
||
toast.error(err instanceof Error ? err.message : String(err));
|
||
} finally {
|
||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||
<SheetContent
|
||
side="right"
|
||
className="flex w-full flex-col gap-0 p-0 sm:max-w-xl"
|
||
>
|
||
<SheetHeader className="border-b px-5 pb-3 pt-4">
|
||
<SheetTitle>添加技能</SheetTitle>
|
||
<SheetDescription>
|
||
为该智能体启用技能。修改后需在右侧面板点击「保存」才会生效。
|
||
</SheetDescription>
|
||
</SheetHeader>
|
||
|
||
{/* Toolbar: search / source / upload */}
|
||
<div className="space-y-2.5 border-b px-5 py-3">
|
||
<div className="flex items-center gap-2">
|
||
<div className="relative flex-1">
|
||
<SearchIcon className="text-muted-foreground absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2" />
|
||
<Input
|
||
placeholder="搜索技能(中英文名称、描述)…"
|
||
value={search}
|
||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||
className="h-8 pl-8 text-xs"
|
||
/>
|
||
</div>
|
||
<Select
|
||
value={source}
|
||
onValueChange={(v) => setSource(v as SourceFilter)}
|
||
>
|
||
<SelectTrigger className="h-8 w-28 shrink-0 px-2 text-xs">
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent position="popper">
|
||
{SOURCE_OPTIONS.map((opt) => (
|
||
<SelectItem key={opt.value} value={opt.value}>
|
||
{opt.label}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
variant="outline"
|
||
className="h-8 shrink-0 text-xs"
|
||
disabled={isUploading}
|
||
onClick={() => fileInputRef.current?.click()}
|
||
title="上传 .zip / .skill 技能包"
|
||
>
|
||
{isUploading ? (
|
||
<Loader2Icon className="size-3.5 animate-spin" />
|
||
) : (
|
||
<UploadIcon className="size-3.5" />
|
||
)}
|
||
上传技能
|
||
</Button>
|
||
<input
|
||
ref={fileInputRef}
|
||
type="file"
|
||
accept=".zip,.skill"
|
||
className="hidden"
|
||
onChange={(e) => {
|
||
const file = e.target.files?.[0];
|
||
if (file) void handleUploadFile(file);
|
||
}}
|
||
/>
|
||
</div>
|
||
|
||
{/* Category tabs */}
|
||
{categories.length > 0 && (
|
||
<div className="flex flex-wrap gap-1.5">
|
||
{[ALL_CATEGORIES, ...categories].map((c) => (
|
||
<button
|
||
key={c}
|
||
type="button"
|
||
onClick={() => setCategory(c)}
|
||
className={cn(
|
||
"rounded-full border px-2.5 py-1 text-xs transition-colors",
|
||
category === c
|
||
? "border-primary/50 bg-primary/10 text-primary font-medium"
|
||
: "border-border text-muted-foreground hover:bg-accent hover:text-foreground",
|
||
)}
|
||
>
|
||
{c === ALL_CATEGORIES ? "全部" : c}
|
||
</button>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
{/* Bulk actions */}
|
||
<div className="flex items-center justify-between">
|
||
<span className="text-muted-foreground text-xs tabular-nums">
|
||
{filtered.length} 个匹配技能
|
||
</span>
|
||
<div className="flex items-center gap-1.5">
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
variant="ghost"
|
||
className="h-7 text-xs"
|
||
disabled={filteredUnselected.length === 0}
|
||
onClick={addAllFiltered}
|
||
>
|
||
<PlusIcon className="size-3.5" />
|
||
添加当前筛选结果
|
||
{filteredUnselected.length > 0
|
||
? `(${filteredUnselected.length})`
|
||
: ""}
|
||
</Button>
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
variant="ghost"
|
||
className="text-muted-foreground h-7 text-xs"
|
||
disabled={selected.length === 0}
|
||
onClick={clearSelected}
|
||
>
|
||
<XIcon className="size-3.5" />
|
||
清空已选
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
{/* Skill card grid */}
|
||
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-3">
|
||
{isLoading ? (
|
||
<div className="text-muted-foreground flex h-32 items-center justify-center gap-2 text-sm">
|
||
<Loader2Icon className="size-4 animate-spin" />
|
||
技能加载中…
|
||
</div>
|
||
) : filtered.length === 0 ? (
|
||
<div className="text-muted-foreground flex h-32 flex-col items-center justify-center gap-1.5 text-sm">
|
||
<span>没有匹配的技能</span>
|
||
{(query || category !== ALL_CATEGORIES || source !== "all") && (
|
||
<span className="text-xs">试试调整搜索词或筛选条件</span>
|
||
)}
|
||
</div>
|
||
) : (
|
||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||
{filtered.map((skill) => {
|
||
const isSelected = selectedSet.has(skill.name);
|
||
return (
|
||
<div
|
||
key={skill.name}
|
||
role="button"
|
||
tabIndex={0}
|
||
onClick={() => toggle(skill.name)}
|
||
onKeyDown={(e) => {
|
||
if (e.key === "Enter" || e.key === " ") {
|
||
e.preventDefault();
|
||
toggle(skill.name);
|
||
}
|
||
}}
|
||
title={isSelected ? "点击禁用" : "点击启用"}
|
||
className={cn(
|
||
"group/card flex cursor-pointer flex-col gap-2 rounded-xl border p-3 transition-colors",
|
||
isSelected
|
||
? "border-primary/50 bg-primary/5 ring-primary/15 ring-1"
|
||
: "bg-background/60 hover:border-primary/40 hover:bg-accent/40",
|
||
)}
|
||
>
|
||
<div className="flex items-start gap-2.5">
|
||
<div
|
||
className={cn(
|
||
"flex size-9 shrink-0 items-center justify-center rounded-lg text-sm font-semibold",
|
||
isSelected
|
||
? "bg-primary/15 text-primary"
|
||
: "bg-muted text-muted-foreground",
|
||
)}
|
||
>
|
||
{skillInitial(skill)}
|
||
</div>
|
||
<div className="min-w-0 flex-1">
|
||
<div
|
||
className="truncate text-sm font-medium"
|
||
title={skillDisplayLabel(skill)}
|
||
>
|
||
{skillDisplayLabel(skill)}
|
||
</div>
|
||
<p className="text-muted-foreground mt-0.5 line-clamp-2 text-xs leading-relaxed">
|
||
{skill.description?.trim()
|
||
? desensitize(skill.description)
|
||
: "暂无描述"}
|
||
</p>
|
||
</div>
|
||
<Switch
|
||
checked={isSelected}
|
||
onCheckedChange={() => toggle(skill.name)}
|
||
onClick={(e) => e.stopPropagation()}
|
||
aria-label={isSelected ? "禁用技能" : "启用技能"}
|
||
className="shrink-0"
|
||
/>
|
||
</div>
|
||
<div className="flex items-center gap-1.5">
|
||
{skill.category?.trim() && (
|
||
<Badge variant="secondary" className="text-[10px]">
|
||
{skill.category}
|
||
</Badge>
|
||
)}
|
||
{skillSourceLabel(skill) && (
|
||
<Badge variant="outline" className="text-[10px]">
|
||
{skillSourceLabel(skill)}
|
||
</Badge>
|
||
)}
|
||
{isSelected && (
|
||
<Badge className="bg-primary/15 text-primary hover:bg-primary/15 text-[10px]">
|
||
<CheckIcon className="size-2.5" />
|
||
已启用
|
||
</Badge>
|
||
)}
|
||
{onViewDetail && (
|
||
<button
|
||
type="button"
|
||
onClick={(e) => {
|
||
e.stopPropagation();
|
||
onViewDetail(skill.name);
|
||
}}
|
||
title="查看技能详情"
|
||
className="text-muted-foreground hover:text-foreground ml-auto opacity-60 transition-opacity group-hover/card:opacity-100"
|
||
>
|
||
<InfoIcon className="size-3.5" />
|
||
</button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
{/* Footer: selected count + done */}
|
||
<div className="flex shrink-0 items-center justify-between border-t px-5 py-3">
|
||
<span className="text-sm">
|
||
已选 <span className="text-primary font-semibold tabular-nums">{selected.length}</span> 个技能
|
||
</span>
|
||
<Button size="sm" onClick={() => onOpenChange(false)}>
|
||
完成
|
||
</Button>
|
||
</div>
|
||
</SheetContent>
|
||
</Sheet>
|
||
);
|
||
}
|