调整目录

This commit is contained in:
mlogclub
2026-04-24 12:01:30 +08:00
parent 7889ecb0d2
commit a9275c2d4a
209 changed files with 0 additions and 0 deletions
@@ -0,0 +1,558 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useMemo, useState } from "react"
import { Resolver, useForm } from "react-hook-form"
import { z } from "zod/v4"
import { LoaderCircleIcon, PlayIcon } from "lucide-react"
import { toast } from "sonner"
import { ProjectDialog } from "@/components/project-dialog"
import { OptionCombobox } from "@/components/option-combobox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
Field,
FieldContent,
FieldError,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
debugResumeSkillDefinition,
debugRunSkillDefinition,
fetchAIAgentsAll,
type AIAgent,
type SkillDebugResumePayload,
type SkillDebugRunPayload,
type SkillDebugRunResult,
} from "@/lib/api/admin"
type DebugDialogProps = {
open: boolean
skillCode: string
skillName: string
onOpenChange: (open: boolean) => void
}
const debugFormSchema = z.object({
aiAgentId: z.string().trim().min(1, "请选择 AI Agent"),
conversationId: z.string().trim(),
userMessage: z.string().trim().min(1, "请输入用户消息"),
})
type DebugForm = z.infer<typeof debugFormSchema>
const debugFormResolver = zodResolver(debugFormSchema as never) as Resolver<
z.input<typeof debugFormSchema>,
undefined,
z.output<typeof debugFormSchema>
>
const emptyForm: DebugForm = {
aiAgentId: "",
conversationId: "",
userMessage: "",
}
const quickResumeActions = [
{ label: "确认", value: "确认" },
{ label: "取消", value: "取消" },
]
function ResultBlock({
title,
value,
emptyText = "暂无数据",
}: {
title: string
value?: string
emptyText?: string
}) {
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm">{title}</CardTitle>
</CardHeader>
<CardContent>
{value ? (
<pre className="overflow-x-auto whitespace-pre-wrap break-words rounded-lg bg-muted/50 p-3 text-xs leading-5">
{value}
</pre>
) : (
<div className="text-sm text-muted-foreground">{emptyText}</div>
)}
</CardContent>
</Card>
)
}
export function DebugDialog({
open,
skillCode,
skillName,
onOpenChange,
}: DebugDialogProps) {
if (!open) {
return null
}
return (
<DebugDialogBody
key={skillCode}
open={open}
skillCode={skillCode}
skillName={skillName}
onOpenChange={onOpenChange}
/>
)
}
function DebugDialogBody({
open,
skillCode,
skillName,
onOpenChange,
}: DebugDialogProps) {
const formId = `skill-debug-form-${skillCode}`
const [running, setRunning] = useState(false)
const [resuming, setResuming] = useState(false)
const [aiAgents, setAiAgents] = useState<AIAgent[]>([])
const [result, setResult] = useState<SkillDebugRunResult | null>(null)
const [resumeResult, setResumeResult] = useState<SkillDebugRunResult | null>(null)
const [resumeMessage, setResumeMessage] = useState("")
const form = useForm<
z.input<typeof debugFormSchema>,
undefined,
z.output<typeof debugFormSchema>
>({
resolver: debugFormResolver,
defaultValues: emptyForm,
})
const {
handleSubmit,
reset,
register,
setValue,
watch,
formState: { errors },
} = form
const selectedAgentId = watch("aiAgentId")
useEffect(() => {
async function loadAIAgents() {
try {
const data = await fetchAIAgentsAll({ status: 1 })
setAiAgents(data)
} catch (error) {
console.error("Failed to load AI agents:", error)
}
}
void loadAIAgents()
}, [])
useEffect(() => {
if (!open) {
return
}
reset(emptyForm)
setResult(null)
setResumeResult(null)
setResumeMessage("")
}, [open, reset])
useEffect(() => {
if (!open || aiAgents.length === 0 || selectedAgentId) {
return
}
setValue("aiAgentId", String(aiAgents[0].id), { shouldValidate: true })
}, [aiAgents, open, selectedAgentId, setValue])
const aiAgentOptions = useMemo(
() =>
aiAgents.map((item) => ({
value: String(item.id),
label: item.name,
})),
[aiAgents],
)
const selectedAgent = useMemo(
() => aiAgents.find((item) => String(item.id) === selectedAgentId) ?? null,
[aiAgents, selectedAgentId],
)
async function onSubmit(values: DebugForm) {
const payload: SkillDebugRunPayload = {
aiAgentId: Number(values.aiAgentId),
skillCode,
userMessage: values.userMessage.trim(),
}
const conversationId = Number(values.conversationId)
if (conversationId > 0) {
payload.conversationId = conversationId
}
setRunning(true)
try {
const data = await debugRunSkillDefinition(payload)
setResult(data)
setResumeResult(null)
setResumeMessage("")
} catch (error) {
toast.error(error instanceof Error ? error.message : "Skill 调试失败")
setResult(null)
} finally {
setRunning(false)
}
}
async function handleResumeDebug(messageText?: string) {
const nextMessage = (messageText ?? resumeMessage).trim()
if (!result?.checkPointId || !result.interrupted) {
return
}
if (!nextMessage) {
toast.error("请输入恢复消息")
return
}
const payload: SkillDebugResumePayload = {
aiAgentId: Number(selectedAgentId || result.aiAgentId),
checkPointId: result.checkPointId,
userMessage: nextMessage,
}
const conversationId = result.conversationId || Number(watch("conversationId"))
if (conversationId > 0) {
payload.conversationId = conversationId
}
setResuming(true)
try {
const data = await debugResumeSkillDefinition(payload)
setResumeResult(data)
setResumeMessage(nextMessage)
} catch (error) {
toast.error(error instanceof Error ? error.message : "恢复调试失败")
setResumeResult(null)
} finally {
setResuming(false)
}
}
return (
<ProjectDialog
open={open}
onOpenChange={onOpenChange}
title={`调试 Skill · ${skillName || skillCode}`}
description="强制指定当前 Skill,直接查看 route、tools、graph、HITL 和回复结果。"
size="xl"
allowFullscreen
footer={
<>
<Button
type="button"
variant="outline"
disabled={running}
onClick={() => onOpenChange(false)}
>
</Button>
<Button type="submit" form={formId} disabled={running}>
{running ? <LoaderCircleIcon className="animate-spin" /> : <PlayIcon />}
{running ? "调试中..." : "开始调试"}
</Button>
</>
}
>
<div className="space-y-6">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm"></CardTitle>
</CardHeader>
<CardContent>
<form id={formId} onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Field data-invalid={!!errors.aiAgentId}>
<FieldLabel>AI Agent</FieldLabel>
<FieldContent>
<OptionCombobox
value={selectedAgentId}
options={aiAgentOptions}
placeholder="选择 AI Agent"
searchPlaceholder="搜索 AI Agent"
emptyText="未找到 AI Agent"
onChange={(value) =>
setValue("aiAgentId", value, { shouldValidate: true })
}
/>
<FieldError errors={[errors.aiAgentId]} />
</FieldContent>
</Field>
<Field data-invalid={!!errors.conversationId}>
<FieldLabel htmlFor="skill-debug-conversation-id">
Conversation ID
</FieldLabel>
<FieldContent>
<Input
id="skill-debug-conversation-id"
type="number"
min={0}
placeholder="可选,填已有会话 ID 以复用上下文"
aria-invalid={!!errors.conversationId}
{...register("conversationId")}
/>
<FieldError errors={[errors.conversationId]} />
</FieldContent>
</Field>
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Field>
<FieldLabel>Skill</FieldLabel>
<FieldContent>
<Input value={skillCode} disabled />
</FieldContent>
</Field>
<Field>
<FieldLabel> Agent</FieldLabel>
<FieldContent>
<Input
value={selectedAgent?.name || "未选择"}
disabled
/>
</FieldContent>
</Field>
</div>
<Field data-invalid={!!errors.userMessage}>
<FieldLabel htmlFor="skill-debug-user-message"></FieldLabel>
<FieldContent>
<Textarea
id="skill-debug-user-message"
rows={5}
placeholder="输入一段用户消息,调试当前 Skill 的路由、工具和回复。"
aria-invalid={!!errors.userMessage}
{...register("userMessage")}
/>
<FieldError errors={[errors.userMessage]} />
</FieldContent>
</Field>
</form>
</CardContent>
</Card>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm"></CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="flex flex-wrap gap-2">
<Badge variant="outline">{result?.skillCode || skillCode}</Badge>
{result?.graphToolCode ? (
<Badge variant="secondary">{result.graphToolCode}</Badge>
) : null}
{result?.interruptType ? (
<Badge variant="secondary">{result.interruptType}</Badge>
) : null}
{result?.interrupted ? (
<Badge></Badge>
) : (
<Badge variant="outline"></Badge>
)}
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground">Skill </div>
<div className="mt-1 font-medium">{result?.skillName || skillName}</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground">Plan Reason</div>
<div className="mt-1 whitespace-pre-wrap break-words">
{result?.planReason || "暂无"}
</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground">Reply</div>
<div className="mt-1 whitespace-pre-wrap break-words">
{result?.replyText || "暂无"}
</div>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground">Checkpoint</div>
<div className="mt-1 break-all">
{result?.checkPointId || "暂无"}
</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"></div>
<div className="mt-1 whitespace-pre-wrap break-words">
{result?.errorMessage || "暂无"}
</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm"></CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"></div>
<div className="mt-2 flex flex-wrap gap-2">
{(result?.toolWhitelist ?? []).length > 0 ? (
result?.toolWhitelist.map((toolCode) => (
<Badge key={toolCode} variant="outline">
{toolCode}
</Badge>
))
) : (
<span className="text-muted-foreground"></span>
)}
</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"></div>
<div className="mt-2 flex flex-wrap gap-2">
{(result?.exposedToolCodes ?? []).length > 0 ? (
result?.exposedToolCodes.map((toolCode) => (
<Badge key={toolCode} variant="outline">
{toolCode}
</Badge>
))
) : (
<span className="text-muted-foreground"></span>
)}
</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"></div>
<div className="mt-2 flex flex-wrap gap-2">
{(result?.invokedToolCodes ?? []).length > 0 ? (
result?.invokedToolCodes.map((toolCode) => (
<Badge key={toolCode} variant="secondary">
{toolCode}
</Badge>
))
) : (
<span className="text-muted-foreground"></span>
)}
</div>
</div>
</CardContent>
</Card>
</div>
<div className="grid grid-cols-1 gap-4">
<ResultBlock title="Skill Route Trace" value={result?.skillRouteTrace} />
<ResultBlock title="Tool Search Trace" value={result?.toolSearchTrace} />
<ResultBlock title="Graph Tool Trace" value={result?.graphToolTrace} />
<ResultBlock title="Trace Data" value={result?.traceData} />
</div>
{result?.interrupted && result.checkPointId ? (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm"></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="rounded-lg bg-muted/50 p-3 text-sm">
<div className="text-xs text-muted-foreground"> Checkpoint</div>
<div className="mt-1 break-all">{result.checkPointId}</div>
</div>
<Field>
<FieldLabel htmlFor="skill-debug-resume-message"></FieldLabel>
<FieldContent>
<Textarea
id="skill-debug-resume-message"
rows={3}
placeholder="输入确认、取消或其他恢复消息"
value={resumeMessage}
onChange={(event) => setResumeMessage(event.target.value)}
/>
</FieldContent>
</Field>
<div className="flex flex-wrap gap-2">
{quickResumeActions.map((item) => (
<Button
key={item.value}
type="button"
variant="outline"
disabled={resuming}
onClick={() => void handleResumeDebug(item.value)}
>
{item.label}
</Button>
))}
<Button
type="button"
disabled={resuming}
onClick={() => void handleResumeDebug()}
>
{resuming ? (
<LoaderCircleIcon className="animate-spin" />
) : (
<PlayIcon />
)}
{resuming ? "恢复中..." : "恢复调试"}
</Button>
</div>
</CardContent>
</Card>
) : null}
{resumeResult ? (
<div className="space-y-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm"></CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="flex flex-wrap gap-2">
<Badge variant="outline">{resumeResult.skillCode || skillCode}</Badge>
{resumeResult.graphToolCode ? (
<Badge variant="secondary">{resumeResult.graphToolCode}</Badge>
) : null}
{resumeResult.interruptType ? (
<Badge variant="secondary">{resumeResult.interruptType}</Badge>
) : null}
{resumeResult.interrupted ? (
<Badge></Badge>
) : (
<Badge variant="outline"></Badge>
)}
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"></div>
<div className="mt-1 whitespace-pre-wrap break-words">
{resumeMessage || "暂无"}
</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"></div>
<div className="mt-1 whitespace-pre-wrap break-words">
{resumeResult.replyText || "暂无"}
</div>
</div>
<div className="rounded-lg bg-muted/50 p-3">
<div className="text-xs text-muted-foreground"> Plan Reason</div>
<div className="mt-1 whitespace-pre-wrap break-words">
{resumeResult.planReason || "暂无"}
</div>
</div>
</CardContent>
</Card>
<ResultBlock title="恢复 Tool Search Trace" value={resumeResult.toolSearchTrace} />
<ResultBlock title="恢复 Graph Tool Trace" value={resumeResult.graphToolTrace} />
<ResultBlock title="恢复 Trace Data" value={resumeResult.traceData} />
</div>
) : null}
</div>
</ProjectDialog>
)
}
@@ -0,0 +1,402 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useMemo, useState } from "react";
import { Resolver, useForm } from "react-hook-form";
import { z } from "zod/v4";
import { OptionCombobox } from "@/components/option-combobox";
import { ProjectDialog } from "@/components/project-dialog";
import { Button } from "@/components/ui/button";
import {
Field,
FieldContent,
FieldError,
FieldLabel,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
fetchMCPCatalog,
fetchSkillDefinition,
type CreateSkillDefinitionPayload,
type MCPToolCatalogItem,
type SkillDefinition,
} from "@/lib/api/admin";
type SkillEditDialogProps = {
open: boolean;
saving: boolean;
itemId: number | null;
onOpenChange: (open: boolean) => void;
onSubmit: (payload: CreateSkillDefinitionPayload) => Promise<void>;
};
const emptyForm: EditForm = {
code: "",
name: "",
description: "",
instruction: "",
examplesText: "",
remark: "",
};
const skillFormSchema = z.object({
code: z
.string()
.trim()
.min(1, "Skill 编码不能为空")
.regex(/^[a-zA-Z0-9_-]+$/, "Skill 编码仅支持字母、数字、下划线和中划线"),
name: z.string().trim().min(1, "Skill 名称不能为空"),
description: z.string().trim(),
instruction: z.string().trim().min(1, "技能说明不能为空"),
examplesText: z.string().trim(),
remark: z.string().trim(),
});
type EditForm = z.infer<typeof skillFormSchema>;
const editFormResolver = zodResolver(skillFormSchema as never) as Resolver<
z.input<typeof skillFormSchema>,
undefined,
z.output<typeof skillFormSchema>
>;
function buildForm(item: SkillDefinition | null): EditForm {
if (!item) {
return emptyForm;
}
return {
code: item.code,
name: item.name,
description: item.description ?? "",
instruction: item.instruction ?? "",
examplesText: (item.examples ?? []).join("\n"),
remark: item.remark ?? "",
};
}
function buildPayload(
form: EditForm,
toolWhitelist: string[],
): CreateSkillDefinitionPayload {
return {
code: form.code.trim(),
name: form.name.trim(),
description: form.description.trim(),
instruction: form.instruction.trim(),
examples: form.examplesText
.split("\n")
.map((item) => item.trim())
.filter(Boolean),
toolWhitelist,
remark: form.remark.trim(),
};
}
export function EditDialog({
open,
saving,
itemId,
onOpenChange,
onSubmit,
}: SkillEditDialogProps) {
if (!open) {
return null;
}
return (
<SkillEditDialogBody
key={itemId ? `edit-${itemId}` : "create"}
open={open}
saving={saving}
itemId={itemId}
onOpenChange={onOpenChange}
onSubmit={onSubmit}
/>
);
}
type SkillEditDialogBodyProps = SkillEditDialogProps;
function SkillEditDialogBody({
open,
saving,
itemId,
onOpenChange,
onSubmit,
}: SkillEditDialogBodyProps) {
const formId = "skill-definition-edit-form";
const [loading, setLoading] = useState(false);
const [toolCatalog, setToolCatalog] = useState<MCPToolCatalogItem[]>([]);
const [selectedToolWhitelist, setSelectedToolWhitelist] = useState<
string[]
>([]);
const [toolCodeToAdd, setToolCodeToAdd] = useState("");
const form = useForm<
z.input<typeof skillFormSchema>,
undefined,
z.output<typeof skillFormSchema>
>({
resolver: editFormResolver,
defaultValues: emptyForm,
});
const {
handleSubmit,
reset,
register,
formState: { errors },
} = form;
useEffect(() => {
async function loadDetail() {
if (!itemId) {
reset(emptyForm);
setSelectedToolWhitelist([]);
setToolCodeToAdd("");
return;
}
setLoading(true);
try {
const data = await fetchSkillDefinition(itemId);
reset(buildForm(data));
setSelectedToolWhitelist(data.toolWhitelist ?? []);
setToolCodeToAdd("");
} catch (error) {
console.error("Failed to load skill definition:", error);
} finally {
setLoading(false);
}
}
void loadDetail();
}, [itemId, reset]);
useEffect(() => {
async function loadToolCatalog() {
try {
const data = await fetchMCPCatalog();
setToolCatalog(data);
} catch (error) {
console.error("Failed to load MCP tool catalog:", error);
}
}
void loadToolCatalog();
}, []);
async function onFormSubmit(values: EditForm) {
await onSubmit(buildPayload(values, selectedToolWhitelist));
}
const toolOptions = useMemo(
() =>
toolCatalog.map((item) => ({
value: item.toolCode,
label: `${item.title || item.toolName} · ${item.toolCode}`,
})),
[toolCatalog],
);
const addableToolOptions = useMemo(
() =>
toolOptions.filter(
(option) => !selectedToolWhitelist.includes(option.value),
),
[selectedToolWhitelist, toolOptions],
);
const selectedToolOptions = useMemo(
() =>
selectedToolWhitelist
.map((toolCode) => toolOptions.find((option) => option.value === toolCode))
.filter(
(option): option is { value: string; label: string } => !!option,
),
[selectedToolWhitelist, toolOptions],
);
function handleAddToolWhitelist(toolCode: string) {
if (!toolCode || selectedToolWhitelist.includes(toolCode)) {
return;
}
setSelectedToolWhitelist((prev) => [...prev, toolCode]);
setToolCodeToAdd("");
}
function handleRemoveToolWhitelist(toolCode: string) {
setSelectedToolWhitelist((prev) =>
prev.filter((item) => item !== toolCode),
);
}
return (
<ProjectDialog
open={open}
onOpenChange={onOpenChange}
title={itemId ? "编辑" : "新建"}
size="xl"
allowFullscreen
footer={
<>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={saving}
>
</Button>
<Button type="submit" form={formId} disabled={saving || loading}>
{saving ? "保存中..." : itemId ? "保存" : "创建"}
</Button>
</>
}
>
{loading ? (
<div className="flex items-center justify-center py-12">
<div className="text-muted-foreground">...</div>
</div>
) : (
<form
id={formId}
onSubmit={handleSubmit(onFormSubmit)}
className="space-y-4"
>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Field data-invalid={!!errors.code}>
<FieldLabel htmlFor="skill-code"></FieldLabel>
<FieldContent>
<Input
id="skill-code"
placeholder="例如:refund_skill"
aria-invalid={!!errors.code}
{...register("code")}
/>
<FieldError errors={[errors.code]} />
</FieldContent>
</Field>
<Field data-invalid={!!errors.name}>
<FieldLabel htmlFor="skill-name"></FieldLabel>
<FieldContent>
<Input
id="skill-name"
placeholder="例如:退款处理"
aria-invalid={!!errors.name}
{...register("name")}
/>
<FieldError errors={[errors.name]} />
</FieldContent>
</Field>
</div>
<Field data-invalid={!!errors.description}>
<FieldLabel htmlFor="skill-description"></FieldLabel>
<FieldContent>
<Textarea
id="skill-description"
rows={3}
placeholder="描述这个 Skill 的用途、边界和适用场景"
aria-invalid={!!errors.description}
{...register("description")}
/>
<FieldError errors={[errors.description]} />
</FieldContent>
</Field>
<Field data-invalid={!!errors.instruction}>
<FieldLabel htmlFor="skill-instruction"></FieldLabel>
<FieldContent>
<Textarea
id="skill-instruction"
rows={12}
placeholder="请输入 Skill 文档内容,描述目标、步骤、工具使用规则和边界。"
aria-invalid={!!errors.instruction}
{...register("instruction")}
/>
<FieldError errors={[errors.instruction]} />
</FieldContent>
</Field>
<Field data-invalid={!!errors.examplesText}>
<FieldLabel htmlFor="skill-examples"></FieldLabel>
<FieldContent>
<Textarea
id="skill-examples"
rows={5}
placeholder={"每行一个典型用户问法,例如:\n我要申请退款\n帮我查下订单"}
aria-invalid={!!errors.examplesText}
{...register("examplesText")}
/>
<FieldError errors={[errors.examplesText]} />
</FieldContent>
</Field>
<Field>
<FieldLabel></FieldLabel>
<FieldContent className="space-y-3">
<div className="flex items-center gap-2">
<div className="flex-1">
<OptionCombobox
value={toolCodeToAdd}
options={addableToolOptions}
placeholder="选择该 Skill 允许使用的工具"
searchPlaceholder="搜索 toolCode 或工具名"
emptyText="没有可添加的工具"
onChange={handleAddToolWhitelist}
/>
</div>
<Button
type="button"
variant="outline"
disabled={!toolCodeToAdd}
onClick={() => handleAddToolWhitelist(toolCodeToAdd)}
>
</Button>
</div>
<div className="flex flex-wrap gap-2">
{selectedToolOptions.length === 0 ? (
<span className="text-sm text-muted-foreground">
Skill Agent
</span>
) : (
selectedToolOptions.map((option) => (
<Button
key={option.value}
type="button"
variant="outline"
size="sm"
onClick={() => handleRemoveToolWhitelist(option.value)}
className="justify-start"
>
{option.label}
</Button>
))
)}
</div>
</FieldContent>
</Field>
<Field data-invalid={!!errors.remark}>
<FieldLabel htmlFor="skill-remark"></FieldLabel>
<FieldContent>
<Textarea
id="skill-remark"
rows={3}
placeholder="记录内部备注或维护说明"
aria-invalid={!!errors.remark}
{...register("remark")}
/>
<FieldError errors={[errors.remark]} />
</FieldContent>
</Field>
</form>
)}
</ProjectDialog>
);
}
+473
View File
@@ -0,0 +1,473 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import {
BrainCircuitIcon,
BugIcon,
MoreHorizontalIcon,
PlusIcon,
RefreshCwIcon,
RotateCcwIcon,
SearchIcon,
Trash2Icon,
} from "lucide-react"
import { toast } from "sonner"
import { ListPagination } from "@/components/list-pagination"
import { OptionCombobox } from "@/components/option-combobox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
createSkillDefinition,
deleteSkillDefinition,
fetchSkillDefinitions,
restoreSkillDefinition,
updateSkillDefinition,
updateSkillDefinitionStatus,
type CreateSkillDefinitionPayload,
type PageResult,
type SkillDefinition,
} from "@/lib/api/admin"
import { Status, StatusLabels } from "@/lib/generated/enums"
import { getEnumLabel, getEnumOptions } from "@/lib/enums"
import { formatDateTime } from "@/lib/utils"
import { EditDialog } from "./_components/edit"
import { DebugDialog } from "./_components/debug-dialog"
const statusFilterOptions = [
{ value: "all", label: "全部状态" },
...getEnumOptions(StatusLabels).map((option) => ({
value: String(option.value),
label: option.label,
})),
]
type SkillRowProps = {
item: SkillDefinition
actionLoadingId: number | null
openEditDialog: (item: SkillDefinition) => void
openDebugDialog: (item: SkillDefinition) => void
handleToggleStatus: (item: SkillDefinition) => void
handleDelete: (item: SkillDefinition) => void
handleRestore: (item: SkillDefinition) => void
}
function SkillRow({
item,
actionLoadingId,
openEditDialog,
openDebugDialog,
handleToggleStatus,
handleDelete,
handleRestore,
}: SkillRowProps) {
const isDeleted = item.status === Status.Deleted
const statusBadgeVariant = isDeleted
? "destructive"
: item.status === Status.Ok
? "default"
: "outline"
return (
<TableRow className={isDeleted ? "bg-destructive/5" : undefined}>
<TableCell>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex size-10 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
<BrainCircuitIcon className="size-4" />
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<div className="font-medium">{item.name}</div>
<Badge variant="outline">{item.code}</Badge>
<Badge variant="secondary"> {item.toolWhitelist.length}</Badge>
<Badge variant="secondary"> {item.examples.length}</Badge>
</div>
<div className="mt-2 space-y-2">
<div className="line-clamp-2 text-sm leading-6 text-muted-foreground">
{item.description || "暂无描述"}
</div>
</div>
{item.toolWhitelist.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2">
{item.toolWhitelist.slice(0, 3).map((toolCode) => (
<Badge key={toolCode} variant="outline">
{toolCode}
</Badge>
))}
{item.toolWhitelist.length > 3 ? (
<Badge variant="outline">+{item.toolWhitelist.length - 3}</Badge>
) : null}
</div>
) : null}
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<Switch
checked={item.status === Status.Ok}
disabled={actionLoadingId === item.id || isDeleted}
onCheckedChange={() => void handleToggleStatus(item)}
aria-label={`${item.name} 状态切换`}
/>
<Badge variant={statusBadgeVariant}>
{getEnumLabel(StatusLabels, item.status as keyof typeof StatusLabels)}
</Badge>
</div>
</TableCell>
<TableCell>
<div className="space-y-1 text-sm">
<div>{formatDateTime(item.updatedAt)}</div>
<div className="text-xs text-muted-foreground">
{item.updateUserName || "-"}
</div>
</div>
</TableCell>
<TableCell className="text-right">
<ButtonGroup className="ml-auto">
<Button variant="outline" size="sm" onClick={() => openDebugDialog(item)}>
<BugIcon />
</Button>
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="icon-sm" />}
aria-label={`更多操作 ${item.name}`}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-40">
{isDeleted ? (
<DropdownMenuItem
disabled={actionLoadingId === item.id}
onClick={() => void handleRestore(item)}
>
<RotateCcwIcon />
{actionLoadingId === item.id ? "恢复中..." : "恢复"}
</DropdownMenuItem>
) : (
<DropdownMenuItem
disabled={actionLoadingId === item.id}
onClick={() => void handleDelete(item)}
className="text-destructive focus:text-destructive"
>
<Trash2Icon />
{actionLoadingId === item.id ? "删除中..." : "删除"}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
)
}
export default function DashboardSkillsPage() {
const [nameInput, setNameInput] = useState("")
const [codeInput, setCodeInput] = useState("")
const [statusFilterInput, setStatusFilterInput] = useState("all")
const [name, setName] = useState("")
const [code, setCode] = useState("")
const [statusFilter, setStatusFilter] = useState("all")
const [page, setPage] = useState(1)
const [limit, setLimit] = useState(20)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [debugDialogOpen, setDebugDialogOpen] = useState(false)
const [editingItem, setEditingItem] = useState<SkillDefinition | null>(null)
const [debuggingItem, setDebuggingItem] = useState<SkillDefinition | null>(null)
const [result, setResult] = useState<PageResult<SkillDefinition>>({
results: [],
page: { page: 1, limit: 20, total: 0 },
})
const loadData = useCallback(async () => {
setLoading(true)
try {
const data = await fetchSkillDefinitions({
name: name.trim() || undefined,
code: code.trim() || undefined,
status: statusFilter === "all" ? undefined : Number(statusFilter),
page,
limit,
})
setResult(data)
} catch (error) {
toast.error(error instanceof Error ? error.message : "加载 Skills 失败")
} finally {
setLoading(false)
}
}, [name, code, statusFilter, page, limit])
useEffect(() => {
void loadData()
}, [loadData])
function applyFilters() {
setName(nameInput)
setCode(codeInput)
setStatusFilter(statusFilterInput)
setPage(1)
}
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
if (event.key !== "Enter") {
return
}
event.preventDefault()
applyFilters()
}
function handlePageChange(nextPage: number) {
if (nextPage < 1 || nextPage === page) {
return
}
setPage(nextPage)
}
function openCreateDialog() {
setEditingItem(null)
setDialogOpen(true)
}
function openEditDialog(item: SkillDefinition) {
setEditingItem(item)
setDialogOpen(true)
}
function openDebugDialog(item: SkillDefinition) {
setDebuggingItem(item)
setDebugDialogOpen(true)
}
function handleDialogOpenChange(open: boolean) {
if (saving) {
return
}
if (!open) {
setEditingItem(null)
}
setDialogOpen(open)
}
function handleDebugDialogOpenChange(open: boolean) {
if (!open) {
setDebuggingItem(null)
}
setDebugDialogOpen(open)
}
async function handleSubmit(payload: CreateSkillDefinitionPayload) {
if (saving) {
return
}
setSaving(true)
try {
if (editingItem) {
await updateSkillDefinition({
id: editingItem.id,
...payload,
})
toast.success(`已更新 Skill${editingItem.name}`)
} else {
await createSkillDefinition(payload)
toast.success(`已创建 Skill${payload.name}`)
}
setDialogOpen(false)
setEditingItem(null)
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存 Skill 失败")
} finally {
setSaving(false)
}
}
async function handleToggleStatus(item: SkillDefinition) {
if (item.status === Status.Deleted) {
return
}
const nextStatus = item.status === Status.Ok ? Status.Disabled : Status.Ok
setActionLoadingId(item.id)
try {
await updateSkillDefinitionStatus(item.id, nextStatus)
toast.success(`${nextStatus === Status.Ok ? "启用" : "停用"}${item.name}`)
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : "更新状态失败")
} finally {
setActionLoadingId(null)
}
}
async function handleDelete(item: SkillDefinition) {
if (item.status === Status.Deleted) {
return
}
setActionLoadingId(item.id)
try {
await deleteSkillDefinition(item.id)
toast.success(`已删除 Skill${item.name}`)
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : "删除 Skill 失败")
} finally {
setActionLoadingId(null)
}
}
async function handleRestore(item: SkillDefinition) {
if (item.status !== Status.Deleted) {
return
}
setActionLoadingId(item.id)
try {
await restoreSkillDefinition(item.id)
toast.success(`已恢复 Skill${item.name}`)
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : "恢复 Skill 失败")
} finally {
setActionLoadingId(null)
}
}
return (
<>
<div className="flex flex-1 flex-col gap-6 p-4 lg:p-6">
<div className="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-end">
<div className="relative min-w-72">
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={nameInput}
onChange={(event) => setNameInput(event.target.value)}
onKeyDown={handleFilterKeyDown}
placeholder="按名称筛选"
className="pl-9"
/>
</div>
<Input
value={codeInput}
onChange={(event) => setCodeInput(event.target.value)}
onKeyDown={handleFilterKeyDown}
placeholder="按编码筛选"
className="w-full xl:w-56"
/>
<div className="w-full xl:w-36">
<OptionCombobox
value={statusFilterInput}
options={statusFilterOptions}
placeholder="全部状态"
searchPlaceholder="搜索状态"
emptyText="未找到状态"
onChange={setStatusFilterInput}
/>
</div>
<Button variant="outline" onClick={applyFilters} disabled={loading}>
<SearchIcon />
</Button>
<Button variant="outline" onClick={() => void loadData()} disabled={loading}>
<RefreshCwIcon className={loading ? "animate-spin" : ""} />
</Button>
<Button onClick={openCreateDialog}>
<PlusIcon />
</Button>
</div>
<div className="space-y-4">
<div className="overflow-hidden rounded-2xl border bg-background">
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
<TableHead>Skill</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="w-[168px] text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{!loading && result.results.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="py-12 text-center text-muted-foreground">
Skill
</TableCell>
</TableRow>
) : null}
{result.results.map((item) => (
<SkillRow
key={item.id}
item={item}
actionLoadingId={actionLoadingId}
openEditDialog={openEditDialog}
openDebugDialog={openDebugDialog}
handleToggleStatus={handleToggleStatus}
handleDelete={handleDelete}
handleRestore={handleRestore}
/>
))}
</TableBody>
</Table>
<div className="border-t px-4 py-3">
<ListPagination
page={result.page.page}
total={result.page.total}
limit={limit}
loading={loading}
onPageChange={handlePageChange}
onLimitChange={(nextLimit) => {
setLimit(nextLimit)
setPage(1)
}}
/>
</div>
</div>
</div>
</div>
<EditDialog
open={dialogOpen}
saving={saving}
itemId={editingItem?.id ?? null}
onOpenChange={handleDialogOpenChange}
onSubmit={handleSubmit}
/>
<DebugDialog
open={debugDialogOpen}
skillCode={debuggingItem?.code ?? ""}
skillName={debuggingItem?.name ?? ""}
onOpenChange={handleDebugDialogOpenChange}
/>
</>
)
}