Files
deerflow-code/frontend-web/src/strategy-selection/AgentConfigDialog.tsx
T

313 lines
12 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { Bot, Check, LoaderCircle, Save, Sparkles } from "lucide-react";
import { toast } from "sonner";
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
import { ModelNameSelect } from "@/components/workspace/model-name-select";
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { getAgent, updateAgent } from "@/core/agents/api";
import type { Agent } from "@/core/agents/types";
import { useAllSkillsAdmin } from "@/core/skills/hooks";
import { cn } from "@/lib/utils";
import { STRATEGY_AGENT_ROLES } from "./constants";
interface AgentConfigDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface AgentConfigDraft {
soul: string;
model: string | null;
skills: string[];
}
function normalizeSkills(skills: string[]) {
return [...new Set(skills)].sort((left, right) => left.localeCompare(right));
}
function sameSkills(left: string[], right: string[]) {
const normalizedLeft = normalizeSkills(left);
const normalizedRight = normalizeSkills(right);
return (
normalizedLeft.length === normalizedRight.length &&
normalizedLeft.every((skill, index) => skill === normalizedRight[index])
);
}
export function AgentConfigDialog({ open, onOpenChange }: AgentConfigDialogProps) {
const [selectedId, setSelectedId] = useState<string>(STRATEGY_AGENT_ROLES[0].id);
const [agent, setAgent] = useState<Agent | null>(null);
const [soul, setSoul] = useState("");
const [model, setModel] = useState<string | null>(null);
const [selectedSkills, setSelectedSkills] = useState<string[]>([]);
const [savedDraft, setSavedDraft] = useState<AgentConfigDraft | null>(null);
const [detailSkillName, setDetailSkillName] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const selectedRole = useMemo(
() => STRATEGY_AGENT_ROLES.find((role) => role.id === selectedId)!,
[selectedId],
);
const {
skills,
isLoading: isSkillsLoading,
error: skillsError,
} = useAllSkillsAdmin(open);
const selectableSkills = useMemo(
() =>
skills.filter((skill) => {
const globallyAvailable =
Boolean(skill.builtin) || Boolean(skill.published);
return (
skill.enabled &&
(skill.state ?? "active") === "active" &&
globallyAvailable
);
}),
[skills],
);
const dirty = Boolean(
agent &&
savedDraft &&
(soul !== savedDraft.soul ||
model !== savedDraft.model ||
!sameSkills(selectedSkills, savedDraft.skills)),
);
useEffect(() => {
if (!open || !selectedId) return;
let active = true;
setLoading(true);
setError("");
setAgent(null);
setSavedDraft(null);
void getAgent(selectedId)
.then((data) => {
if (!active) return;
setAgent(data);
const nextDraft = {
soul: data.soul ?? "",
model: data.model ?? null,
skills: data.skills ?? [],
};
setSoul(nextDraft.soul);
setModel(nextDraft.model);
setSelectedSkills(nextDraft.skills);
setSavedDraft(nextDraft);
})
.catch((reason: unknown) => {
if (!active) return;
setError(
reason instanceof Error
? reason.message
: "智能体配置加载失败,请确认后端已完成默认配置初始化。",
);
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [open, selectedId]);
const save = async () => {
if (!agent) return;
setSaving(true);
try {
const updated = await updateAgent(agent.id, {
soul: soul.trim(),
model,
skills: selectedSkills,
});
setAgent(updated);
setSoul(updated.soul ?? "");
setModel(updated.model ?? null);
setSelectedSkills(updated.skills ?? []);
setSavedDraft({
soul: updated.soul ?? "",
model: updated.model ?? null,
skills: updated.skills ?? [],
});
toast.success(`${updated.name} 配置已保存`);
} catch (reason) {
toast.error(reason instanceof Error ? reason.message : "保存失败");
} finally {
setSaving(false);
}
};
const confirmDiscardChanges = () =>
!dirty || window.confirm("当前智能体配置尚未保存,确定放弃这些修改吗?");
const selectRole = (roleId: string) => {
if (roleId === selectedId || saving || !confirmDiscardChanges()) return;
setSelectedId(roleId);
};
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen && (saving || !confirmDiscardChanges())) return;
onOpenChange(nextOpen);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="h-[min(780px,calc(100vh-48px))] max-w-[1080px] grid-rows-[auto_minmax(0,1fr)_auto] gap-0 overflow-hidden p-0 sm:max-w-[1080px]">
<DialogHeader className="border-b px-6 py-5 dark:border-[#173d68]">
<DialogTitle className="flex items-center gap-2">
<Bot className="size-5 text-primary" />
策略智能体配置
</DialogTitle>
<DialogDescription>
这是全局统一配置,不属于某一个项目。管理员保存后,所有策略项目下一次运行都会使用这里的模型、SOUL 和技能。
</DialogDescription>
</DialogHeader>
<div className="grid min-h-0 grid-cols-[290px_minmax(0,1fr)]">
<div className="min-h-0 overflow-y-auto border-r bg-muted/20 p-3 dark:border-[#173d68] dark:bg-[#031b38]">
<div className="mb-2 px-2 text-xs font-semibold tracking-wide text-muted-foreground">
流程角色 · {STRATEGY_AGENT_ROLES.length}
</div>
<div className="space-y-1.5">
{STRATEGY_AGENT_ROLES.map((role) => {
const selected = role.id === selectedId;
return (
<button
key={role.id}
type="button"
disabled={saving}
onClick={() => selectRole(role.id)}
className={cn(
"w-full rounded-lg border px-3 py-3 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-60",
selected
? "border-primary/45 bg-primary/10 shadow-sm"
: "border-transparent hover:border-border hover:bg-background dark:hover:border-[#28507c] dark:hover:bg-[#08274c]",
)}
>
<span className="flex items-center justify-between gap-2">
<span className="text-sm font-medium">{role.name}</span>
{selected && <Check className="size-4 text-primary" />}
</span>
<span className="mt-1 block text-xs leading-5 text-muted-foreground">
{role.role}
</span>
</button>
);
})}
</div>
</div>
<div className="min-h-0 overflow-y-auto px-6 py-5">
<div className="mb-5 flex items-start justify-between gap-3">
<div>
<h3 className="font-semibold">{selectedRole.name}</h3>
<p className="mt-1 text-sm text-muted-foreground">{selectedRole.role}</p>
</div>
<Badge variant="outline" className="font-mono text-[11px]">
{selectedRole.id}
</Badge>
</div>
{loading ? (
<div className="flex h-56 items-center justify-center gap-2 text-sm text-muted-foreground">
<LoaderCircle className="size-4 animate-spin" />
正在读取智能体配置…
</div>
) : error ? (
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
<p className="font-medium">暂时无法加载该智能体</p>
<p className="mt-1 leading-6 opacity-85">{error}</p>
</div>
) : agent ? (
<div className="space-y-5">
<div className="grid grid-cols-[minmax(0,1fr)_minmax(220px,0.9fr)] gap-3 rounded-lg border bg-muted/20 p-3 text-sm dark:border-[#173d68] dark:bg-[#031b38]">
<div>
<span className="text-xs text-muted-foreground">当前名称</span>
<div className="mt-1 font-medium">{agent.name}</div>
</div>
<label className="block">
<span className="text-xs text-muted-foreground">运行模型</span>
<ModelNameSelect
value={model}
onChange={setModel}
disabled={saving}
defaultLabel="使用系统默认模型"
title="选择该全局智能体运行时使用的大模型;未指定时使用系统默认模型"
triggerClassName="mt-1 w-full bg-background"
/>
</label>
</div>
<label className="block">
<span className="mb-2 flex items-center gap-2 text-sm font-medium">
<Sparkles className="size-4 text-primary" /> SOUL
</span>
<Textarea
value={soul}
disabled={saving}
onChange={(event) => setSoul(event.target.value)}
className="min-h-[220px] resize-y font-mono text-xs leading-6"
placeholder="定义智能体的角色、分析方法、边界和输出要求…"
/>
</label>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<span className="text-sm font-medium">技能库选择</span>
<Badge variant="secondary">已选 {selectedSkills.length} 个</Badge>
</div>
<p className="text-xs leading-5 text-muted-foreground">
从系统技能库勾选该智能体可使用的技能;这里保存的是全局白名单,不接受手工输入技能名。
</p>
<SkillTransferSelector
skills={selectableSkills}
selected={selectedSkills}
onChange={setSelectedSkills}
isLoading={isSkillsLoading}
onViewDetail={setDetailSkillName}
/>
{skillsError ? (
<p className="text-xs text-destructive">技能库加载失败,请稍后重试。</p>
) : null}
</div>
</div>
) : null}
</div>
</div>
<DialogFooter className="border-t px-6 py-4 dark:border-[#173d68]">
<Button variant="outline" disabled={saving} onClick={() => handleOpenChange(false)}>
关闭
</Button>
<Button disabled={!agent || loading || saving || isSkillsLoading} onClick={() => void save()}>
{saving ? <LoaderCircle className="animate-spin" /> : <Save />}
保存当前智能体
</Button>
</DialogFooter>
</DialogContent>
<SkillDetailDialog
skillName={detailSkillName}
open={detailSkillName !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setDetailSkillName(null);
}}
/>
</Dialog>
);
}