feat(studio): Agent 编排服务端保存 + 我的编排列表(owner 隔离)

编排好的 Agent 现在可命名保存到服务端、跨会话可见;左侧「我的编排」列出本人全部。

- store: sundynix_agent 表(owner+name 唯一,Graph=React Flow {nodes,edges} JSON 含布局,
  UpdatedAt);ListAgents(最近在前)/SaveAgent(OnConflict 覆盖图+时间)/DeleteAgent。AutoMigrate +Agent。
- gateway: GET/POST/DELETE /api/v1/agents(owner 隔离,身份取自 X-User-ID)。
- 前端:api listAgents/saveAgent/deleteAgent;StudioView 左面板下半区「我的编排(N)」列出本人编排,
  点击载入(含布局)、悬停删除;工具栏 编排名+保存(服务端),去掉 localStorage 模板。

验证:curl 保存「合同审查流程」→ wt 列表含之,alice 列表为空(隔离)。Preview:示例图填名「尽调问答
Agent」保存 → 左「我的编排(2)」即时出现两条、可点载入。tsc+vite+gateway build 通过;重建 .app。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-06-13 16:23:03 +08:00
parent 337d4d7619
commit 4bf614a07c
6 changed files with 212 additions and 82 deletions
+32
View File
@@ -126,6 +126,38 @@ export interface VaultDoc {
content: string;
}
// ---- 我的 Agent 编排(服务端保存,owner 隔离)----
export interface AgentInfo {
name: string;
graph: string; // {nodes,edges} JSON
updated_at?: string;
}
export async function listAgents(id: Identity): Promise<AgentInfo[]> {
const res = await fetch(`${GATEWAY}/api/v1/agents`, { headers: idHeaders(id) });
const data = (await res.json()) as { agents?: AgentInfo[]; error?: string };
if (!res.ok) throw new Error(data.error ?? `list agents failed: ${res.status}`);
return data.agents ?? [];
}
export async function saveAgent(id: Identity, name: string, graph: string): Promise<void> {
const res = await fetch(`${GATEWAY}/api/v1/agents`, {
method: "POST",
headers: { "Content-Type": "application/json", ...idHeaders(id) },
body: JSON.stringify({ name, graph }),
});
const data = (await res.json()) as { name?: string; error?: string };
if (!res.ok || !data.name) throw new Error(data.error ?? `save agent failed: ${res.status}`);
}
export async function deleteAgent(id: Identity, name: string): Promise<void> {
const res = await fetch(`${GATEWAY}/api/v1/agents?name=${encodeURIComponent(name)}`, { method: "DELETE", headers: idHeaders(id) });
if (!res.ok) {
const data = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(data.error ?? `delete agent failed: ${res.status}`);
}
}
// listChatModels: GET /api/v1/admin/models?kind=chat —— 已登记的对话模型名(供编排 Agent 节点选择)。
export async function listChatModels(): Promise<string[]> {
try {
@@ -13,31 +13,17 @@ import {
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { Play, ShieldCheck, Sparkles, Trash2, Save, FolderOpen } from "lucide-react";
import { Play, ShieldCheck, Sparkles, Trash2, Save, Workflow } from "lucide-react";
import { nodeTypes, type NodeStatus } from "./TypedNode";
import { Inspector } from "./Inspector";
import { NODE_KINDS, NODE_ORDER } from "./nodeCatalog";
import { exportDsl, validate, type Issue, type TaskDsl } from "../lib/dsl";
import type { RunPhase } from "../lib/run";
import { listKb, listChatModels, type Identity } from "../lib/api";
import { Button, Input, useToast } from "../ui";
import { listKb, listChatModels, listAgents, saveAgent, deleteAgent, type Identity, type AgentInfo } from "../lib/api";
import { Button, Input, cn, useToast } from "../ui";
let seq = 0;
interface Template {
name: string;
nodes: Node[];
edges: Edge[];
}
const TPL_KEY = "sundynix.studio.templates";
function loadTpls(): Template[] {
try {
return JSON.parse(localStorage.getItem(TPL_KEY) || "[]");
} catch {
return [];
}
}
// buildExample:一张可直接运行的示例图(输入 → 检索本人 default 库 → Agent → 输出)。
function buildExample(): { nodes: Node[]; edges: Edge[] } {
const mk = (id: string, kind: string, x: number, cfg: Record<string, unknown>): Node => ({
@@ -61,7 +47,7 @@ function buildExample(): { nodes: Node[]; edges: Edge[] } {
};
}
// 编排 Studio:左节点面板 · 中画布 · 右检查器 · 顶工具栏(运行/校验/模板)
// 编排 Studio:左(节点面板 + 我的编排) · 中画布 · 右检查器 · 顶工具栏。
export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) => void; phase: RunPhase; identity: Identity }) {
const toast = useToast();
const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
@@ -70,15 +56,19 @@ export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) =
const [issues, setIssues] = useState<Issue[] | null>(null);
const [kbOpts, setKbOpts] = useState<string[]>([]);
const [modelOpts, setModelOpts] = useState<string[]>([]);
const [tplName, setTplName] = useState("");
const [tpls, setTpls] = useState<Template[]>(loadTpls());
const [agents, setAgents] = useState<AgentInfo[]>([]);
const [name, setName] = useState("");
// 载入真实知识库 / 对话模型作为节点下拉选项。
useEffect(() => {
listKb(identity).then((ks) => setKbOpts(ks.map((k) => k.name))).catch(() => {});
listChatModels().then(setModelOpts).catch(() => {});
}, [identity]);
const refreshAgents = useCallback(() => {
listAgents(identity).then(setAgents).catch(() => {});
}, [identity]);
useEffect(() => refreshAgents(), [refreshAgents]);
const dynamicOptions = useMemo(() => ({ kb: kbOpts, model: modelOpts }), [kbOpts, modelOpts]);
const onConnect = useCallback((c: Connection) => setEdges((es) => addEdge(c, es)), [setEdges]);
@@ -117,12 +107,11 @@ export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) =
const loadGraph = useCallback(
(g: { nodes: Node[]; edges: Edge[] }) => {
setNodes(g.nodes.map((n) => ({ ...n, data: { ...n.data, status: "idle" as NodeStatus } })));
setEdges(g.edges);
setNodes((g.nodes ?? []).map((n) => ({ ...n, data: { ...n.data, status: "idle" as NodeStatus } })));
setEdges(g.edges ?? []);
setSelId(null);
setIssues(null);
// 让自增 id 越过已载入节点,避免碰撞。
for (const n of g.nodes) {
for (const n of g.nodes ?? []) {
const m = /^n(\d+)$/.exec(n.id);
if (m) seq = Math.max(seq, Number(m[1]));
}
@@ -137,23 +126,38 @@ export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) =
setIssues(null);
};
const saveTpl = () => {
const name = tplName.trim();
if (!name) {
toast.push("error", "先填模板名");
return;
const save = async () => {
const nm = name.trim();
if (!nm) return toast.push("error", "先填编排名");
if (nodes.length === 0) return toast.push("error", "画布为空");
try {
await saveAgent(identity, nm, JSON.stringify({ nodes, edges }));
toast.push("success", `已保存编排「${nm}`);
refreshAgents();
} catch (e) {
toast.push("error", (e as Error).message);
}
};
const openAgent = (a: AgentInfo) => {
try {
loadGraph(JSON.parse(a.graph));
setName(a.name);
} catch {
toast.push("error", "编排数据损坏,无法载入");
}
};
const removeAgent = async (nm: string) => {
try {
await deleteAgent(identity, nm);
refreshAgents();
toast.push("success", `已删除「${nm}`);
} catch (e) {
toast.push("error", (e as Error).message);
}
if (nodes.length === 0) {
toast.push("error", "画布为空");
return;
}
const next = [...tpls.filter((t) => t.name !== name), { name, nodes, edges }];
setTpls(next);
localStorage.setItem(TPL_KEY, JSON.stringify(next));
toast.push("success", `已保存模板「${name}`);
};
// 运行状态映射到节点徽标。
useEffect(() => {
const status: NodeStatus =
phase === "streaming" || phase === "submitting" ? "running" : phase === "done" ? "done" : phase === "error" ? "error" : "idle";
@@ -171,22 +175,42 @@ export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) =
return (
<div className="flex h-full">
{/* 左节点面板 */}
<div className="w-40 shrink-0 overflow-auto border-r border-line bg-ink-900 p-2">
<div className="mb-1 px-1 text-[11px] font-semibold text-slate-500"></div>
{NODE_ORDER.map((kind) => {
const k = NODE_KINDS[kind];
return (
<button
key={kind}
onClick={() => addNode(kind)}
className={`mb-1 flex w-full items-center gap-2 rounded-md border border-l-[3px] border-line bg-ink-800 px-2 py-1.5 text-left text-xs text-slate-300 hover:bg-ink-700 ${k.accent}`}
title={k.desc}
>
{k.label}
</button>
);
})}
{/* 左节点面板 + 我的编排 */}
<div className="flex w-44 shrink-0 flex-col border-r border-line bg-ink-900">
<div className="overflow-auto p-2">
<div className="mb-1 px-1 text-[11px] font-semibold text-slate-500"></div>
{NODE_ORDER.map((kind) => {
const k = NODE_KINDS[kind];
return (
<button
key={kind}
onClick={() => addNode(kind)}
className={`mb-1 flex w-full items-center gap-2 rounded-md border border-l-[3px] border-line bg-ink-800 px-2 py-1.5 text-left text-xs text-slate-300 hover:bg-ink-700 ${k.accent}`}
title={k.desc}
>
{k.label}
</button>
);
})}
</div>
<div className="flex min-h-0 flex-1 flex-col border-t border-line p-2">
<div className="mb-1 flex items-center gap-1 px-1 text-[11px] font-semibold text-slate-500">
<Workflow className="h-3.5 w-3.5" /> {agents.length > 0 && `(${agents.length})`}
</div>
<ul className="min-h-0 flex-1 space-y-0.5 overflow-auto">
{agents.length === 0 && <li className="px-1 text-[11px] text-slate-600"></li>}
{agents.map((a) => (
<li key={a.name} className="group flex items-center gap-1 rounded hover:bg-ink-800">
<button onClick={() => openAgent(a)} className="flex-1 truncate px-2 py-1.5 text-left text-xs text-slate-300" title={`载入「${a.name}`}>
{a.name}
</button>
<button onClick={() => removeAgent(a.name)} className="px-1 text-slate-600 opacity-0 hover:text-danger group-hover:opacity-100" title="删除">
<Trash2 className="h-3.5 w-3.5" />
</button>
</li>
))}
</ul>
</div>
</div>
{/* 中画布 */}
@@ -206,33 +230,10 @@ export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) =
</Button>
<span className="mx-1 h-4 w-px bg-line" />
<Input className="h-8 w-28" value={tplName} onChange={(e) => setTplName(e.target.value)} placeholder="模板名" />
<Button size="sm" icon={Save} onClick={saveTpl}>
<Input className="h-8 w-32" value={name} onChange={(e) => setName(e.target.value)} placeholder="编排名" />
<Button size="sm" variant="primary" icon={Save} onClick={save} disabled={nodes.length === 0}>
</Button>
{tpls.length > 0 && (
<div className="relative">
<select
className="h-8 rounded-md border border-line bg-ink-800 px-2 pr-6 text-xs text-slate-300 focus:border-brand focus:outline-none"
value=""
onChange={(e) => {
const t = tpls.find((x) => x.name === e.target.value);
if (t) {
loadGraph(t);
setTplName(t.name);
}
}}
>
<option value=""></option>
{tpls.map((t) => (
<option key={t.name} value={t.name}>
{t.name}
</option>
))}
</select>
<FolderOpen className="pointer-events-none absolute right-1.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-500" />
</div>
)}
<span className="ml-auto text-[11px] text-slate-500">
{nodes.length} · {edges.length} 线
</span>
@@ -264,7 +265,7 @@ export function StudioView({ onRun, phase, identity }: { onRun: (dsl: TaskDsl) =
{issues && issues.length > 0 && (
<div className="absolute bottom-2 left-2 max-w-md rounded-lg border border-line bg-ink-850 p-2 text-[11px] shadow-card">
{issues.map((i, idx) => (
<div key={idx} className={i.level === "error" ? "text-danger" : "text-warn"}>
<div key={idx} className={cn(i.level === "error" ? "text-danger" : "text-warn")}>
{i.level === "error" ? "✗" : "⚠"} {i.msg}
</div>
))}