- 「设置和更多」新增「智能体管理」「技能管理」入口,与定时任务管理同级; 独立的 AdminAgentsPage/AdminSkillsPage 复用 AgentCard/SkillRow, 管理员可查看并编辑/删除所有用户的智能体与技能。 - 后端 /api/agents、/api/skills 增加 ?admin=true 越权列表;agents 端 放宽 _get_editable_or_raise 让管理员可编辑/删除任意智能体;新增 list_all/update_any/delete_any(agents)与 list_all(skills)。 - 新增 AuthSyncWatcher:监听 localStorage["deerflow.auth"] 的 storage 事件,user_id 变化时自动 reload,修复多标签切换登录后老页面点击 「新对话」偶发 404 的问题。 - LLMErrorHandlingMiddleware 将 bad_response_status_code / JSON decode 等上游网关乱码识别为可重试的 upstream 类故障。 - 侧边栏「任务管理」改名为「定时任务」。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
917 lines
32 KiB
TypeScript
917 lines
32 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
AlertCircle,
|
|
ArchiveIcon,
|
|
CheckCircle2,
|
|
ChevronLeftIcon,
|
|
ChevronRightIcon,
|
|
ClockIcon,
|
|
FileArchive,
|
|
GlobeIcon,
|
|
Loader2,
|
|
LockIcon,
|
|
PinIcon,
|
|
PinOffIcon,
|
|
RefreshCwIcon,
|
|
SparklesIcon,
|
|
TagsIcon,
|
|
Trash2Icon,
|
|
TrendingUpIcon,
|
|
Upload,
|
|
} from "lucide-react";
|
|
import { useRouter } from "next/navigation";
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { toast } from "sonner";
|
|
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import {
|
|
Empty,
|
|
EmptyContent,
|
|
EmptyDescription,
|
|
EmptyHeader,
|
|
EmptyMedia,
|
|
EmptyTitle,
|
|
} from "@/components/ui/empty";
|
|
import {
|
|
Item,
|
|
ItemActions,
|
|
ItemTitle,
|
|
ItemContent,
|
|
ItemDescription,
|
|
} from "@/components/ui/item";
|
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
|
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
|
|
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
|
import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog";
|
|
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
|
|
import { getStoredAuth } from "@/core/auth";
|
|
import { useI18n } from "@/core/i18n/hooks";
|
|
import type { ValidateSkillUploadResponse } from "@/core/skills/api";
|
|
import {
|
|
useDeleteCustomSkill,
|
|
useInstallSkillUpload,
|
|
useReconcileCustomSkills,
|
|
useSetSkillPinned,
|
|
useSetSkillPublished,
|
|
useSkills,
|
|
useValidateSkillUpload,
|
|
} from "@/core/skills/hooks";
|
|
import type { Skill } from "@/core/skills/type";
|
|
import { env } from "@/env";
|
|
import { desensitize } from "@/lib/desensitize";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
import { SettingsSection } from "./settings-section";
|
|
import { SkillStateSheet } from "./skill-state-sheet";
|
|
|
|
export function SkillSettingsPage({ onClose }: { onClose?: () => void } = {}) {
|
|
const { t } = useI18n();
|
|
return (
|
|
<SettingsSection
|
|
title={t.settings.skills.title}
|
|
description={t.settings.skills.description}
|
|
>
|
|
<SkillSettingsList onClose={onClose} />
|
|
</SettingsSection>
|
|
);
|
|
}
|
|
|
|
const PAGE_SIZE = 10;
|
|
|
|
function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
|
const { t } = useI18n();
|
|
const router = useRouter();
|
|
const [filter, setFilter] = useState<string>("mine");
|
|
const [installOpen, setInstallOpen] = useState(false);
|
|
const [staleSheetOpen, setStaleSheetOpen] = useState(false);
|
|
const [archiveSheetOpen, setArchiveSheetOpen] = useState(false);
|
|
const [search, setSearch] = useState("");
|
|
const [tagIds, setTagIds] = useState<string[]>([]);
|
|
const [page, setPage] = useState(1);
|
|
const reconcileMutation = useReconcileCustomSkills();
|
|
// Name + tag filtering is resolved server-side via the /api/skills query.
|
|
const { skills, isLoading, error } = useSkills({ search, tagIds });
|
|
|
|
const storedAuth = useMemo(() => getStoredAuth(), []);
|
|
const currentUserId = storedAuth?.user_id ?? null;
|
|
const isAdmin = storedAuth?.system_role === "admin";
|
|
|
|
// 把可见技能分类成 UI 关心的几个桶。
|
|
// "All" = 内置 + 已发布的技能(仅 active 状态);自己的技能也要自己发布了才出现。
|
|
// "Mine" = 严格属于我自己的自定义技能(仅 active 状态)。
|
|
const { activeAll, activeMine, staleVisible, archivedVisible } = useMemo(() => {
|
|
const all: Skill[] = [];
|
|
const mine: Skill[] = [];
|
|
const stale: Skill[] = [];
|
|
const archived: Skill[] = [];
|
|
for (const skill of skills) {
|
|
const state = skill.state ?? "active";
|
|
const isCustom = skill.category === "custom";
|
|
const isOwnedByMe =
|
|
isCustom && !!skill.owner_user_id && skill.owner_user_id === currentUserId;
|
|
const isBuiltin = skill.builtin ?? !skill.owner_user_id;
|
|
|
|
if (state === "stale") {
|
|
stale.push(skill);
|
|
continue;
|
|
}
|
|
if (state === "archived") {
|
|
archived.push(skill);
|
|
continue;
|
|
}
|
|
// state === active
|
|
if (isBuiltin || !!skill.published) {
|
|
all.push(skill);
|
|
}
|
|
if (isOwnedByMe) {
|
|
mine.push(skill);
|
|
}
|
|
}
|
|
return {
|
|
activeAll: all,
|
|
activeMine: mine,
|
|
staleVisible: stale,
|
|
archivedVisible: archived,
|
|
};
|
|
}, [skills, currentUserId]);
|
|
|
|
const filteredSkills = filter === "mine" ? activeMine : activeAll;
|
|
const staleCount = staleVisible.length;
|
|
const archivedCount = archivedVisible.length;
|
|
|
|
const totalPages = Math.max(1, Math.ceil(filteredSkills.length / PAGE_SIZE));
|
|
// Filter / search / tag changes may shrink the result set — pull the page
|
|
// back into range without forcing a reset on every keystroke.
|
|
useEffect(() => {
|
|
if (page > totalPages) setPage(totalPages);
|
|
}, [page, totalPages]);
|
|
const pagedSkills = useMemo(
|
|
() => filteredSkills.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),
|
|
[filteredSkills, page],
|
|
);
|
|
|
|
const handleCreateSkill = () => {
|
|
onClose?.();
|
|
router.push("/?mode=skill");
|
|
};
|
|
|
|
const handleRescan = async () => {
|
|
try {
|
|
const result = await reconcileMutation.mutateAsync();
|
|
if (result.adopted.length > 0) {
|
|
toast.success(
|
|
t.settings.skills.rescanSkillsAdopted.replace(
|
|
"{count}",
|
|
String(result.adopted.length),
|
|
),
|
|
);
|
|
} else {
|
|
toast.info(t.settings.skills.rescanSkillsNoop);
|
|
}
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : String(err));
|
|
}
|
|
};
|
|
return (
|
|
<div className="flex w-full flex-col gap-4">
|
|
<header className="flex flex-wrap items-center justify-between gap-3">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Tabs value={filter} onValueChange={setFilter}>
|
|
<TabsList variant="line">
|
|
<TabsTrigger value="mine">{t.settings.skills.tabMine}</TabsTrigger>
|
|
<TabsTrigger value="all">{t.settings.skills.tabAll}</TabsTrigger>
|
|
</TabsList>
|
|
</Tabs>
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={staleCount === 0}
|
|
onClick={() => setStaleSheetOpen(true)}
|
|
title={t.settings.skills.badgeStaleTitle}
|
|
>
|
|
<ClockIcon className="size-4" />
|
|
{t.settings.skills.entryStale.replace("{count}", String(staleCount))}
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={archivedCount === 0}
|
|
onClick={() => setArchiveSheetOpen(true)}
|
|
title={t.settings.skills.badgeArchivedTitle}
|
|
>
|
|
<ArchiveIcon className="size-4" />
|
|
{t.settings.skills.entryArchived.replace(
|
|
"{count}",
|
|
String(archivedCount),
|
|
)}
|
|
</Button>
|
|
</div>
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
onClick={() => {
|
|
onClose?.();
|
|
router.push("/page/workspace/skills/evolution");
|
|
}}
|
|
>
|
|
<TrendingUpIcon className="size-4" />
|
|
{t.settings.skills.goToEvolution}
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
onClick={() => void handleRescan()}
|
|
disabled={
|
|
reconcileMutation.isPending ||
|
|
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
|
|
}
|
|
title={t.settings.skills.rescanSkills}
|
|
>
|
|
{reconcileMutation.isPending ? (
|
|
<Loader2 className="size-4 animate-spin" />
|
|
) : (
|
|
<RefreshCwIcon className="size-4" />
|
|
)}
|
|
{reconcileMutation.isPending
|
|
? t.settings.skills.rescanSkillsRunning
|
|
: t.settings.skills.rescanSkills}
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
onClick={() => setInstallOpen(true)}
|
|
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
|
|
>
|
|
<Upload className="size-4" />
|
|
{t.settings.skills.installSkill}
|
|
</Button>
|
|
<Button size="sm" onClick={handleCreateSkill}>
|
|
<SparklesIcon className="size-4" />
|
|
{t.settings.skills.createSkill}
|
|
</Button>
|
|
</div>
|
|
</header>
|
|
<TagSearchBar
|
|
targetType="skill"
|
|
onSearchChange={setSearch}
|
|
tagIds={tagIds}
|
|
onTagIdsChange={setTagIds}
|
|
/>
|
|
{isLoading && (
|
|
<div className="text-muted-foreground text-sm">{t.common.loading}</div>
|
|
)}
|
|
{error && <div className="text-destructive text-sm">Error: {error.message}</div>}
|
|
{!isLoading && !error && filteredSkills.length === 0 && (
|
|
<EmptySkill onCreateSkill={handleCreateSkill} />
|
|
)}
|
|
{!isLoading && !error &&
|
|
filteredSkills.length > 0 &&
|
|
pagedSkills.map((skill) => (
|
|
<SkillRow
|
|
key={skill.name}
|
|
skill={skill}
|
|
currentUserId={currentUserId}
|
|
isAdmin={isAdmin}
|
|
/>
|
|
))}
|
|
{!isLoading && !error && totalPages > 1 && (
|
|
<div className="flex items-center justify-end gap-2 pt-1">
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={page <= 1}
|
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
|
>
|
|
<ChevronLeftIcon className="size-4" />
|
|
{t.settings.skills.paginationPrev}
|
|
</Button>
|
|
<span className="text-muted-foreground text-xs">
|
|
{t.settings.skills.paginationPageOf
|
|
.replace("{page}", String(page))
|
|
.replace("{total}", String(totalPages))}
|
|
</span>
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={page >= totalPages}
|
|
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
|
>
|
|
{t.settings.skills.paginationNext}
|
|
<ChevronRightIcon className="size-4" />
|
|
</Button>
|
|
</div>
|
|
)}
|
|
<InstallSkillDialog
|
|
open={installOpen}
|
|
onClose={() => setInstallOpen(false)}
|
|
isAdmin={isAdmin}
|
|
/>
|
|
<SkillStateSheet
|
|
kind="stale"
|
|
open={staleSheetOpen}
|
|
onOpenChange={setStaleSheetOpen}
|
|
skills={staleVisible}
|
|
/>
|
|
<SkillStateSheet
|
|
kind="archived"
|
|
open={archiveSheetOpen}
|
|
onOpenChange={setArchiveSheetOpen}
|
|
skills={archivedVisible}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function SkillRow({
|
|
skill,
|
|
currentUserId,
|
|
isAdmin,
|
|
}: {
|
|
skill: Skill;
|
|
currentUserId: string | null;
|
|
isAdmin: boolean;
|
|
}) {
|
|
const { t } = useI18n();
|
|
const setPublished = useSetSkillPublished();
|
|
const setPinned = useSetSkillPinned();
|
|
const deleteSkill = useDeleteCustomSkill();
|
|
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
|
const [tagPickerOpen, setTagPickerOpen] = useState(false);
|
|
const [detailOpen, setDetailOpen] = useState(false);
|
|
|
|
const isCustom = skill.category === "custom";
|
|
// Built-in flag falls back to "no DB owner" so legacy responses without
|
|
// the multitenancy fields still classify public skills correctly.
|
|
const isBuiltin = skill.builtin ?? !skill.owner_user_id;
|
|
const isOwned =
|
|
isCustom && !isBuiltin && !!skill.owner_user_id && skill.owner_user_id === currentUserId;
|
|
const isFromOthers = isCustom && !isBuiltin && !isOwned;
|
|
// Admin can edit/delete/unpublish anyone's skill; non-admin only their own.
|
|
const canManage = isCustom && (isOwned || isAdmin);
|
|
const canTogglePublish = canManage && !isBuiltin;
|
|
|
|
async function handleTogglePublished(next: boolean) {
|
|
try {
|
|
await setPublished.mutateAsync({ skillName: skill.name, published: next });
|
|
toast.success(
|
|
next
|
|
? t.settings.skills.publishSuccess
|
|
: t.settings.skills.unpublishSuccess,
|
|
);
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : String(err));
|
|
}
|
|
}
|
|
|
|
async function handleDelete() {
|
|
try {
|
|
await deleteSkill.mutateAsync(skill.name);
|
|
toast.success(t.settings.skills.deleteSuccess);
|
|
setConfirmDeleteOpen(false);
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : String(err));
|
|
}
|
|
}
|
|
|
|
async function handleTogglePinned() {
|
|
const next = !skill.pinned;
|
|
try {
|
|
await setPinned.mutateAsync({ skillName: skill.name, pinned: next });
|
|
toast.success(
|
|
next ? t.settings.skills.pinSuccess : t.settings.skills.unpinSuccess,
|
|
);
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : String(err));
|
|
}
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Item className="w-full" variant="outline">
|
|
<ItemContent
|
|
className="cursor-pointer"
|
|
onClick={() => setDetailOpen(true)}
|
|
>
|
|
<ItemTitle>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<span>{desensitize(skill.name)}</span>
|
|
{isBuiltin && (
|
|
<Badge variant="secondary" className="text-xs">
|
|
{t.settings.skills.badgeBuiltin}
|
|
</Badge>
|
|
)}
|
|
{isOwned && (
|
|
<Badge
|
|
variant="default"
|
|
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
|
>
|
|
{t.settings.skills.badgeMine}
|
|
</Badge>
|
|
)}
|
|
{isFromOthers && (
|
|
<Badge
|
|
variant="outline"
|
|
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
|
title={
|
|
skill.owner_user_id
|
|
? t.settings.skills.badgeFromOthersTitle.replace(
|
|
"{user_id}",
|
|
skill.owner_user_id,
|
|
)
|
|
: undefined
|
|
}
|
|
>
|
|
{t.settings.skills.badgeFromOthers}
|
|
</Badge>
|
|
)}
|
|
{isOwned && skill.published && (
|
|
<Badge
|
|
variant="outline"
|
|
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
|
title={t.settings.skills.badgePublishedTitle}
|
|
>
|
|
<GlobeIcon className="size-3" />
|
|
{t.settings.skills.badgePublished}
|
|
</Badge>
|
|
)}
|
|
{isCustom && !isBuiltin && skill.source === "agent" && (
|
|
<Badge
|
|
variant="outline"
|
|
className="border-cyan-500/30 text-cyan-700 dark:text-cyan-300 text-xs"
|
|
title={t.settings.skills.badgeSourceAgentTitle}
|
|
>
|
|
{t.settings.skills.badgeSourceAgent}
|
|
</Badge>
|
|
)}
|
|
{isCustom && !isBuiltin && skill.source === "upload" && (
|
|
<Badge
|
|
variant="outline"
|
|
className="border-zinc-400/40 text-zinc-600 dark:text-zinc-400 text-xs"
|
|
title={t.settings.skills.badgeSourceUploadTitle}
|
|
>
|
|
{t.settings.skills.badgeSourceUpload}
|
|
</Badge>
|
|
)}
|
|
{skill.pinned && (
|
|
<Badge
|
|
variant="outline"
|
|
className="border-purple-500/30 text-purple-700 dark:text-purple-300 text-xs"
|
|
title={t.settings.skills.badgePinnedTitle}
|
|
>
|
|
{t.settings.skills.badgePinned}
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
</ItemTitle>
|
|
<ItemDescription className="line-clamp-4">
|
|
{desensitize(skill.description ?? "")}
|
|
</ItemDescription>
|
|
{skill.use_count !== undefined && (
|
|
<div className="text-muted-foreground mt-1 text-xs">
|
|
{skill.use_count > 0
|
|
? t.settings.skills.useCountInline.replace(
|
|
"{count}",
|
|
String(skill.use_count),
|
|
)
|
|
: t.settings.skills.useCountInlineZero}
|
|
</div>
|
|
)}
|
|
{(skill.tags?.length ?? 0) > 0 && (
|
|
<TagChipList tags={skill.tags!} className="mt-2" />
|
|
)}
|
|
</ItemContent>
|
|
<ItemActions>
|
|
{isAdmin && (
|
|
<Button
|
|
size="icon"
|
|
variant="ghost"
|
|
className="h-8 w-8 shrink-0"
|
|
onClick={() => setTagPickerOpen(true)}
|
|
title={t.adminTags.manageTags}
|
|
>
|
|
<TagsIcon className="size-3.5" />
|
|
</Button>
|
|
)}
|
|
{canManage && (
|
|
<Button
|
|
size="icon"
|
|
variant="ghost"
|
|
className="h-8 w-8 shrink-0"
|
|
disabled={setPinned.isPending}
|
|
onClick={() => void handleTogglePinned()}
|
|
title={
|
|
skill.pinned
|
|
? t.settings.skills.unpinAction
|
|
: t.settings.skills.pinAction
|
|
}
|
|
>
|
|
{skill.pinned ? (
|
|
<PinOffIcon className="size-3.5" />
|
|
) : (
|
|
<PinIcon className="size-3.5" />
|
|
)}
|
|
</Button>
|
|
)}
|
|
{canTogglePublish && (
|
|
<Button
|
|
size="icon"
|
|
variant="ghost"
|
|
className="h-8 w-8 shrink-0"
|
|
disabled={setPublished.isPending}
|
|
onClick={() => void handleTogglePublished(!skill.published)}
|
|
title={
|
|
skill.published
|
|
? t.settings.skills.unpublishAction
|
|
: t.settings.skills.publishAction
|
|
}
|
|
>
|
|
{skill.published ? (
|
|
<LockIcon className="size-3.5" />
|
|
) : (
|
|
<GlobeIcon className="size-3.5" />
|
|
)}
|
|
</Button>
|
|
)}
|
|
{canManage && (
|
|
<Button
|
|
size="icon"
|
|
variant="ghost"
|
|
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
|
onClick={() => setConfirmDeleteOpen(true)}
|
|
title={t.settings.skills.deleteAction}
|
|
>
|
|
<Trash2Icon className="size-3.5" />
|
|
</Button>
|
|
)}
|
|
</ItemActions>
|
|
</Item>
|
|
<Dialog open={confirmDeleteOpen} onOpenChange={setConfirmDeleteOpen}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>{t.settings.skills.deleteAction}</DialogTitle>
|
|
<DialogDescription>
|
|
{desensitize(
|
|
t.settings.skills.deleteConfirm.replace("{name}", skill.name),
|
|
)}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<DialogFooter>
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setConfirmDeleteOpen(false)}
|
|
disabled={deleteSkill.isPending}
|
|
>
|
|
{t.common.cancel}
|
|
</Button>
|
|
<Button
|
|
variant="destructive"
|
|
onClick={() => void handleDelete()}
|
|
disabled={deleteSkill.isPending}
|
|
>
|
|
{deleteSkill.isPending ? t.common.loading : t.common.delete}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
{isAdmin && (
|
|
<TagPickerDialog
|
|
open={tagPickerOpen}
|
|
onOpenChange={setTagPickerOpen}
|
|
targetType="skill"
|
|
targetId={skill.name}
|
|
currentTags={skill.tags ?? []}
|
|
/>
|
|
)}
|
|
<SkillDetailDialog
|
|
skillName={skill.name}
|
|
open={detailOpen}
|
|
onOpenChange={setDetailOpen}
|
|
/>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function EmptySkill({ onCreateSkill }: { onCreateSkill: () => void }) {
|
|
const { t } = useI18n();
|
|
return (
|
|
<Empty>
|
|
<EmptyHeader>
|
|
<EmptyMedia variant="icon">
|
|
<SparklesIcon />
|
|
</EmptyMedia>
|
|
<EmptyTitle>{t.settings.skills.emptyTitle}</EmptyTitle>
|
|
<EmptyDescription>
|
|
{t.settings.skills.emptyDescription}
|
|
</EmptyDescription>
|
|
</EmptyHeader>
|
|
<EmptyContent>
|
|
<Button onClick={onCreateSkill}>{t.settings.skills.emptyButton}</Button>
|
|
</EmptyContent>
|
|
</Empty>
|
|
);
|
|
}
|
|
|
|
function InstallSkillDialog({
|
|
open,
|
|
onClose,
|
|
isAdmin,
|
|
}: {
|
|
open: boolean;
|
|
onClose: () => void;
|
|
isAdmin: boolean;
|
|
}) {
|
|
const { t } = useI18n();
|
|
const dialog = t.settings.skills.installDialog;
|
|
const inputRef = useRef<HTMLInputElement | null>(null);
|
|
const [file, setFile] = useState<File | null>(null);
|
|
const [validation, setValidation] = useState<ValidateSkillUploadResponse | null>(null);
|
|
const [validationError, setValidationError] = useState<string | null>(null);
|
|
const [isDragging, setIsDragging] = useState(false);
|
|
const [targetCategory, setTargetCategory] = useState<"custom" | "public">("custom");
|
|
const validateMutation = useValidateSkillUpload();
|
|
const installMutation = useInstallSkillUpload();
|
|
|
|
const reset = useCallback(() => {
|
|
setFile(null);
|
|
setValidation(null);
|
|
setValidationError(null);
|
|
setIsDragging(false);
|
|
setTargetCategory("custom");
|
|
if (inputRef.current) inputRef.current.value = "";
|
|
}, []);
|
|
|
|
const handleClose = useCallback(() => {
|
|
if (validateMutation.isPending || installMutation.isPending) return;
|
|
reset();
|
|
onClose();
|
|
}, [installMutation.isPending, onClose, reset, validateMutation.isPending]);
|
|
|
|
const acceptFile = useCallback(
|
|
async (selected: File) => {
|
|
const lower = selected.name.toLowerCase();
|
|
if (!lower.endsWith(".zip") && !lower.endsWith(".skill")) {
|
|
toast.error(dialog.rejectInvalidExt);
|
|
return;
|
|
}
|
|
setFile(selected);
|
|
setValidation(null);
|
|
setValidationError(null);
|
|
try {
|
|
const result = await validateMutation.mutateAsync(selected);
|
|
setValidation(result);
|
|
} catch (err) {
|
|
setValidationError(err instanceof Error ? err.message : String(err));
|
|
}
|
|
},
|
|
[dialog.rejectInvalidExt, validateMutation],
|
|
);
|
|
|
|
const onDrop = useCallback(
|
|
(e: React.DragEvent<HTMLDivElement>) => {
|
|
e.preventDefault();
|
|
// Stop the global chat-upload listener on `document` from also receiving this drop.
|
|
// React's stopPropagation alone doesn't reach native document listeners — we need to
|
|
// halt the underlying DOM event too.
|
|
e.stopPropagation();
|
|
e.nativeEvent.stopImmediatePropagation();
|
|
setIsDragging(false);
|
|
const dropped = e.dataTransfer.files?.[0];
|
|
if (dropped) void acceptFile(dropped);
|
|
},
|
|
[acceptFile],
|
|
);
|
|
|
|
const onPick = useCallback(
|
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const picked = e.target.files?.[0];
|
|
if (picked) void acceptFile(picked);
|
|
},
|
|
[acceptFile],
|
|
);
|
|
|
|
const handleInstall = useCallback(
|
|
async (overwrite: boolean) => {
|
|
if (!file) return;
|
|
try {
|
|
const result = await installMutation.mutateAsync({ file, overwrite, targetCategory });
|
|
toast.success(
|
|
(result.overwritten ? dialog.installSuccessReplaced : dialog.installSuccess).replace(
|
|
"{name}",
|
|
result.skill_name,
|
|
),
|
|
);
|
|
reset();
|
|
onClose();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : String(err));
|
|
}
|
|
},
|
|
[dialog.installSuccess, dialog.installSuccessReplaced, file, installMutation, onClose, reset, targetCategory],
|
|
);
|
|
|
|
const isPublicConflict = validation?.conflict && validation.conflict_kind === "public";
|
|
const isCustomConflict = validation?.conflict && validation.conflict_kind === "custom";
|
|
// Admin targeting public directory can overwrite an existing public skill.
|
|
const adminCanOverwritePublic = isAdmin && targetCategory === "public" && !!isPublicConflict;
|
|
const canInstall = !!validation && !validationError && !isCustomConflict && (adminCanOverwritePublic ? false : !isPublicConflict);
|
|
const canOverwrite = !!validation && !validationError && (!!isCustomConflict || adminCanOverwritePublic);
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={(o) => !o && handleClose()}>
|
|
<DialogContent className="max-w-xl">
|
|
<DialogHeader>
|
|
<DialogTitle>{dialog.title}</DialogTitle>
|
|
</DialogHeader>
|
|
<div className="flex flex-col gap-4">
|
|
<div
|
|
onDragOver={(e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
e.nativeEvent.stopImmediatePropagation();
|
|
setIsDragging(true);
|
|
}}
|
|
onDragLeave={() => setIsDragging(false)}
|
|
onDrop={onDrop}
|
|
className={cn(
|
|
"flex flex-col items-center justify-center gap-2 rounded-md border-2 border-dashed p-6 text-center transition-colors",
|
|
isDragging ? "border-primary bg-accent/40" : "border-muted-foreground/30",
|
|
)}
|
|
>
|
|
<FileArchive className="text-muted-foreground size-8" />
|
|
<div className="text-muted-foreground text-sm">
|
|
{dialog.dropHint}
|
|
<button
|
|
type="button"
|
|
className="text-primary ml-1 underline underline-offset-4"
|
|
onClick={() => inputRef.current?.click()}
|
|
>
|
|
{dialog.chooseFile}
|
|
</button>
|
|
</div>
|
|
{file && (
|
|
<div className="text-muted-foreground mt-1 text-xs">
|
|
{file.name} · {(file.size / 1024).toFixed(1)} KB
|
|
</div>
|
|
)}
|
|
<input
|
|
ref={inputRef}
|
|
type="file"
|
|
accept=".zip,.skill,application/zip"
|
|
hidden
|
|
onChange={onPick}
|
|
/>
|
|
</div>
|
|
|
|
{isAdmin && (
|
|
<div className="flex items-center gap-3 text-sm">
|
|
<span className="text-muted-foreground shrink-0">{dialog.targetCategoryLabel}</span>
|
|
<div className="flex gap-4">
|
|
{(["custom", "public"] as const).map((cat) => (
|
|
<label key={cat} className="flex cursor-pointer items-center gap-1.5">
|
|
<input
|
|
type="radio"
|
|
name="targetCategory"
|
|
value={cat}
|
|
checked={targetCategory === cat}
|
|
onChange={() => setTargetCategory(cat)}
|
|
className="accent-primary"
|
|
/>
|
|
<span>{cat === "custom" ? dialog.categoryCustom : dialog.categoryPublic}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{validateMutation.isPending && (
|
|
<div className="text-muted-foreground flex items-center gap-2 text-sm">
|
|
<Loader2 className="size-4 animate-spin" />
|
|
{dialog.validating}
|
|
</div>
|
|
)}
|
|
|
|
{validationError && (
|
|
<div className="text-destructive flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm">
|
|
<AlertCircle className="mt-0.5 size-4 shrink-0" />
|
|
<span>{validationError}</span>
|
|
</div>
|
|
)}
|
|
|
|
{validation && !validationError && (
|
|
<div className="flex flex-col gap-2 rounded-md border p-3 text-sm">
|
|
<div className="flex items-center gap-2 text-emerald-600">
|
|
<CheckCircle2 className="size-4" />
|
|
<span className="font-medium">{desensitize(validation.skill_name)}</span>
|
|
</div>
|
|
<Field label={dialog.descriptionLabel}>
|
|
<span className="line-clamp-3 whitespace-pre-wrap">
|
|
{validation.description ? desensitize(validation.description) : "—"}
|
|
</span>
|
|
</Field>
|
|
{validation.license && (
|
|
<Field label={dialog.licenseLabel}>{desensitize(validation.license)}</Field>
|
|
)}
|
|
{validation.allowed_tools.length > 0 && (
|
|
<Field label={dialog.toolsLabel}>
|
|
<div className="flex flex-wrap gap-1">
|
|
{validation.allowed_tools.map((tool) => (
|
|
<Badge key={tool} variant="secondary" className="text-xs">
|
|
{desensitize(tool)}
|
|
</Badge>
|
|
))}
|
|
</div>
|
|
</Field>
|
|
)}
|
|
{validation.warnings.length > 0 && (
|
|
<Field label={dialog.warningsLabel}>
|
|
<ul className="list-disc pl-4 text-xs">
|
|
{validation.warnings.map((w, idx) => (
|
|
<li key={idx}>{desensitize(w)}</li>
|
|
))}
|
|
</ul>
|
|
</Field>
|
|
)}
|
|
{isCustomConflict && (
|
|
<div className="text-amber-600 mt-1 flex items-start gap-2 text-xs">
|
|
<AlertCircle className="mt-0.5 size-3.5 shrink-0" />
|
|
<span>
|
|
{desensitize(
|
|
dialog.conflictCustom.replace("{name}", validation.skill_name),
|
|
)}
|
|
</span>
|
|
</div>
|
|
)}
|
|
{isPublicConflict && (
|
|
<div className={cn("mt-1 flex items-start gap-2 text-xs", adminCanOverwritePublic ? "text-amber-600" : "text-destructive")}>
|
|
<AlertCircle className="mt-0.5 size-3.5 shrink-0" />
|
|
<span>
|
|
{desensitize(
|
|
(adminCanOverwritePublic ? dialog.conflictPublicAdminHint : dialog.conflictPublic).replace("{name}", validation.skill_name),
|
|
)}
|
|
</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
<DialogFooter>
|
|
<Button
|
|
variant="outline"
|
|
onClick={handleClose}
|
|
disabled={installMutation.isPending}
|
|
>
|
|
{dialog.cancel}
|
|
</Button>
|
|
{canOverwrite && (
|
|
<Button
|
|
variant="destructive"
|
|
onClick={() => handleInstall(true)}
|
|
disabled={installMutation.isPending}
|
|
>
|
|
{installMutation.isPending && (
|
|
<Loader2 className="size-4 animate-spin" />
|
|
)}
|
|
{dialog.replace}
|
|
</Button>
|
|
)}
|
|
<Button
|
|
onClick={() => handleInstall(false)}
|
|
disabled={!canInstall || installMutation.isPending}
|
|
>
|
|
{installMutation.isPending && (
|
|
<Loader2 className="size-4 animate-spin" />
|
|
)}
|
|
{installMutation.isPending ? dialog.installing : dialog.install}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
function Field({
|
|
label,
|
|
children,
|
|
}: {
|
|
label: string;
|
|
children: React.ReactNode;
|
|
}) {
|
|
return (
|
|
<div className="grid grid-cols-[80px_1fr] gap-2">
|
|
<span className="text-muted-foreground shrink-0 text-xs">{label}</span>
|
|
<div className="min-w-0">{children}</div>
|
|
</div>
|
|
);
|
|
}
|