mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-22 06:22:00 +00:00
AgentLab:可视化 Agent 编排实验台
在画布上拖拽编排 agent 工作流,并实时看着它执行。 后端 FastAPI + LangGraph:把画布 JSON 编译成 StateGraph,15 种节点 (模型/Agent/多Agent、工具/沙箱、分支/循环/子图、记忆/检索/整形、 人工介入/结构校验)。选 LangGraph 是因为可视化编排真正难的是暂停、 恢复和回放,而 checkpointer + interrupt() 正好把这几件事做在了底层。 前端 React + React Flow:节点元数据驱动属性面板与连接桩,运行时 节点高亮、边流动画、卡片内流式 token 全部由同一份事件流驱动。 关键实现: - Agent 内工具审批用 @task 缓存模型调用,interrupt 重放时不重复计费 - 沙箱保持只读根文件系统,代码经 exec+base64 写入(put_archive 会被 只读容器拒绝),断网、非 root、内存/CPU/超时限额 - 检索为向量与 BM25 混合,本地哈希 embedding 零配置可用 - 分支条件走 AST 白名单求值器;HTTP 工具逐 IP 拦截内网与元数据地址 - Mock provider 让无 API Key 也能跑通完整链路 7 个内置模板全部冒烟通过,含真实模型端到端验证。
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { useEffect } from 'react'
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom'
|
||||
import { BookOpen, FlaskConical, History, Settings, Wrench } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from './api/client'
|
||||
import { useCatalog } from './store/catalog'
|
||||
import { StudioPage } from './pages/StudioPage'
|
||||
import { RunsPage } from './pages/RunsPage'
|
||||
import { ToolsPage } from './pages/ToolsPage'
|
||||
import { KnowledgePage } from './pages/KnowledgePage'
|
||||
import { SettingsPage, applyTheme } from './pages/SettingsPage'
|
||||
import { Spinner } from './components/ui'
|
||||
|
||||
const NAV = [
|
||||
{ to: '/studio', label: '编排', icon: FlaskConical },
|
||||
{ to: '/runs', label: '运行', icon: History },
|
||||
{ to: '/tools', label: '工具', icon: Wrench },
|
||||
{ to: '/knowledge', label: '知识', icon: BookOpen },
|
||||
{ to: '/settings', label: '设置', icon: Settings },
|
||||
]
|
||||
|
||||
export default function App() {
|
||||
const { loaded, refresh, refreshApprovals, approvals } = useCatalog()
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
void api.settings.get().then((s) => applyTheme(s?.ui?.theme ?? 'system')).catch(() => {})
|
||||
}, [refresh])
|
||||
|
||||
// 待审批是全局待办:别的页面也要能看到有东西等着人处理
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => void refreshApprovals(), 4000)
|
||||
return () => clearInterval(timer)
|
||||
}, [refreshApprovals])
|
||||
|
||||
const pending = approvals.filter((a) => a.status === 'pending').length
|
||||
|
||||
if (!loaded) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center gap-2 text-dim">
|
||||
<Spinner size={16} /> 正在连接后端…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
<nav className="flex w-14 shrink-0 flex-col items-center gap-1 border-r bg-panel py-2">
|
||||
<div className="mb-2 flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--accent)] text-[13px] font-bold text-white">
|
||||
A
|
||||
</div>
|
||||
{NAV.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
className={({ isActive }) =>
|
||||
clsx(
|
||||
'relative flex w-11 flex-col items-center gap-0.5 rounded-lg py-2 text-[9.5px] transition-colors',
|
||||
isActive ? 'bg-hover text-fg' : 'text-faint hover:bg-hover hover:text-dim',
|
||||
)
|
||||
}
|
||||
>
|
||||
<item.icon size={15} />
|
||||
{item.label}
|
||||
{item.to === '/runs' && pending > 0 && (
|
||||
<span className="absolute right-1.5 top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-[var(--warn)] px-1 text-[8.5px] font-bold text-black">
|
||||
{pending}
|
||||
</span>
|
||||
)}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<main className="min-w-0 flex-1">
|
||||
<Routes>
|
||||
<Route path="/" element={<Navigate to="/studio" replace />} />
|
||||
<Route path="/studio" element={<StudioPage />} />
|
||||
<Route path="/runs" element={<RunsPage />} />
|
||||
<Route path="/tools" element={<ToolsPage />} />
|
||||
<Route path="/knowledge" element={<KnowledgePage />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import type {
|
||||
Approval, GraphSpec, KbDocument, MemoryItem, Provider, Run, RunEvent,
|
||||
Skill, ToolInfo, ValidationIssue, Workflow,
|
||||
} from '../types'
|
||||
|
||||
const BASE = '/api'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, message: string) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(BASE + path, {
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
|
||||
...init?.headers,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
let detail = `${res.status} ${res.statusText}`
|
||||
try {
|
||||
const body = await res.json()
|
||||
// FastAPI 的校验错误是数组,直接 String() 会变成 [object Object]
|
||||
detail = typeof body.detail === 'string' ? body.detail : JSON.stringify(body.detail ?? body)
|
||||
} catch {
|
||||
/* 响应体不是 JSON,保留状态行 */
|
||||
}
|
||||
throw new ApiError(res.status, detail)
|
||||
}
|
||||
if (res.status === 204) return undefined as T
|
||||
return res.json()
|
||||
}
|
||||
|
||||
const get = <T>(p: string) => request<T>(p)
|
||||
const post = <T>(p: string, body?: unknown) =>
|
||||
request<T>(p, { method: 'POST', body: JSON.stringify(body ?? {}) })
|
||||
const patch = <T>(p: string, body: unknown) =>
|
||||
request<T>(p, { method: 'PATCH', body: JSON.stringify(body) })
|
||||
const put = <T>(p: string, body: unknown) =>
|
||||
request<T>(p, { method: 'PUT', body: JSON.stringify(body) })
|
||||
const del = (p: string) => request<void>(p, { method: 'DELETE' })
|
||||
|
||||
export const api = {
|
||||
health: () => get<{ status: string }>('/health'),
|
||||
system: () => get<any>('/system'),
|
||||
|
||||
// ---- 工作流 ----
|
||||
workflows: {
|
||||
list: () => get<Workflow[]>('/workflows'),
|
||||
get: (id: string) => get<Workflow>(`/workflows/${id}`),
|
||||
create: (body: { name: string; description?: string; graph?: GraphSpec; tags?: string[] }) =>
|
||||
post<Workflow>('/workflows', body),
|
||||
update: (id: string, body: Partial<Workflow> & { note?: string }) =>
|
||||
patch<Workflow>(`/workflows/${id}`, body),
|
||||
remove: (id: string) => del(`/workflows/${id}`),
|
||||
duplicate: (id: string) => post<Workflow>(`/workflows/${id}/duplicate`),
|
||||
versions: (id: string) => get<any[]>(`/workflows/${id}/versions`),
|
||||
restore: (id: string, v: number) => post<Workflow>(`/workflows/${id}/versions/${v}/restore`),
|
||||
validate: (graph: GraphSpec) =>
|
||||
post<{ ok: boolean; issues: ValidationIssue[] }>('/workflows/validate', { graph }),
|
||||
},
|
||||
|
||||
// ---- 运行 ----
|
||||
runs: {
|
||||
list: (params?: { workflow_id?: string; status?: string; limit?: number }) => {
|
||||
const q = new URLSearchParams(
|
||||
Object.entries(params ?? {}).filter(([, v]) => v != null) as [string, string][],
|
||||
)
|
||||
return get<Run[]>(`/runs${q.toString() ? `?${q}` : ''}`)
|
||||
},
|
||||
get: (id: string) => get<Run>(`/runs/${id}`),
|
||||
start: (body: {
|
||||
workflow_id?: string; graph?: GraphSpec; input?: Record<string, any>
|
||||
memory_scope?: string; collection?: string
|
||||
}) => post<Run>('/runs', body),
|
||||
cancel: (id: string) => post<{ ok: boolean }>(`/runs/${id}/cancel`),
|
||||
resume: (id: string, response: any) => post<Run>(`/runs/${id}/resume`, { response }),
|
||||
events: (id: string, after = 0) => get<RunEvent[]>(`/runs/${id}/events?after=${after}`),
|
||||
state: (id: string) => get<any>(`/runs/${id}/state`),
|
||||
history: (id: string) => get<any[]>(`/runs/${id}/history`),
|
||||
remove: (id: string) => del(`/runs/${id}`),
|
||||
},
|
||||
|
||||
approvals: {
|
||||
list: (status = 'pending') => get<Approval[]>(`/approvals?status=${status}`),
|
||||
decide: (id: string, body: { approved: boolean; note?: string; value?: any; args?: any }) =>
|
||||
post<Run>(`/approvals/${id}/decide`, body),
|
||||
},
|
||||
|
||||
// ---- 设置 ----
|
||||
providers: {
|
||||
list: () => get<Provider[]>('/providers'),
|
||||
catalog: () => get<any>('/providers/catalog'),
|
||||
create: (body: any) => post<Provider>('/providers', body),
|
||||
update: (id: string, body: any) => patch<Provider>(`/providers/${id}`, body),
|
||||
remove: (id: string) => del(`/providers/${id}`),
|
||||
test: (id: string, body: { model?: string; prompt?: string }) =>
|
||||
post<any>(`/providers/${id}/test`, body),
|
||||
},
|
||||
settings: {
|
||||
get: () => get<Record<string, any>>('/settings'),
|
||||
put: (values: Record<string, any>) => put<Record<string, any>>('/settings', { values }),
|
||||
},
|
||||
|
||||
// ---- 工具 ----
|
||||
tools: {
|
||||
list: () => get<ToolInfo[]>('/tools'),
|
||||
run: (name: string, args: Record<string, any>) =>
|
||||
post<any>(`/tools/${name}/run`, { args }),
|
||||
},
|
||||
customTools: {
|
||||
list: () => get<any[]>('/custom-tools'),
|
||||
create: (body: any) => post<any>('/custom-tools', body),
|
||||
update: (id: string, body: any) => patch<any>(`/custom-tools/${id}`, body),
|
||||
remove: (id: string) => del(`/custom-tools/${id}`),
|
||||
test: (id: string, args: Record<string, any>) => post<any>(`/custom-tools/${id}/test`, { args }),
|
||||
},
|
||||
mcp: {
|
||||
list: () => get<any[]>('/mcp/servers'),
|
||||
create: (body: any) => post<any>('/mcp/servers', body),
|
||||
update: (id: string, body: any) => patch<any>(`/mcp/servers/${id}`, body),
|
||||
remove: (id: string) => del(`/mcp/servers/${id}`),
|
||||
probe: (id: string) => post<any>(`/mcp/servers/${id}/probe`),
|
||||
refresh: () => post<any>('/mcp/refresh'),
|
||||
},
|
||||
|
||||
// ---- 沙箱 ----
|
||||
sandbox: {
|
||||
health: () => get<any>('/sandbox/health'),
|
||||
exec: (body: { code: string; language?: string; timeout?: number; network?: boolean; memory_mb?: number }) =>
|
||||
post<any>('/sandbox/exec', body),
|
||||
},
|
||||
|
||||
// ---- 记忆 / 知识库 / Skill ----
|
||||
memory: {
|
||||
scopes: () => get<{ scope: string; count: number }[]>('/memory/scopes'),
|
||||
list: (scope?: string) => get<MemoryItem[]>(`/memory${scope ? `?scope=${scope}` : ''}`),
|
||||
add: (body: { content: string; scope?: string; kind?: string; importance?: number }) =>
|
||||
post<MemoryItem>('/memory', body),
|
||||
search: (q: string, scope = 'default') =>
|
||||
get<any>(`/memory/search?q=${encodeURIComponent(q)}&scope=${scope}`),
|
||||
remove: (id: string) => del(`/memory/${id}`),
|
||||
clearScope: (scope: string) => del(`/memory/scope/${scope}`),
|
||||
},
|
||||
kb: {
|
||||
collections: () => get<{ collection: string; documents: number; chunks: number }[]>('/kb/collections'),
|
||||
documents: (collection?: string) =>
|
||||
get<KbDocument[]>(`/kb/documents${collection ? `?collection=${collection}` : ''}`),
|
||||
ingest: (body: { collection?: string; title?: string; content: string; source?: string }) =>
|
||||
post<KbDocument>('/kb/documents', body),
|
||||
upload: (file: File, collection = 'default') => {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
return request<KbDocument>(`/kb/upload?collection=${collection}`, { method: 'POST', body: form })
|
||||
},
|
||||
search: (q: string, collection?: string, alpha = 0.5) =>
|
||||
get<any>(`/kb/search?q=${encodeURIComponent(q)}&alpha=${alpha}${collection ? `&collection=${collection}` : ''}`),
|
||||
remove: (id: string) => del(`/kb/documents/${id}`),
|
||||
},
|
||||
skills: {
|
||||
list: () => get<Skill[]>('/skills'),
|
||||
create: (body: Partial<Skill>) => post<Skill>('/skills', body),
|
||||
update: (id: string, body: Partial<Skill>) => patch<Skill>(`/skills/${id}`, body),
|
||||
remove: (id: string) => del(`/skills/${id}`),
|
||||
},
|
||||
|
||||
// ---- Copilot ----
|
||||
copilot: {
|
||||
generate: (body: { instruction: string; base_graph?: GraphSpec | null }) =>
|
||||
post<{ graph: GraphSpec; explanation: string; issues: ValidationIssue[] }>(
|
||||
'/copilot/generate', body),
|
||||
explain: (graph: GraphSpec) => post<{ explanation: string }>('/copilot/explain', { graph }),
|
||||
layout: (graph: GraphSpec) => post<GraphSpec>('/copilot/layout', { graph }),
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅一次运行的事件流。
|
||||
*
|
||||
* 先补历史再接实时由后端保证,这里只负责断线重连 —— 重连时带上已收到的最大
|
||||
* seq,所以不会重复也不会丢事件。
|
||||
*/
|
||||
export function streamRun(
|
||||
runId: string,
|
||||
onEvent: (event: RunEvent) => void,
|
||||
onClose?: () => void,
|
||||
): () => void {
|
||||
let socket: WebSocket | null = null
|
||||
let closed = false
|
||||
let lastSeq = 0
|
||||
let retry = 0
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return
|
||||
const proto = location.protocol === 'https:' ? 'wss' : 'ws'
|
||||
socket = new WebSocket(`${proto}://${location.host}/api/runs/${runId}/stream?after=${lastSeq}`)
|
||||
|
||||
socket.onmessage = (ev) => {
|
||||
const event = JSON.parse(ev.data) as RunEvent & { type: string }
|
||||
if (event.type === 'stream.end') {
|
||||
closed = true
|
||||
socket?.close()
|
||||
onClose?.()
|
||||
return
|
||||
}
|
||||
if (event.seq) lastSeq = Math.max(lastSeq, event.seq)
|
||||
onEvent(event)
|
||||
}
|
||||
socket.onclose = () => {
|
||||
if (closed) return
|
||||
// 指数退避重连,最多等 5 秒
|
||||
retry += 1
|
||||
setTimeout(connect, Math.min(300 * 2 ** retry, 5000))
|
||||
}
|
||||
socket.onopen = () => {
|
||||
retry = 0
|
||||
}
|
||||
}
|
||||
connect()
|
||||
|
||||
return () => {
|
||||
closed = true
|
||||
socket?.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useCallback, useMemo, useRef } from 'react'
|
||||
import {
|
||||
Background, BackgroundVariant, Controls, MiniMap, ReactFlow, ReactFlowProvider,
|
||||
useReactFlow, type Edge,
|
||||
} from '@xyflow/react'
|
||||
import { NodeCard } from './NodeCard'
|
||||
import { useStudio } from '../store/studio'
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
const nodeTypes = { card: NodeCard }
|
||||
|
||||
const NODE_COLOR: Record<string, string> = {
|
||||
input: '#3fb950', output: '#a371f7', llm: '#4f8cff', agent: '#6366f1',
|
||||
supervisor: '#db61a2', tool: '#f0883e', code: '#2dd4bf', branch: '#d29922',
|
||||
loop: '#ec4899', human: '#f85149', validate: '#84cc16', memory: '#14b8a6',
|
||||
retrieve: '#0ea5e9', transform: '#8b949e', subgraph: '#bc8cff',
|
||||
}
|
||||
|
||||
function CanvasInner() {
|
||||
const wrapper = useRef<HTMLDivElement>(null)
|
||||
const { screenToFlowPosition } = useReactFlow()
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
const activeEdges = useStudio((s) => s.activeEdges)
|
||||
const { onNodesChange, onEdgesChange, onConnect, addNode, select } = useStudio()
|
||||
|
||||
// 正在流动的边加动画,让"数据走到哪了"看得见
|
||||
const decorated = useMemo<Edge[]>(
|
||||
() =>
|
||||
edges.map((e) =>
|
||||
activeEdges.includes(e.id)
|
||||
? { ...e, className: 'edge-active', animated: true }
|
||||
: { ...e, className: undefined, animated: false },
|
||||
),
|
||||
[edges, activeEdges],
|
||||
)
|
||||
|
||||
const onDrop = useCallback(
|
||||
(event: React.DragEvent) => {
|
||||
event.preventDefault()
|
||||
const type = event.dataTransfer.getData('application/agentlab-node') as NodeType
|
||||
if (!type) return
|
||||
addNode(type, screenToFlowPosition({ x: event.clientX, y: event.clientY }))
|
||||
},
|
||||
[addNode, screenToFlowPosition],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="h-full w-full" ref={wrapper}>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={decorated}
|
||||
nodeTypes={nodeTypes}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onConnect={onConnect}
|
||||
onNodeClick={(_, node) => select(node.id)}
|
||||
onPaneClick={() => select(null)}
|
||||
onDrop={onDrop}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
e.dataTransfer.dropEffect = 'move'
|
||||
}}
|
||||
fitView
|
||||
fitViewOptions={{ padding: 0.12, maxZoom: 1.1, minZoom: 0.5 }}
|
||||
minZoom={0.2}
|
||||
maxZoom={2}
|
||||
defaultEdgeOptions={{ type: 'smoothstep' }}
|
||||
proOptions={{ hideAttribution: true }}
|
||||
deleteKeyCode={['Backspace', 'Delete']}
|
||||
>
|
||||
<Background variant={BackgroundVariant.Dots} gap={18} size={1} color="var(--canvas-dot)" />
|
||||
<Controls showInteractive={false} />
|
||||
<MiniMap
|
||||
pannable
|
||||
zoomable
|
||||
maskColor="color-mix(in srgb, var(--bg) 82%, transparent)"
|
||||
nodeColor={(n) => NODE_COLOR[(n.data as any)?.nodeType as string] ?? '#666'}
|
||||
style={{ width: 140, height: 96 }}
|
||||
/>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function FlowCanvas() {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<CanvasInner />
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Copy, Plus, Settings2, Trash2, X } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_DEFS, type FieldDef } from './nodeDefs'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { useCatalog, modelOptions } from '../store/catalog'
|
||||
import { JsonInput } from '../components/ui'
|
||||
|
||||
/** 属性面板。所有字段都由 nodeDefs 的声明驱动渲染,加节点类型不用改这里。 */
|
||||
export function Inspector() {
|
||||
const selectedId = useStudio((s) => s.selectedId)
|
||||
const node = useStudio((s) => s.nodes.find((n) => n.id === s.selectedId))
|
||||
const allIssues = useStudio((s) => s.issues)
|
||||
const issues = useMemo(
|
||||
() => allIssues.filter((i) => i.node_id === selectedId),
|
||||
[allIssues, selectedId],
|
||||
)
|
||||
const runtime = useStudio((s) => (selectedId ? s.runtime[selectedId] : undefined))
|
||||
const { updateNode, removeNode, duplicateNode, select } = useStudio()
|
||||
const [showAdvanced, setShowAdvanced] = useState(false)
|
||||
|
||||
if (!node) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
|
||||
<Settings2 size={22} className="text-faint opacity-40" />
|
||||
<div className="text-xs text-faint">选中一个节点来编辑它</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const def = NODE_DEFS[node.data.nodeType]
|
||||
const config = node.data.config ?? {}
|
||||
const setConfig = (key: string, value: any) =>
|
||||
updateNode(node.id, { config: { ...config, [key]: value } })
|
||||
|
||||
const visible = def.fields.filter((f) => !f.when || f.when(config))
|
||||
const basic = visible.filter((f) => !f.advanced)
|
||||
const advanced = visible.filter((f) => f.advanced)
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex items-center gap-2 border-b px-3 py-2">
|
||||
<def.icon size={13} style={{ color: 'var(--nt)' }} className={`nt-${node.data.nodeType}`} />
|
||||
<span className="flex-1 truncate text-xs font-semibold">{def.label}</span>
|
||||
<button className="btn btn-ghost btn-sm" title="复制节点" onClick={() => duplicateNode(node.id)}>
|
||||
<Copy size={12} />
|
||||
</button>
|
||||
<button className="btn btn-ghost btn-sm" title="删除节点" onClick={() => removeNode(node.id)}>
|
||||
<Trash2 size={12} className="text-[var(--err)]" />
|
||||
</button>
|
||||
<button className="btn btn-ghost btn-sm" onClick={() => select(null)}>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-3">
|
||||
<div className="mb-3 text-[11px] leading-relaxed text-faint">{def.description}</div>
|
||||
|
||||
{!!issues.length && (
|
||||
<div className="mb-3 space-y-1">
|
||||
{issues.map((issue, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="rounded border px-2 py-1.5 text-[11px] leading-snug"
|
||||
style={{
|
||||
borderColor: issue.level === 'error' ? 'var(--err)' : 'var(--warn)',
|
||||
color: issue.level === 'error' ? 'var(--err)' : 'var(--warn)',
|
||||
}}
|
||||
>
|
||||
{issue.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="label">节点名称</label>
|
||||
<input
|
||||
className="field"
|
||||
value={node.data.label ?? ''}
|
||||
onChange={(e) => updateNode(node.id, { label: e.target.value })}
|
||||
placeholder={def.label}
|
||||
/>
|
||||
<div className="mt-1 text-[10px] text-faint">
|
||||
ID: <code className="mono">{node.id}</code> · 下游用 {`{{ nodes.${node.id}.text }}`} 引用
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{basic.map((field) => (
|
||||
<Field key={field.key} field={field} value={config[field.key]} onChange={(v) => setConfig(field.key, v)} />
|
||||
))}
|
||||
|
||||
{!!advanced.length && (
|
||||
<div className="mt-3 border-t pt-3">
|
||||
<button
|
||||
className="mb-2 text-[11px] text-faint hover:text-dim"
|
||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
||||
>
|
||||
{showAdvanced ? '▾' : '▸'} 高级选项({advanced.length})
|
||||
</button>
|
||||
{showAdvanced &&
|
||||
advanced.map((field) => (
|
||||
<Field key={field.key} field={field} value={config[field.key]} onChange={(v) => setConfig(field.key, v)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{runtime?.preview != null && (
|
||||
<div className="mt-4 border-t pt-3">
|
||||
<div className="label">上次运行输出</div>
|
||||
<pre className="mono max-h-60 overflow-auto rounded border bg-bg p-2 text-[10.5px] leading-relaxed whitespace-pre-wrap break-words">
|
||||
{typeof runtime.preview === 'string'
|
||||
? runtime.preview
|
||||
: JSON.stringify(runtime.preview, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function Field({ field, value, onChange }: {
|
||||
field: FieldDef; value: any; onChange: (v: any) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-3">
|
||||
{field.type !== 'switch' && <label className="label">{field.label}</label>}
|
||||
<FieldInput field={field} value={value} onChange={onChange} />
|
||||
{field.help && field.type !== 'switch' && (
|
||||
<div className="mt-1 text-[10px] leading-snug text-faint">{field.help}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldInput({ field, value, onChange }: {
|
||||
field: FieldDef; value: any; onChange: (v: any) => void
|
||||
}) {
|
||||
const catalog = useCatalog()
|
||||
|
||||
switch (field.type) {
|
||||
case 'text':
|
||||
return (
|
||||
<input className="field" value={value ?? ''} placeholder={field.placeholder}
|
||||
onChange={(e) => onChange(e.target.value)} />
|
||||
)
|
||||
|
||||
case 'number':
|
||||
return (
|
||||
<input
|
||||
className="field" type="number" value={value ?? ''} min={field.min} max={field.max}
|
||||
step={field.step ?? 1} placeholder={field.placeholder}
|
||||
onChange={(e) => onChange(e.target.value === '' ? undefined : Number(e.target.value))}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'textarea':
|
||||
case 'prompt':
|
||||
return (
|
||||
<textarea
|
||||
className={clsx('field', field.type === 'prompt' && 'mono text-[11.5px]')}
|
||||
rows={field.type === 'prompt' ? 4 : 3}
|
||||
value={value ?? ''} placeholder={field.placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'code':
|
||||
return (
|
||||
<textarea
|
||||
className="field mono text-[11px]" rows={10} spellCheck={false}
|
||||
value={value ?? ''} placeholder={field.placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'select':
|
||||
return (
|
||||
<select className="field" value={value ?? ''} onChange={(e) => onChange(e.target.value)}>
|
||||
{(field.options ?? []).map((o) => (
|
||||
<option key={o.value} value={o.value}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
|
||||
case 'switch':
|
||||
return (
|
||||
<label className="flex cursor-pointer items-center gap-2 py-0.5">
|
||||
<input type="checkbox" checked={!!value} onChange={(e) => onChange(e.target.checked)}
|
||||
className="accent-[var(--accent)]" />
|
||||
<span className="text-xs">{field.label}</span>
|
||||
{field.help && <span className="text-[10px] text-faint">· {field.help}</span>}
|
||||
</label>
|
||||
)
|
||||
|
||||
case 'json':
|
||||
return <JsonInput value={value} onChange={onChange} placeholder={field.placeholder} />
|
||||
|
||||
case 'model': {
|
||||
const options = modelOptions(catalog.providers)
|
||||
const groups = [...new Set(options.map((o) => o.group))]
|
||||
return (
|
||||
<select className="field" value={value ?? ''} onChange={(e) => onChange(e.target.value)}>
|
||||
<option value="">默认(用第一个可用 provider)</option>
|
||||
{groups.map((g) => (
|
||||
<optgroup key={g} label={g}>
|
||||
{options.filter((o) => o.group === g).map((o) => (
|
||||
<option key={g + o.value} value={o.value}>{o.label}</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
case 'collection':
|
||||
return (
|
||||
<input className="field" list="kb-collections" value={value ?? ''}
|
||||
placeholder="default" onChange={(e) => onChange(e.target.value)} />
|
||||
)
|
||||
|
||||
case 'skills':
|
||||
return (
|
||||
<MultiPick
|
||||
options={catalog.skills.filter((s) => s.enabled).map((s) => ({ value: s.name, label: s.name, hint: s.description }))}
|
||||
value={Array.isArray(value) ? value : []}
|
||||
onChange={onChange}
|
||||
empty="还没有 Skill,去「方法论」页创建"
|
||||
/>
|
||||
)
|
||||
|
||||
case 'tools': {
|
||||
const options = catalog.tools.map((t) => ({
|
||||
value: t.id, label: t.name, hint: t.description, danger: t.dangerous, group: t.category,
|
||||
}))
|
||||
// tool 节点只选一个,agent 节点可以多选
|
||||
if (field.help?.includes('只能选一个')) {
|
||||
return (
|
||||
<select className="field" value={value ?? ''} onChange={(e) => onChange(e.target.value)}>
|
||||
<option value="">— 选择工具 —</option>
|
||||
{[...new Set(options.map((o) => o.group))].map((g) => (
|
||||
<optgroup key={g} label={g}>
|
||||
{options.filter((o) => o.group === g).map((o) => (
|
||||
<option key={o.value} value={o.value}>{o.label}{o.danger ? ' ⚠' : ''}</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<MultiPick options={options} value={Array.isArray(value) ? value : []} onChange={onChange}
|
||||
empty="没有可用工具" />
|
||||
)
|
||||
}
|
||||
|
||||
case 'ioFields':
|
||||
return <IoFieldList value={value ?? []} onChange={onChange} />
|
||||
|
||||
case 'cases':
|
||||
return <CaseList value={value ?? []} onChange={onChange} />
|
||||
|
||||
case 'agents':
|
||||
return <AgentList value={value ?? []} onChange={onChange} />
|
||||
|
||||
default:
|
||||
return <input className="field" value={value ?? ''} onChange={(e) => onChange(e.target.value)} />
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 复合编辑器
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function MultiPick({ options, value, onChange, empty }: {
|
||||
options: { value: string; label: string; hint?: string; danger?: boolean; group?: string }[]
|
||||
value: string[]; onChange: (v: string[]) => void; empty: string
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const toggle = (v: string) =>
|
||||
onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v])
|
||||
|
||||
const filtered = options.filter(
|
||||
(o) => !query || o.label.toLowerCase().includes(query.toLowerCase()) ||
|
||||
(o.hint ?? '').toLowerCase().includes(query.toLowerCase()),
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-1.5 flex flex-wrap gap-1">
|
||||
{value.map((v) => {
|
||||
const opt = options.find((o) => o.value === v)
|
||||
return (
|
||||
<span key={v} className="chip" style={{ borderColor: 'var(--accent)', color: 'var(--accent)' }}>
|
||||
{opt?.label ?? v}
|
||||
<button onClick={() => toggle(v)} className="ml-0.5 hover:opacity-60"><X size={9} /></button>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
{!value.length && <span className="text-[10.5px] text-faint">未选择</span>}
|
||||
</div>
|
||||
<button className="btn btn-sm w-full justify-center" onClick={() => setOpen(!open)}>
|
||||
<Plus size={11} /> {open ? '收起' : '添加'}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="mt-1.5 rounded border bg-bg">
|
||||
<input className="field rounded-b-none border-0 border-b" placeholder="搜索…"
|
||||
value={query} onChange={(e) => setQuery(e.target.value)} autoFocus />
|
||||
<div className="max-h-52 overflow-y-auto p-1">
|
||||
{!filtered.length && <div className="px-2 py-3 text-center text-[10.5px] text-faint">{empty}</div>}
|
||||
{filtered.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
onClick={() => toggle(o.value)}
|
||||
className={clsx(
|
||||
'flex w-full items-start gap-2 rounded px-2 py-1.5 text-left hover:bg-hover',
|
||||
value.includes(o.value) && 'bg-hover',
|
||||
)}
|
||||
>
|
||||
<input type="checkbox" readOnly checked={value.includes(o.value)}
|
||||
className="mt-0.5 accent-[var(--accent)]" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-[11.5px]">
|
||||
{o.label}
|
||||
{o.danger && <span className="ml-1 text-[9px] text-[var(--warn)]">需确认</span>}
|
||||
</span>
|
||||
{o.hint && <span className="block truncate text-[10px] text-faint">{o.hint}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ children, onRemove }: { children: React.ReactNode; onRemove: () => void }) {
|
||||
return (
|
||||
<div className="mb-1.5 rounded border bg-bg p-2">
|
||||
<div className="flex items-start gap-1.5">
|
||||
<div className="min-w-0 flex-1 space-y-1.5">{children}</div>
|
||||
<button className="btn btn-ghost btn-sm shrink-0" onClick={onRemove}>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function IoFieldList({ value, onChange }: { value: any[]; onChange: (v: any[]) => void }) {
|
||||
const update = (i: number, patch: any) =>
|
||||
onChange(value.map((f, idx) => (idx === i ? { ...f, ...patch } : f)))
|
||||
// 有 value 的是成果字段(output),有 required 的是输入字段
|
||||
const isOutput = value.some((f) => 'value' in f)
|
||||
|
||||
return (
|
||||
<div>
|
||||
{value.map((field, i) => (
|
||||
<Row key={i} onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<input className="field" placeholder="字段名" value={field.name ?? ''}
|
||||
onChange={(e) => update(i, { name: e.target.value })} />
|
||||
{isOutput ? (
|
||||
<input className="field mono text-[11px]" placeholder="{{ vars.xxx }}"
|
||||
value={field.value ?? ''} onChange={(e) => update(i, { value: e.target.value })} />
|
||||
) : (
|
||||
<>
|
||||
<input className="field" placeholder="说明(可选)" value={field.description ?? ''}
|
||||
onChange={(e) => update(i, { description: e.target.value })} />
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="flex items-center gap-1.5 text-[11px]">
|
||||
<input type="checkbox" checked={!!field.required} className="accent-[var(--accent)]"
|
||||
onChange={(e) => update(i, { required: e.target.checked })} />
|
||||
必填
|
||||
</label>
|
||||
<input className="field flex-1" placeholder="默认值" value={field.default ?? ''}
|
||||
onChange={(e) => update(i, { default: e.target.value })} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Row>
|
||||
))}
|
||||
<button className="btn btn-sm w-full justify-center"
|
||||
onClick={() => onChange([...value, isOutput ? { name: '', value: '' } : { name: '', required: false }])}>
|
||||
<Plus size={11} /> 添加字段
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CaseList({ value, onChange }: { value: any[]; onChange: (v: any[]) => void }) {
|
||||
const update = (i: number, patch: any) =>
|
||||
onChange(value.map((c, idx) => (idx === i ? { ...c, ...patch } : c)))
|
||||
return (
|
||||
<div>
|
||||
{value.map((c, i) => (
|
||||
<Row key={i} onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<input className="field" placeholder="分支标识(会成为连线出口)" value={c.key ?? ''}
|
||||
onChange={(e) => update(i, { key: e.target.value })} />
|
||||
<input className="field mono text-[11px]" placeholder="条件,如 len(vars.text) > 100"
|
||||
value={c.condition ?? ''} onChange={(e) => update(i, { condition: e.target.value })} />
|
||||
<input className="field" placeholder="说明(模型分类时作为类别描述)" value={c.label ?? ''}
|
||||
onChange={(e) => update(i, { label: e.target.value })} />
|
||||
</Row>
|
||||
))}
|
||||
<button className="btn btn-sm w-full justify-center"
|
||||
onClick={() => onChange([...value, { key: '', condition: '', label: '' }])}>
|
||||
<Plus size={11} /> 添加分支
|
||||
</button>
|
||||
<div className="mt-1.5 text-[10px] leading-snug text-faint">
|
||||
所有条件都不满足时走 default 出口,记得连一条
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AgentList({ value, onChange }: { value: any[]; onChange: (v: any[]) => void }) {
|
||||
const catalog = useCatalog()
|
||||
const update = (i: number, patch: any) =>
|
||||
onChange(value.map((a, idx) => (idx === i ? { ...a, ...patch } : a)))
|
||||
return (
|
||||
<div>
|
||||
{value.map((agent, i) => (
|
||||
<Row key={i} onRemove={() => onChange(value.filter((_, idx) => idx !== i))}>
|
||||
<input className="field" placeholder="成员名(英文,如 researcher)" value={agent.name ?? ''}
|
||||
onChange={(e) => update(i, { name: e.target.value })} />
|
||||
<input className="field" placeholder="职责一句话(调度者据此分派)" value={agent.description ?? ''}
|
||||
onChange={(e) => update(i, { description: e.target.value })} />
|
||||
<textarea className="field" rows={2} placeholder="角色设定 system prompt"
|
||||
value={agent.system ?? ''} onChange={(e) => update(i, { system: e.target.value })} />
|
||||
<MultiPick
|
||||
options={catalog.tools.map((t) => ({ value: t.id, label: t.name, hint: t.description, group: t.category }))}
|
||||
value={agent.tools ?? []} onChange={(v) => update(i, { tools: v })} empty="没有可用工具"
|
||||
/>
|
||||
</Row>
|
||||
))}
|
||||
<button className="btn btn-sm w-full justify-center"
|
||||
onClick={() => onChange([...value, { name: '', description: '', system: '', tools: [] }])}>
|
||||
<Plus size={11} /> 添加成员
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { memo } from 'react'
|
||||
import { Handle, Position, type NodeProps } from '@xyflow/react'
|
||||
import { AlertTriangle, Check, Hand, Loader2, Sparkles, Wrench } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { NODE_DEFS, sourceHandles } from './nodeDefs'
|
||||
import { useStudio, type FlowNode } from '../store/studio'
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
/** 卡片正文的一行摘要:不用打开属性面板就能看懂这个节点在干什么。 */
|
||||
function summarize(type: NodeType, config: Record<string, any>): string {
|
||||
const first = (...vals: any[]) => vals.find((v) => typeof v === 'string' && v.trim())?.trim() ?? ''
|
||||
switch (type) {
|
||||
case 'input':
|
||||
return (config.fields ?? []).map((f: any) => f.name).filter(Boolean).join(' · ') || '未定义输入'
|
||||
case 'output':
|
||||
return (config.fields ?? []).map((f: any) => f.name).filter(Boolean).join(' · ') || '未定义成果'
|
||||
case 'llm':
|
||||
return first(config.prompt, config.system) || '未填提示'
|
||||
case 'agent': {
|
||||
const tools = (config.tools ?? []).length
|
||||
return `${first(config.prompt, config.system) || '未填任务'}${tools ? ` · ${tools} 个工具` : ''}`
|
||||
}
|
||||
case 'supervisor':
|
||||
return `${(config.agents ?? []).map((a: any) => a.name).join(' / ') || '未配成员'}`
|
||||
case 'tool':
|
||||
return config.tool ? `${config.tool}()` : '未选择工具'
|
||||
case 'code':
|
||||
return `${config.language ?? 'python'} · ${(config.code ?? '').split('\n')[0].slice(0, 48) || '空'}`
|
||||
case 'branch':
|
||||
return (config.cases ?? []).map((c: any) => c.key).filter(Boolean).join(' / ') || '未配分支'
|
||||
case 'loop':
|
||||
return config.mode === 'while'
|
||||
? `当 ${config.condition || '?'} 时重复`
|
||||
: `遍历 ${config.items || '?'}`
|
||||
case 'retrieve':
|
||||
return `${config.collection || 'default'} · 取 ${config.limit ?? 5} 条`
|
||||
case 'memory':
|
||||
return `${{ recall: '回忆', write: '记住', clear: '清空' }[config.action as string] ?? ''} @ ${config.scope || 'default'}`
|
||||
case 'human':
|
||||
return first(config.title) || '等待人工'
|
||||
case 'validate':
|
||||
return 'JSON Schema 校验' + (config.repair_with_llm ? ' · 失败自动返工' : '')
|
||||
case 'transform':
|
||||
return first(config.expression, config.template) || '未配置'
|
||||
case 'subgraph':
|
||||
return config.workflow_id ? '嵌套工作流' : '未选择工作流'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function NodeCardImpl({ id, data, selected }: NodeProps<FlowNode>) {
|
||||
const def = NODE_DEFS[data.nodeType]
|
||||
const runtime = useStudio((s) => s.runtime[id])
|
||||
// selector 必须返回稳定引用:filter() 每次都造新数组,会触发无限重渲染
|
||||
const hasError = useStudio((s) => s.issues.some((i) => i.node_id === id && i.level === 'error'))
|
||||
const Icon = def?.icon ?? Sparkles
|
||||
const handles = sourceHandles(data.nodeType, data.config)
|
||||
const status = runtime?.status ?? 'idle'
|
||||
|
||||
const streamed = runtime?.tokens || runtime?.thinking
|
||||
const summary = summarize(data.nodeType, data.config)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
`nt-${data.nodeType} group relative rounded-lg border bg-elev transition-shadow`,
|
||||
status === 'running' && 'node-running',
|
||||
status === 'done' && 'node-done',
|
||||
status === 'failed' && 'node-failed',
|
||||
status === 'waiting' && 'node-waiting',
|
||||
selected && 'ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]',
|
||||
)}
|
||||
style={{ width: 238, borderColor: selected ? 'var(--accent)' : undefined }}
|
||||
>
|
||||
{def?.hasTarget && (
|
||||
<Handle type="target" position={Position.Left} style={{ left: -5 }} />
|
||||
)}
|
||||
|
||||
{/* 标题栏 */}
|
||||
<div className="flex items-center gap-2 rounded-t-lg px-2.5 py-2"
|
||||
style={{ background: 'color-mix(in srgb, var(--nt) 9%, transparent)' }}>
|
||||
<div
|
||||
className="flex h-5 w-5 shrink-0 items-center justify-center rounded"
|
||||
style={{ background: 'color-mix(in srgb, var(--nt) 20%, transparent)', color: 'var(--nt)' }}
|
||||
>
|
||||
<Icon size={12} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[12px] font-medium leading-tight">
|
||||
{data.label || def?.label}
|
||||
</div>
|
||||
</div>
|
||||
{status === 'running' && <Loader2 size={12} className="animate-spin" style={{ color: 'var(--nt)' }} />}
|
||||
{status === 'done' && <Check size={12} className="text-[var(--ok)]" />}
|
||||
{status === 'waiting' && <Hand size={12} className="text-[var(--warn)]" />}
|
||||
{status === 'failed' && <AlertTriangle size={12} className="text-[var(--err)]" />}
|
||||
{status === 'idle' && hasError && (
|
||||
<AlertTriangle size={12} className="text-[var(--err)] opacity-70" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 摘要 */}
|
||||
{summary && (
|
||||
<div className="px-2.5 pb-2 pt-1.5 text-[11px] leading-snug text-dim">
|
||||
<div className="line-clamp-2 break-words">{summary}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 运行态:实时流出来的内容 */}
|
||||
{streamed && status !== 'idle' && (
|
||||
<div className="mx-2 mb-2 max-h-20 overflow-hidden rounded border bg-bg px-2 py-1.5">
|
||||
{runtime?.thinking && !runtime?.tokens && (
|
||||
<div className="mb-1 text-[9.5px] uppercase tracking-wide text-faint">思考中</div>
|
||||
)}
|
||||
<div className="mono whitespace-pre-wrap break-words text-[10px] leading-relaxed text-dim">
|
||||
{(runtime?.tokens || runtime?.thinking || '').slice(-180)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 工具调用 */}
|
||||
{!!runtime?.toolCalls?.length && (
|
||||
<div className="mx-2 mb-2 flex flex-wrap gap-1">
|
||||
{runtime.toolCalls.slice(-4).map((call, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="chip"
|
||||
style={{
|
||||
borderColor: call.ok === false ? 'var(--err)' : undefined,
|
||||
color: call.ok === undefined ? 'var(--accent)' : undefined,
|
||||
}}
|
||||
title={call.result?.slice(0, 300)}
|
||||
>
|
||||
<Wrench size={8} />
|
||||
{call.tool}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 底部状态条 */}
|
||||
{(runtime?.durationMs != null || runtime?.error) && (
|
||||
<div className="flex items-center gap-2 border-t px-2.5 py-1">
|
||||
{runtime.durationMs != null && (
|
||||
<span className="text-[10px] text-faint">{formatMs(runtime.durationMs)}</span>
|
||||
)}
|
||||
{runtime.error && (
|
||||
<span className="truncate text-[10px] text-[var(--err)]" title={runtime.error}>
|
||||
{runtime.error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 出口:有名字的分支把标签显示出来,不用点开就知道哪条是哪条 */}
|
||||
{handles.map((handle, i) => {
|
||||
const top = handles.length === 1 ? '50%' : `${((i + 1) / (handles.length + 1)) * 100}%`
|
||||
return (
|
||||
<div key={handle.id}>
|
||||
<Handle
|
||||
id={handle.id}
|
||||
type="source"
|
||||
position={Position.Right}
|
||||
style={{ top, right: -5, borderColor: handle.color }}
|
||||
/>
|
||||
{handle.label && (
|
||||
<span
|
||||
className="pointer-events-none absolute left-full ml-2 -translate-y-1/2 whitespace-nowrap text-[9.5px]"
|
||||
style={{ top, color: handle.color ?? 'var(--text-faint)' }}
|
||||
>
|
||||
{handle.label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function formatMs(ms: number): string {
|
||||
if (ms < 1000) return `${ms}ms`
|
||||
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`
|
||||
return `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000)}s`
|
||||
}
|
||||
|
||||
export const NodeCard = memo(NodeCardImpl)
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useState } from 'react'
|
||||
import { NODE_CATEGORIES, NODE_DEFS } from './nodeDefs'
|
||||
import { useStudio } from '../store/studio'
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
/** 左侧节点库。拖到画布,或点一下放在视野中间。 */
|
||||
export function Palette() {
|
||||
const [query, setQuery] = useState('')
|
||||
const addNode = useStudio((s) => s.addNode)
|
||||
|
||||
const defs = Object.values(NODE_DEFS).filter(
|
||||
(d) =>
|
||||
!query ||
|
||||
d.label.includes(query) ||
|
||||
d.description.includes(query) ||
|
||||
d.type.includes(query.toLowerCase()),
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="border-b p-2">
|
||||
<input
|
||||
className="field"
|
||||
placeholder="搜索节点…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-2">
|
||||
{NODE_CATEGORIES.map((category) => {
|
||||
const items = defs.filter((d) => d.category === category)
|
||||
if (!items.length) return null
|
||||
return (
|
||||
<div key={category} className="mb-3">
|
||||
<div className="mb-1.5 px-1 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
{category}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{items.map((def) => (
|
||||
<div
|
||||
key={def.type}
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
e.dataTransfer.setData('application/agentlab-node', def.type)
|
||||
e.dataTransfer.effectAllowed = 'move'
|
||||
}}
|
||||
onClick={() =>
|
||||
addNode(def.type as NodeType, {
|
||||
x: 220 + Math.random() * 160,
|
||||
y: 160 + Math.random() * 200,
|
||||
})
|
||||
}
|
||||
className={`nt-${def.type} group flex cursor-grab items-start gap-2 rounded-md border border-transparent px-2 py-1.5 hover:border-[var(--border)] hover:bg-hover active:cursor-grabbing`}
|
||||
title={def.description}
|
||||
>
|
||||
<div
|
||||
className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded"
|
||||
style={{
|
||||
background: 'color-mix(in srgb, var(--nt) 18%, transparent)',
|
||||
color: 'var(--nt)',
|
||||
}}
|
||||
>
|
||||
<def.icon size={12} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11.5px] font-medium leading-tight">{def.label}</div>
|
||||
<div className="truncate text-[10px] leading-tight text-faint">
|
||||
{def.description}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{!defs.length && (
|
||||
<div className="px-2 py-6 text-center text-[11px] text-faint">没有匹配的节点</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="border-t px-3 py-2 text-[10px] leading-relaxed text-faint">
|
||||
拖到画布,或点击直接添加。<br />
|
||||
从节点右侧圆点拖到另一个节点左侧即可连线。
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
import {
|
||||
Bot, Braces, Brain, CheckCircle2, Code2, Database, FileInput, FileOutput,
|
||||
GitBranch, Hand, Repeat, Search, Shuffle, Users, Wrench,
|
||||
} from 'lucide-react'
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
export type FieldType =
|
||||
| 'text' | 'textarea' | 'prompt' | 'code' | 'number' | 'select' | 'switch'
|
||||
| 'json' | 'model' | 'tools' | 'skills' | 'collection'
|
||||
| 'ioFields' | 'cases' | 'agents'
|
||||
|
||||
export interface FieldDef {
|
||||
key: string
|
||||
label: string
|
||||
type: FieldType
|
||||
placeholder?: string
|
||||
help?: string
|
||||
options?: { value: string; label: string }[]
|
||||
min?: number
|
||||
max?: number
|
||||
step?: number
|
||||
/** 只在满足条件时显示,避免面板一次糊一屏用不上的选项 */
|
||||
when?: (config: Record<string, any>) => boolean
|
||||
advanced?: boolean
|
||||
}
|
||||
|
||||
export interface HandleDef {
|
||||
id: string
|
||||
label: string
|
||||
color?: string
|
||||
}
|
||||
|
||||
export interface NodeDef {
|
||||
type: NodeType
|
||||
label: string
|
||||
category: string
|
||||
description: string
|
||||
icon: typeof Bot
|
||||
hasTarget: boolean
|
||||
/** 静态出口;branch/loop 这类由配置动态生成的返回 null */
|
||||
sources: HandleDef[] | null
|
||||
fields: FieldDef[]
|
||||
defaults: Record<string, any>
|
||||
}
|
||||
|
||||
const MODEL_FIELDS: FieldDef[] = [
|
||||
{ key: 'model', label: '模型', type: 'model', help: '留空则用默认 provider' },
|
||||
{
|
||||
key: 'thinking', label: '思考模式', type: 'select', advanced: true,
|
||||
options: [
|
||||
{ value: '', label: '跟随模型默认' },
|
||||
{ value: 'summarized', label: '开启并显示摘要' },
|
||||
{ value: 'adaptive', label: '开启但不显示' },
|
||||
{ value: 'off', label: '关闭' },
|
||||
],
|
||||
help: 'Claude 4.6+ 默认会先思考再回答,思考也消耗 token',
|
||||
},
|
||||
{
|
||||
key: 'effort', label: '投入程度', type: 'select', advanced: true,
|
||||
options: [
|
||||
{ value: '', label: '默认' }, { value: 'low', label: 'low' },
|
||||
{ value: 'medium', label: 'medium' }, { value: 'high', label: 'high' },
|
||||
{ value: 'xhigh', label: 'xhigh' }, { value: 'max', label: 'max' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'temperature', label: '温度', type: 'number', min: 0, max: 2, step: 0.1, advanced: true,
|
||||
help: 'Claude 4.6 之后的模型不支持,填了也会被自动忽略',
|
||||
},
|
||||
{ key: 'max_tokens', label: '最大输出 token', type: 'number', min: 1, advanced: true },
|
||||
]
|
||||
|
||||
const COMMON_TAIL: FieldDef[] = [
|
||||
{
|
||||
key: 'assign_to', label: '结果存为变量', type: 'text', placeholder: '例如 result',
|
||||
help: '下游用 {{ vars.变量名 }} 引用',
|
||||
},
|
||||
{ key: 'skip_if', label: '跳过条件', type: 'text', advanced: true, placeholder: 'vars.count == 0' },
|
||||
{ key: 'retries', label: '失败重试次数', type: 'number', min: 0, max: 5, advanced: true },
|
||||
{
|
||||
key: 'on_error', label: '出错时', type: 'select', advanced: true,
|
||||
options: [{ value: '', label: '中断整个运行' }, { value: 'continue', label: '记录错误并继续' }],
|
||||
},
|
||||
]
|
||||
|
||||
export const NODE_DEFS: Record<NodeType, NodeDef> = {
|
||||
input: {
|
||||
type: 'input', label: '输入', category: '起止', icon: FileInput,
|
||||
description: '工作流入口,声明需要哪些输入',
|
||||
hasTarget: false, sources: [{ id: 'out', label: '' }],
|
||||
fields: [{ key: 'fields', label: '输入字段', type: 'ioFields' }],
|
||||
defaults: { fields: [{ name: 'question', required: true }] },
|
||||
},
|
||||
output: {
|
||||
type: 'output', label: '成果', category: '起止', icon: FileOutput,
|
||||
description: '收集最终结构化成果',
|
||||
hasTarget: true, sources: [],
|
||||
fields: [{ key: 'fields', label: '成果字段', type: 'ioFields' }],
|
||||
defaults: { fields: [{ name: '结果', value: '{{ last_message }}' }] },
|
||||
},
|
||||
llm: {
|
||||
type: 'llm', label: '模型调用', category: '模型', icon: Brain,
|
||||
description: '单次 LLM 调用,可要求结构化输出',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'system', label: '系统提示', type: 'textarea', placeholder: '你是…' },
|
||||
{ key: 'prompt', label: '用户提示', type: 'prompt', placeholder: '{{ input.question }}' },
|
||||
{ key: 'skills', label: '挂载 Skill', type: 'skills' },
|
||||
...MODEL_FIELDS,
|
||||
{
|
||||
key: 'output_schema', label: '结构化输出 Schema', type: 'json', advanced: true,
|
||||
help: '填了就强制模型按此 JSON Schema 返回',
|
||||
},
|
||||
{ key: 'use_history', label: '带上对话历史', type: 'switch', advanced: true },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { system: '', prompt: '{{ input.question }}' },
|
||||
},
|
||||
agent: {
|
||||
type: 'agent', label: 'Agent', category: '模型', icon: Bot,
|
||||
description: '带工具循环,自己决定调什么工具',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'system', label: '角色设定', type: 'textarea' },
|
||||
{ key: 'prompt', label: '任务', type: 'prompt' },
|
||||
{ key: 'tools', label: '可用工具', type: 'tools' },
|
||||
{ key: 'skills', label: '挂载 Skill', type: 'skills' },
|
||||
{ key: 'max_steps', label: '最大步数', type: 'number', min: 1, max: 25 },
|
||||
{
|
||||
key: 'approval', label: '工具审批', type: 'select',
|
||||
options: [
|
||||
{ value: 'dangerous', label: '仅危险工具需要确认' },
|
||||
{ value: 'always', label: '每次调用都确认' },
|
||||
{ value: 'never', label: '全部自动放行' },
|
||||
],
|
||||
help: '需要确认时运行会暂停,等你在审批面板放行',
|
||||
},
|
||||
...MODEL_FIELDS,
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { max_steps: 8, approval: 'dangerous', tools: [] },
|
||||
},
|
||||
supervisor: {
|
||||
type: 'supervisor', label: '多 Agent 协作', category: '模型', icon: Users,
|
||||
description: '调度者按进展把任务分派给多个专家',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'goal', label: '团队目标', type: 'prompt' },
|
||||
{ key: 'agents', label: '团队成员', type: 'agents' },
|
||||
{ key: 'max_rounds', label: '最大轮次', type: 'number', min: 1, max: 25 },
|
||||
...MODEL_FIELDS,
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { max_rounds: 6, agents: [] },
|
||||
},
|
||||
tool: {
|
||||
type: 'tool', label: '调用工具', category: '执行', icon: Wrench,
|
||||
description: '直接调用一个指定工具',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'tool', label: '工具', type: 'tools', help: '只能选一个' },
|
||||
{ key: 'args', label: '参数', type: 'json', help: '值里可以用 {{ }} 引用上游' },
|
||||
{
|
||||
key: 'approval', label: '执行前确认', type: 'select',
|
||||
options: [
|
||||
{ value: 'dangerous', label: '危险工具需要确认' },
|
||||
{ value: 'always', label: '总是确认' },
|
||||
{ value: 'never', label: '不确认' },
|
||||
],
|
||||
},
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { args: {}, approval: 'dangerous' },
|
||||
},
|
||||
code: {
|
||||
type: 'code', label: '沙箱代码', category: '执行', icon: Code2,
|
||||
description: '在隔离容器里执行代码',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{
|
||||
key: 'language', label: '语言', type: 'select',
|
||||
options: [
|
||||
{ value: 'python', label: 'Python' }, { value: 'bash', label: 'Bash' },
|
||||
{ value: 'node', label: 'Node.js' },
|
||||
],
|
||||
},
|
||||
{ key: 'code', label: '代码', type: 'code', help: '代码里可以用 {{ }} 插值' },
|
||||
{ key: 'timeout', label: '超时(秒)', type: 'number', min: 1, max: 300 },
|
||||
{ key: 'memory_mb', label: '内存上限 MB', type: 'number', min: 64, max: 4096, advanced: true },
|
||||
{ key: 'network', label: '允许联网', type: 'switch', help: '默认断网' },
|
||||
{
|
||||
key: 'approval', label: '执行前确认', type: 'select', advanced: true,
|
||||
options: [{ value: 'never', label: '不确认' }, { value: 'always', label: '总是确认(可改代码)' }],
|
||||
},
|
||||
{ key: 'fail_fast', label: '执行失败即中断', type: 'switch', advanced: true },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { language: 'python', code: 'print("hello")', timeout: 30, network: false, fail_fast: true },
|
||||
},
|
||||
branch: {
|
||||
type: 'branch', label: '条件分支', category: '控制', icon: GitBranch,
|
||||
description: '按条件或语义分类走不同的路',
|
||||
hasTarget: true, sources: null,
|
||||
fields: [
|
||||
{
|
||||
key: 'mode', label: '判断方式', type: 'select',
|
||||
options: [
|
||||
{ value: 'expression', label: '表达式判断' },
|
||||
{ value: 'llm', label: '让模型分类' },
|
||||
],
|
||||
},
|
||||
{ key: 'cases', label: '分支', type: 'cases' },
|
||||
{
|
||||
key: 'input', label: '待分类内容', type: 'prompt',
|
||||
when: (c) => c.mode === 'llm', placeholder: '{{ last_message }}',
|
||||
},
|
||||
{ key: 'instruction', label: '分类说明', type: 'textarea', when: (c) => c.mode === 'llm' },
|
||||
...MODEL_FIELDS.filter((f) => f.key === 'model').map((f) => ({
|
||||
...f, when: (c: any) => c.mode === 'llm',
|
||||
})),
|
||||
...COMMON_TAIL.filter((f) => f.key !== 'assign_to'),
|
||||
],
|
||||
defaults: { mode: 'expression', cases: [{ key: 'yes', condition: '', label: '' }] },
|
||||
},
|
||||
loop: {
|
||||
type: 'loop', label: '循环', category: '控制', icon: Repeat,
|
||||
description: '遍历列表或按条件重复执行',
|
||||
hasTarget: true, sources: null,
|
||||
fields: [
|
||||
{
|
||||
key: 'mode', label: '循环方式', type: 'select',
|
||||
options: [
|
||||
{ value: 'foreach', label: '遍历列表' },
|
||||
{ value: 'while', label: '条件成立时重复' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'items', label: '列表来源', type: 'text', when: (c) => c.mode !== 'while',
|
||||
placeholder: '{{ input.items }}',
|
||||
},
|
||||
{ key: 'item_var', label: '当前项变量名', type: 'text', when: (c) => c.mode !== 'while' },
|
||||
{
|
||||
key: 'condition', label: '继续条件', type: 'text', when: (c) => c.mode === 'while',
|
||||
placeholder: 'vars.done != true',
|
||||
},
|
||||
{ key: 'max_iterations', label: '最大迭代次数', type: 'number', min: 1, max: 100 },
|
||||
],
|
||||
defaults: { mode: 'foreach', item_var: 'item', max_iterations: 10 },
|
||||
},
|
||||
subgraph: {
|
||||
type: 'subgraph', label: '子工作流', category: '控制', icon: Braces,
|
||||
description: '把另一张工作流当成一个节点嵌进来',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'workflow_id', label: '工作流', type: 'select', options: [] },
|
||||
{ key: 'input', label: '传入参数', type: 'json' },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { input: {} },
|
||||
},
|
||||
memory: {
|
||||
type: 'memory', label: '长期记忆', category: '上下文', icon: Database,
|
||||
description: '读取或写入跨运行的长期记忆',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{
|
||||
key: 'action', label: '操作', type: 'select',
|
||||
options: [
|
||||
{ value: 'recall', label: '回忆(检索)' },
|
||||
{ value: 'write', label: '记住(写入)' },
|
||||
{ value: 'clear', label: '清空该作用域' },
|
||||
],
|
||||
},
|
||||
{ key: 'scope', label: '作用域', type: 'text', placeholder: 'default' },
|
||||
{ key: 'query', label: '回忆什么', type: 'prompt', when: (c) => c.action !== 'write' && c.action !== 'clear' },
|
||||
{ key: 'limit', label: '返回条数', type: 'number', min: 1, max: 20, when: (c) => c.action !== 'write' },
|
||||
{ key: 'content', label: '记住的内容', type: 'prompt', when: (c) => c.action === 'write' },
|
||||
{
|
||||
key: 'kind', label: '记忆类型', type: 'select', when: (c) => c.action === 'write',
|
||||
options: [
|
||||
{ value: 'fact', label: '事实' }, { value: 'preference', label: '偏好' },
|
||||
{ value: 'episode', label: '事件' },
|
||||
],
|
||||
},
|
||||
{ key: 'importance', label: '重要程度', type: 'number', min: 0, max: 1, step: 0.1, when: (c) => c.action === 'write' },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { action: 'recall', scope: 'default', limit: 5, query: '{{ last_message }}' },
|
||||
},
|
||||
retrieve: {
|
||||
type: 'retrieve', label: '知识检索', category: '上下文', icon: Search,
|
||||
description: '从知识库里混合检索相关片段',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'query', label: '检索问题', type: 'prompt' },
|
||||
{ key: 'collection', label: '知识库', type: 'collection' },
|
||||
{ key: 'limit', label: '返回片段数', type: 'number', min: 1, max: 20 },
|
||||
{
|
||||
key: 'alpha', label: '向量 vs 关键词', type: 'number', min: 0, max: 1, step: 0.1,
|
||||
help: '1 = 纯语义相似,0 = 纯关键词匹配',
|
||||
},
|
||||
{ key: 'min_score', label: '最低分数', type: 'number', min: 0, max: 1, step: 0.05, advanced: true },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { query: '{{ last_message }}', collection: 'default', limit: 5, alpha: 0.5 },
|
||||
},
|
||||
transform: {
|
||||
type: 'transform', label: '数据整形', category: '上下文', icon: Shuffle,
|
||||
description: '不调模型,直接把数据揉成下游要的形状',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{
|
||||
key: 'mode', label: '方式', type: 'select',
|
||||
options: [
|
||||
{ value: 'template', label: '文本模板' },
|
||||
{ value: 'expression', label: '表达式' },
|
||||
{ value: 'json', label: 'JSON 模板' },
|
||||
],
|
||||
},
|
||||
{ key: 'template', label: '模板', type: 'textarea', when: (c) => c.mode !== 'expression' },
|
||||
{
|
||||
key: 'expression', label: '表达式', type: 'text', when: (c) => c.mode === 'expression',
|
||||
placeholder: "len(vars.items)",
|
||||
},
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { mode: 'template', template: '{{ last_message }}' },
|
||||
},
|
||||
human: {
|
||||
type: 'human', label: '人工介入', category: '把关', icon: Hand,
|
||||
description: '暂停运行,等人确认或补充信息',
|
||||
hasTarget: true, sources: null,
|
||||
fields: [
|
||||
{
|
||||
key: 'mode', label: '介入方式', type: 'select',
|
||||
options: [
|
||||
{ value: 'approve', label: '批准 / 驳回' },
|
||||
{ value: 'input', label: '补充输入' },
|
||||
{ value: 'edit', label: '编辑草稿' },
|
||||
],
|
||||
},
|
||||
{ key: 'title', label: '标题', type: 'text' },
|
||||
{ key: 'message', label: '给人看的内容', type: 'prompt' },
|
||||
{ key: 'draft', label: '草稿内容', type: 'prompt', when: (c) => c.mode === 'edit' },
|
||||
{ key: 'stop_on_reject', label: '驳回即终止运行', type: 'switch', when: (c) => c.mode === 'approve' },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: { mode: 'approve', title: '需要你确认', message: '{{ last_message }}' },
|
||||
},
|
||||
validate: {
|
||||
type: 'validate', label: '结构校验', category: '把关', icon: CheckCircle2,
|
||||
description: '按 JSON Schema 校验,不合格可让模型自动返工',
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
fields: [
|
||||
{ key: 'source', label: '待校验内容', type: 'prompt', placeholder: '{{ last_message }}' },
|
||||
{ key: 'schema', label: 'JSON Schema', type: 'json' },
|
||||
{ key: 'max_retries', label: '最多返工次数', type: 'number', min: 0, max: 5 },
|
||||
{ key: 'repair_with_llm', label: '让模型修复', type: 'switch' },
|
||||
{ key: 'fail_fast', label: '校验失败即中断', type: 'switch' },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
defaults: {
|
||||
source: '{{ last_message }}', max_retries: 2, repair_with_llm: true, fail_fast: true,
|
||||
schema: { type: 'object', properties: {}, required: [] },
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const NODE_CATEGORIES = ['起止', '模型', '执行', '控制', '上下文', '把关']
|
||||
|
||||
/** branch / loop / human 的出口由配置决定,这里统一算出来。 */
|
||||
export function sourceHandles(type: NodeType, config: Record<string, any>): HandleDef[] {
|
||||
const def = NODE_DEFS[type]
|
||||
if (def.sources) return def.sources
|
||||
if (type === 'branch') {
|
||||
const cases = (config.cases ?? []) as { key?: string; label?: string }[]
|
||||
return [
|
||||
...cases
|
||||
.filter((c) => c.key)
|
||||
.map((c) => ({ id: c.key!, label: c.label || c.key!, color: 'var(--ok)' })),
|
||||
{ id: 'default', label: '其他', color: 'var(--text-faint)' },
|
||||
]
|
||||
}
|
||||
if (type === 'loop') {
|
||||
return [
|
||||
{ id: 'body', label: '循环体', color: 'var(--nt)' },
|
||||
{ id: 'done', label: '结束', color: 'var(--text-faint)' },
|
||||
]
|
||||
}
|
||||
if (type === 'human') {
|
||||
if (config.mode === 'approve') {
|
||||
return [
|
||||
{ id: 'approved', label: '通过', color: 'var(--ok)' },
|
||||
{ id: 'rejected', label: '驳回', color: 'var(--err)' },
|
||||
]
|
||||
}
|
||||
return [{ id: 'out', label: '' }]
|
||||
}
|
||||
return [{ id: 'out', label: '' }]
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { AlertCircle, CheckCircle2, Info, Loader2, X } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Toast
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
type ToastKind = 'info' | 'ok' | 'error'
|
||||
interface ToastItem { id: number; kind: ToastKind; text: string }
|
||||
|
||||
const ToastCtx = createContext<(text: string, kind?: ToastKind) => void>(() => {})
|
||||
export const useToast = () => useContext(ToastCtx)
|
||||
|
||||
export function ToastHost({ children }: { children: ReactNode }) {
|
||||
const [items, setItems] = useState<ToastItem[]>([])
|
||||
const push = useCallback((text: string, kind: ToastKind = 'info') => {
|
||||
const id = Date.now() + Math.random()
|
||||
setItems((prev) => [...prev, { id, kind, text }])
|
||||
setTimeout(() => setItems((prev) => prev.filter((t) => t.id !== id)), 4200)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ToastCtx.Provider value={push}>
|
||||
{children}
|
||||
<div className="fixed bottom-4 right-4 z-[100] flex flex-col gap-2 max-w-md">
|
||||
{items.map((t) => (
|
||||
<div
|
||||
key={t.id}
|
||||
className="fade-up flex items-start gap-2 rounded-lg border bg-panel px-3 py-2 shadow-xl"
|
||||
style={{ borderColor: t.kind === 'error' ? 'var(--err)' : 'var(--border)' }}
|
||||
>
|
||||
{t.kind === 'ok' && <CheckCircle2 size={14} className="mt-0.5 shrink-0 text-[var(--ok)]" />}
|
||||
{t.kind === 'error' && <AlertCircle size={14} className="mt-0.5 shrink-0 text-[var(--err)]" />}
|
||||
{t.kind === 'info' && <Info size={14} className="mt-0.5 shrink-0 text-dim" />}
|
||||
<span className="text-xs leading-relaxed whitespace-pre-wrap break-words">{t.text}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastCtx.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Modal
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
export function Modal({
|
||||
open, onClose, title, children, footer, width = 560,
|
||||
}: {
|
||||
open: boolean; onClose: () => void; title: ReactNode
|
||||
children: ReactNode; footer?: ReactNode; width?: number
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
|
||||
if (!open) return null
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4"
|
||||
onMouseDown={(e) => e.target === e.currentTarget && onClose()}
|
||||
>
|
||||
<div
|
||||
className="fade-up flex max-h-[88vh] w-full flex-col overflow-hidden rounded-xl border bg-panel shadow-2xl"
|
||||
style={{ maxWidth: width }}
|
||||
>
|
||||
<div className="flex items-center justify-between border-b px-4 py-3">
|
||||
<div className="text-sm font-semibold">{title}</div>
|
||||
<button className="btn btn-ghost btn-sm" onClick={onClose}><X size={14} /></button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-4">{children}</div>
|
||||
{footer && <div className="flex justify-end gap-2 border-t px-4 py-3">{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 杂项
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
export const Spinner = ({ size = 14 }: { size?: number }) => (
|
||||
<Loader2 size={size} className="animate-spin" />
|
||||
)
|
||||
|
||||
export function Empty({ icon, title, hint, action }: {
|
||||
icon?: ReactNode; title: string; hint?: string; action?: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 px-6 py-14 text-center">
|
||||
{icon && <div className="text-faint opacity-50">{icon}</div>}
|
||||
<div className="text-sm text-dim">{title}</div>
|
||||
{hint && <div className="max-w-sm text-xs text-faint leading-relaxed">{hint}</div>}
|
||||
{action && <div className="mt-2">{action}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Tabs({ tabs, active, onChange }: {
|
||||
tabs: { key: string; label: string; badge?: number }[]
|
||||
active: string
|
||||
onChange: (key: string) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex gap-1 border-b px-2">
|
||||
{tabs.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
onClick={() => onChange(t.key)}
|
||||
className={clsx(
|
||||
'relative px-3 py-2 text-xs transition-colors',
|
||||
active === t.key ? 'text-fg' : 'text-faint hover:text-dim',
|
||||
)}
|
||||
>
|
||||
{t.label}
|
||||
{t.badge != null && t.badge > 0 && (
|
||||
<span className="ml-1.5 rounded-full bg-[var(--accent)] px-1.5 text-[10px] text-white">
|
||||
{t.badge}
|
||||
</span>
|
||||
)}
|
||||
{active === t.key && (
|
||||
<span className="absolute inset-x-2 -bottom-px h-0.5 rounded bg-[var(--accent)]" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Section({ title, right, children, defaultOpen = true }: {
|
||||
title: string; right?: ReactNode; children: ReactNode; defaultOpen?: boolean
|
||||
}) {
|
||||
const [open, setOpen] = useState(defaultOpen)
|
||||
return (
|
||||
<div className="border-b last:border-b-0">
|
||||
<div className="flex items-center justify-between px-3 py-2">
|
||||
<button
|
||||
onClick={() => setOpen(!open)}
|
||||
className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-faint hover:text-dim"
|
||||
>
|
||||
<span className={clsx('transition-transform', open ? 'rotate-90' : '')}>›</span>
|
||||
{title}
|
||||
</button>
|
||||
{right}
|
||||
</div>
|
||||
{open && <div className="px-3 pb-3">{children}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function StatusDot({ status }: { status: string }) {
|
||||
const color =
|
||||
status === 'succeeded' ? 'var(--ok)'
|
||||
: status === 'failed' ? 'var(--err)'
|
||||
: status === 'running' ? 'var(--accent)'
|
||||
: status === 'interrupted' ? 'var(--warn)'
|
||||
: 'var(--text-faint)'
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span
|
||||
className={clsx('h-1.5 w-1.5 rounded-full', status === 'running' && 'animate-pulse')}
|
||||
style={{ background: color }}
|
||||
/>
|
||||
<span className="text-[11px]" style={{ color }}>{STATUS_LABEL[status] ?? status}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export const STATUS_LABEL: Record<string, string> = {
|
||||
queued: '排队中', running: '运行中', interrupted: '等待人工',
|
||||
succeeded: '成功', failed: '失败', cancelled: '已取消',
|
||||
}
|
||||
|
||||
/** 受控的 JSON 编辑框:输入过程中允许非法 JSON,失焦或合法时才回写。 */
|
||||
export function JsonInput({ value, onChange, rows = 5, placeholder }: {
|
||||
value: any; onChange: (v: any) => void; rows?: number; placeholder?: string
|
||||
}) {
|
||||
const [text, setText] = useState(() => (value == null ? '' : JSON.stringify(value, null, 2)))
|
||||
const [bad, setBad] = useState(false)
|
||||
const touched = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (touched.current) return
|
||||
setText(value == null ? '' : JSON.stringify(value, null, 2))
|
||||
}, [value])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<textarea
|
||||
className="field mono text-[11px]"
|
||||
rows={rows}
|
||||
value={text}
|
||||
placeholder={placeholder}
|
||||
style={bad ? { borderColor: 'var(--err)' } : undefined}
|
||||
onChange={(e) => {
|
||||
touched.current = true
|
||||
setText(e.target.value)
|
||||
if (!e.target.value.trim()) { setBad(false); onChange(undefined); return }
|
||||
try {
|
||||
onChange(JSON.parse(e.target.value))
|
||||
setBad(false)
|
||||
} catch {
|
||||
setBad(true)
|
||||
}
|
||||
}}
|
||||
onBlur={() => { touched.current = false }}
|
||||
/>
|
||||
{bad && <div className="mt-1 text-[10px] text-[var(--err)]">JSON 格式不对,还没保存</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CopyButton({ text }: { text: string }) {
|
||||
const [done, setDone] = useState(false)
|
||||
return (
|
||||
<button
|
||||
className="btn btn-ghost btn-sm"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(text)
|
||||
setDone(true)
|
||||
setTimeout(() => setDone(false), 1200)
|
||||
}}
|
||||
>
|
||||
{done ? '已复制' : '复制'}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
@import 'tailwindcss';
|
||||
@import '@xyflow/react/dist/style.css';
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
主题 token。深色是默认(长时间盯画布,深色更省眼),浅色由 data-theme 切换。
|
||||
-------------------------------------------------------------------------- */
|
||||
:root {
|
||||
--bg: #0b0e14;
|
||||
--bg-elev: #11151f;
|
||||
--bg-panel: #141926;
|
||||
--bg-hover: #1b2232;
|
||||
--border: #232a3a;
|
||||
--border-strong: #333c52;
|
||||
--text: #e4e8f1;
|
||||
--text-dim: #94a0b8;
|
||||
--text-faint: #5f6b82;
|
||||
--accent: #4f8cff;
|
||||
--accent-soft: #1e3a6b;
|
||||
--ok: #3fb950;
|
||||
--warn: #d29922;
|
||||
--err: #f85149;
|
||||
--canvas-dot: #1e2534;
|
||||
}
|
||||
|
||||
:root[data-theme='light'] {
|
||||
--bg: #f6f7f9;
|
||||
--bg-elev: #ffffff;
|
||||
--bg-panel: #ffffff;
|
||||
--bg-hover: #eef1f6;
|
||||
--border: #dfe3ea;
|
||||
--border-strong: #c3cad6;
|
||||
--text: #1a1f2b;
|
||||
--text-dim: #5a6579;
|
||||
--text-faint: #8b95a7;
|
||||
--accent: #2563eb;
|
||||
--accent-soft: #dbeafe;
|
||||
--ok: #1a7f37;
|
||||
--warn: #9a6700;
|
||||
--err: #cf222e;
|
||||
--canvas-dot: #d8dde6;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-bg: var(--bg);
|
||||
--color-elev: var(--bg-elev);
|
||||
--color-panel: var(--bg-panel);
|
||||
--color-hover: var(--bg-hover);
|
||||
--color-line: var(--border);
|
||||
--color-line-strong: var(--border-strong);
|
||||
--color-fg: var(--text);
|
||||
--color-dim: var(--text-dim);
|
||||
--color-faint: var(--text-faint);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-soft: var(--accent-soft);
|
||||
--color-ok: var(--ok);
|
||||
--color-warn: var(--warn);
|
||||
--color-err: var(--err);
|
||||
}
|
||||
|
||||
* {
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
|
||||
'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
||||
font-size: 13px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
code,
|
||||
pre,
|
||||
.mono {
|
||||
font-family: 'SF Mono', ui-monospace, 'JetBrains Mono', Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
/* 滚动条:细一点,不抢视觉 */
|
||||
::-webkit-scrollbar {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--border-strong);
|
||||
border-radius: 5px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--text-faint);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
节点类型配色。同一个色相贯穿:图标底色、边框、连线高亮。
|
||||
-------------------------------------------------------------------------- */
|
||||
.nt-input { --nt: #3fb950; }
|
||||
.nt-output { --nt: #a371f7; }
|
||||
.nt-llm { --nt: #4f8cff; }
|
||||
.nt-agent { --nt: #6366f1; }
|
||||
.nt-supervisor { --nt: #db61a2; }
|
||||
.nt-tool { --nt: #f0883e; }
|
||||
.nt-code { --nt: #2dd4bf; }
|
||||
.nt-branch { --nt: #d29922; }
|
||||
.nt-loop { --nt: #ec4899; }
|
||||
.nt-human { --nt: #f85149; }
|
||||
.nt-validate { --nt: #84cc16; }
|
||||
.nt-memory { --nt: #14b8a6; }
|
||||
.nt-retrieve { --nt: #0ea5e9; }
|
||||
.nt-transform { --nt: #8b949e; }
|
||||
.nt-subgraph { --nt: #bc8cff; }
|
||||
|
||||
/* --------------------------------------------------------------------------
|
||||
React Flow 覆盖
|
||||
-------------------------------------------------------------------------- */
|
||||
.react-flow {
|
||||
background: var(--bg);
|
||||
}
|
||||
.react-flow__attribution {
|
||||
display: none;
|
||||
}
|
||||
.react-flow__handle {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
background: var(--bg-elev);
|
||||
border: 2px solid var(--border-strong);
|
||||
transition: all 0.12s;
|
||||
}
|
||||
.react-flow__handle:hover {
|
||||
border-color: var(--accent);
|
||||
transform: scale(1.25);
|
||||
}
|
||||
.react-flow__handle-connecting {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.react-flow__edge-path {
|
||||
stroke: var(--border-strong);
|
||||
stroke-width: 1.6;
|
||||
}
|
||||
.react-flow__edge.selected .react-flow__edge-path {
|
||||
stroke: var(--accent);
|
||||
stroke-width: 2.4;
|
||||
}
|
||||
.react-flow__edge-text {
|
||||
fill: var(--text-dim);
|
||||
font-size: 10px;
|
||||
}
|
||||
.react-flow__controls-button {
|
||||
background: var(--bg-panel);
|
||||
border-color: var(--border);
|
||||
fill: var(--text-dim);
|
||||
}
|
||||
.react-flow__controls-button:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.react-flow__minimap {
|
||||
background: var(--bg-elev);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* 正在执行的边:让数据流动可见 */
|
||||
.react-flow__edge.edge-active .react-flow__edge-path {
|
||||
stroke: var(--accent);
|
||||
stroke-width: 2.4;
|
||||
stroke-dasharray: 6 4;
|
||||
animation: dash 0.5s linear infinite;
|
||||
}
|
||||
@keyframes dash {
|
||||
to {
|
||||
stroke-dashoffset: -10;
|
||||
}
|
||||
}
|
||||
|
||||
/* 节点运行状态 */
|
||||
@keyframes pulse-ring {
|
||||
0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--nt, #4f8cff) 55%, transparent); }
|
||||
70% { box-shadow: 0 0 0 9px transparent; }
|
||||
100% { box-shadow: 0 0 0 0 transparent; }
|
||||
}
|
||||
.node-running {
|
||||
animation: pulse-ring 1.4s ease-out infinite;
|
||||
border-color: var(--nt, #4f8cff) !important;
|
||||
}
|
||||
.node-done {
|
||||
border-color: color-mix(in srgb, var(--ok) 60%, transparent) !important;
|
||||
}
|
||||
.node-failed {
|
||||
border-color: var(--err) !important;
|
||||
}
|
||||
.node-waiting {
|
||||
border-color: var(--warn) !important;
|
||||
}
|
||||
|
||||
@keyframes fade-up {
|
||||
from { opacity: 0; transform: translateY(4px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
.fade-up {
|
||||
animation: fade-up 0.16s ease-out;
|
||||
}
|
||||
|
||||
/* 表单控件统一外观 */
|
||||
.field {
|
||||
width: 100%;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 6px 9px;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
transition: border-color 0.12s;
|
||||
}
|
||||
.field:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.field::placeholder {
|
||||
color: var(--text-faint);
|
||||
}
|
||||
textarea.field {
|
||||
resize: vertical;
|
||||
min-height: 62px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
select.field {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border-radius: 6px;
|
||||
padding: 6px 11px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-elev);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
transition: all 0.12s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: var(--bg-hover);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
filter: brightness(1.12);
|
||||
background: var(--accent);
|
||||
}
|
||||
.btn-danger {
|
||||
color: var(--err);
|
||||
border-color: color-mix(in srgb, var(--err) 40%, transparent);
|
||||
}
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
}
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.btn-sm {
|
||||
padding: 3px 7px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 1px 7px;
|
||||
border-radius: 999px;
|
||||
font-size: 10.5px;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text-dim);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
margin-bottom: 4px;
|
||||
font-weight: 500;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import { ToastHost } from './components/ui'
|
||||
import './index.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<ToastHost>
|
||||
<App />
|
||||
</ToastHost>
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,387 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { BookOpen, Brain, Plus, Search, Sparkles, Trash2, Upload } from 'lucide-react'
|
||||
import { api } from '../api/client'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { Empty, Modal, Spinner, Tabs, useToast } from '../components/ui'
|
||||
import type { KbDocument, MemoryItem, Skill } from '../types'
|
||||
|
||||
export function KnowledgePage() {
|
||||
const [tab, setTab] = useState('kb')
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ key: 'kb', label: '知识库' },
|
||||
{ key: 'memory', label: '长期记忆' },
|
||||
{ key: 'skills', label: '方法论 Skill' },
|
||||
]}
|
||||
active={tab}
|
||||
onChange={setTab}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{tab === 'kb' && <KbTab />}
|
||||
{tab === 'memory' && <MemoryTab />}
|
||||
{tab === 'skills' && <SkillsTab />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function KbTab() {
|
||||
const toast = useToast()
|
||||
const refreshCatalog = useCatalog((s) => s.refresh)
|
||||
const [collection, setCollection] = useState('default')
|
||||
const [collections, setCollections] = useState<any[]>([])
|
||||
const [docs, setDocs] = useState<KbDocument[]>([])
|
||||
const [query, setQuery] = useState('')
|
||||
const [hits, setHits] = useState<any[] | null>(null)
|
||||
const [alpha, setAlpha] = useState(0.5)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const load = async () => {
|
||||
setCollections(await api.kb.collections().catch(() => []))
|
||||
setDocs(await api.kb.documents(collection).catch(() => []))
|
||||
}
|
||||
useEffect(() => { void load() }, [collection])
|
||||
|
||||
const search = async () => {
|
||||
if (!query.trim()) { setHits(null); return }
|
||||
const res = await api.kb.search(query, collection, alpha)
|
||||
setHits(res.results ?? [])
|
||||
}
|
||||
|
||||
const upload = async (files: FileList | null) => {
|
||||
if (!files?.length) return
|
||||
for (const file of Array.from(files)) {
|
||||
try {
|
||||
await api.kb.upload(file, collection)
|
||||
toast(`已导入 ${file.name}`, 'ok')
|
||||
} catch (e: any) {
|
||||
toast(`${file.name}:${e.message}`, 'error')
|
||||
}
|
||||
}
|
||||
await load(); await refreshCatalog()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
<input className="field w-44" value={collection} list="collections"
|
||||
onChange={(e) => setCollection(e.target.value)} placeholder="知识库名称" />
|
||||
<datalist id="collections">
|
||||
{collections.map((c) => <option key={c.collection} value={c.collection} />)}
|
||||
</datalist>
|
||||
<div className="flex-1" />
|
||||
<button className="btn" onClick={() => fileRef.current?.click()}>
|
||||
<Upload size={12} /> 上传文件
|
||||
</button>
|
||||
<input ref={fileRef} type="file" multiple hidden accept=".txt,.md,.json,.csv,.log,.yaml,.yml,.py,.ts,.js"
|
||||
onChange={(e) => upload(e.target.files)} />
|
||||
<button className="btn btn-primary" onClick={() => setAdding(true)}>
|
||||
<Plus size={12} /> 粘贴文本
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-3 flex flex-wrap gap-1.5">
|
||||
{collections.map((c) => (
|
||||
<button key={c.collection} className="chip hover:border-[var(--accent)]"
|
||||
onClick={() => setCollection(c.collection)}
|
||||
style={c.collection === collection ? { borderColor: 'var(--accent)', color: 'var(--accent)' } : undefined}>
|
||||
{c.collection} · {c.documents} 篇 / {c.chunks} 片段
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 检索调试:能直观看到混合检索里语义和关键词各占多少 */}
|
||||
<div className="mb-4 rounded-lg border bg-panel p-3">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<input className="field" placeholder="测试检索效果…" value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && search()} />
|
||||
<button className="btn" onClick={search}><Search size={12} /> 检索</button>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-[11px] text-faint">
|
||||
关键词
|
||||
<input type="range" min={0} max={1} step={0.1} value={alpha} className="flex-1 accent-[var(--accent)]"
|
||||
onChange={(e) => setAlpha(Number(e.target.value))} />
|
||||
语义
|
||||
<span className="w-8 text-right">{alpha.toFixed(1)}</span>
|
||||
</label>
|
||||
|
||||
{hits && (
|
||||
<div className="mt-3 space-y-2">
|
||||
{!hits.length && <div className="text-[11px] text-faint">没有命中</div>}
|
||||
{hits.map((hit) => (
|
||||
<div key={hit.chunk_id} className="rounded border bg-bg p-2">
|
||||
<div className="mb-1 flex items-center gap-2 text-[10.5px] text-faint">
|
||||
<span className="font-medium text-dim">{hit.title}</span>
|
||||
<span>片段 {hit.ordinal}</span>
|
||||
<span className="ml-auto">总分 {hit.score}</span>
|
||||
<span>语义 {hit.signals?.vector?.toFixed(3)}</span>
|
||||
<span>关键词 {hit.signals?.keyword?.toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="line-clamp-3 text-[11px] leading-relaxed">{hit.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!docs.length && <Empty icon={<BookOpen size={22} />} title="这个知识库还是空的"
|
||||
hint="上传文本文件或粘贴内容,会自动切块并建立索引。" />}
|
||||
<div className="space-y-1.5">
|
||||
{docs.map((doc) => (
|
||||
<div key={doc.id} className="flex items-center gap-3 rounded-lg border bg-panel px-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[12px]">{doc.title}</div>
|
||||
<div className="truncate text-[10.5px] text-faint">{doc.source} · {doc.chunk_count} 个片段</div>
|
||||
</div>
|
||||
<button className="btn btn-sm btn-ghost" onClick={async () => {
|
||||
if (!confirm(`删除「${doc.title}」?`)) return
|
||||
await api.kb.remove(doc.id); await load(); await refreshCatalog()
|
||||
}}>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<AddDocModal open={adding} collection={collection} onClose={() => setAdding(false)}
|
||||
onSaved={async () => { setAdding(false); await load(); await refreshCatalog() }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AddDocModal({ open, collection, onClose, onSaved }: {
|
||||
open: boolean; collection: string; onClose: () => void; onSaved: () => void
|
||||
}) {
|
||||
const toast = useToast()
|
||||
const [title, setTitle] = useState('')
|
||||
const [content, setContent] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title={`添加到「${collection}」`} width={640}
|
||||
footer={<>
|
||||
<button className="btn" onClick={onClose}>取消</button>
|
||||
<button className="btn btn-primary" disabled={busy || !content.trim()} onClick={async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.kb.ingest({ collection, title, content })
|
||||
setTitle(''); setContent(''); onSaved(); toast('已导入并建立索引', 'ok')
|
||||
} catch (e: any) { toast(e.message ?? '导入失败', 'error') } finally { setBusy(false) }
|
||||
}}>{busy ? <Spinner /> : '导入'}</button>
|
||||
</>}>
|
||||
<div className="mb-3">
|
||||
<label className="label">标题</label>
|
||||
<input className="field" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="可留空" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">内容</label>
|
||||
<textarea className="field" rows={14} value={content} onChange={(e) => setContent(e.target.value)}
|
||||
placeholder="粘贴文本,会按段落自动切块" />
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function MemoryTab() {
|
||||
const toast = useToast()
|
||||
const [scope, setScope] = useState('default')
|
||||
const [scopes, setScopes] = useState<any[]>([])
|
||||
const [items, setItems] = useState<MemoryItem[]>([])
|
||||
const [text, setText] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [hits, setHits] = useState<any[] | null>(null)
|
||||
|
||||
const load = async () => {
|
||||
setScopes(await api.memory.scopes().catch(() => []))
|
||||
setItems(await api.memory.list(scope).catch(() => []))
|
||||
}
|
||||
useEffect(() => { void load() }, [scope])
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||
<input className="field w-44" value={scope} list="scopes" placeholder="作用域"
|
||||
onChange={(e) => setScope(e.target.value)} />
|
||||
<datalist id="scopes">{scopes.map((s) => <option key={s.scope} value={s.scope} />)}</datalist>
|
||||
{scopes.map((s) => (
|
||||
<button key={s.scope} className="chip hover:border-[var(--accent)]" onClick={() => setScope(s.scope)}
|
||||
style={s.scope === scope ? { borderColor: 'var(--accent)', color: 'var(--accent)' } : undefined}>
|
||||
{s.scope} · {s.count}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mb-3 flex gap-2">
|
||||
<input className="field" placeholder="写一条记忆,写完整的句子…" value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={async (e) => {
|
||||
if (e.key !== 'Enter' || !text.trim()) return
|
||||
await api.memory.add({ content: text, scope })
|
||||
setText(''); await load(); toast('已记住', 'ok')
|
||||
}} />
|
||||
<button className="btn btn-primary" disabled={!text.trim()} onClick={async () => {
|
||||
await api.memory.add({ content: text, scope }); setText(''); await load(); toast('已记住', 'ok')
|
||||
}}>
|
||||
<Plus size={12} /> 记住
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-3 flex gap-2">
|
||||
<input className="field" placeholder="测试回忆效果…" value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={async (e) => {
|
||||
if (e.key !== 'Enter') return
|
||||
setHits((await api.memory.search(query, scope)).results ?? [])
|
||||
}} />
|
||||
<button className="btn" onClick={async () => setHits((await api.memory.search(query, scope)).results ?? [])}>
|
||||
<Search size={12} /> 回忆
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{hits && (
|
||||
<div className="mb-4 rounded-lg border bg-panel p-2">
|
||||
<div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-faint">回忆结果</div>
|
||||
{!hits.length && <div className="px-1 py-2 text-[11px] text-faint">没有召回任何记忆</div>}
|
||||
{hits.map((h) => (
|
||||
<div key={h.id} className="border-b px-1 py-1.5 text-[11px] last:border-0">
|
||||
<span className="mr-2 text-[var(--accent)]">{h.score}</span>
|
||||
{h.content}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!items.length && <Empty icon={<Brain size={22} />} title="这个作用域还没有记忆"
|
||||
hint="记忆会跨运行保留,agent 可以用 memory_write / memory_recall 工具自己读写。" />}
|
||||
<div className="space-y-1.5">
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className="flex items-start gap-3 rounded-lg border bg-panel px-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[11.5px] leading-relaxed">{item.content}</div>
|
||||
<div className="mt-1 flex gap-2 text-[10px] text-faint">
|
||||
<span className="chip">{item.kind}</span>
|
||||
<span>重要度 {item.importance}</span>
|
||||
<span>被召回 {item.use_count} 次</span>
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn btn-sm btn-ghost" onClick={async () => {
|
||||
await api.memory.remove(item.id); await load()
|
||||
}}>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function SkillsTab() {
|
||||
const toast = useToast()
|
||||
const { skills, refresh } = useCatalog()
|
||||
const [editing, setEditing] = useState<Partial<Skill> | null>(null)
|
||||
|
||||
useEffect(() => { void refresh() }, [])
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl p-4">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-semibold">方法论 Skill</div>
|
||||
<div className="text-[11px] text-faint">
|
||||
可复用的做事方法。挂到 LLM / Agent 节点上,运行时注入 system prompt
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn btn-primary" onClick={() => setEditing({ examples: [], tags: [], enabled: true })}>
|
||||
<Plus size={12} /> 新建
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!skills.length && <Empty icon={<Sparkles size={22} />} title="还没有 Skill" />}
|
||||
<div className="space-y-2">
|
||||
{skills.map((skill) => (
|
||||
<div key={skill.id} className="rounded-lg border bg-panel p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[12.5px] font-medium">{skill.name}</span>
|
||||
{skill.tags?.map((t) => <span key={t} className="chip">{t}</span>)}
|
||||
<div className="flex-1" />
|
||||
<button className="btn btn-sm" onClick={() => setEditing(skill)}>编辑</button>
|
||||
<button className="btn btn-sm btn-ghost" onClick={async () => {
|
||||
if (!confirm(`删除「${skill.name}」?`)) return
|
||||
await api.skills.remove(skill.id); await refresh()
|
||||
}}>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-faint">{skill.description}</div>
|
||||
<pre className="mono mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded border bg-bg p-2 text-[10.5px] leading-relaxed text-dim">
|
||||
{skill.instructions}
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<SkillEditor skill={editing} onClose={() => setEditing(null)}
|
||||
onSaved={async () => { setEditing(null); await refresh(); toast('已保存', 'ok') }} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SkillEditor({ skill, onClose, onSaved }: {
|
||||
skill: Partial<Skill>; onClose: () => void; onSaved: () => void
|
||||
}) {
|
||||
const toast = useToast()
|
||||
const [form, setForm] = useState<any>({
|
||||
name: skill.name ?? '', description: skill.description ?? '',
|
||||
instructions: skill.instructions ?? '', tags: skill.tags ?? [],
|
||||
examples: skill.examples ?? [], suggested_tools: skill.suggested_tools ?? [],
|
||||
enabled: skill.enabled ?? true,
|
||||
})
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={skill.id ? '编辑 Skill' : '新建 Skill'} width={620}
|
||||
footer={<>
|
||||
<button className="btn" onClick={onClose}>取消</button>
|
||||
<button className="btn btn-primary" disabled={!form.name} onClick={async () => {
|
||||
try {
|
||||
if (skill.id) await api.skills.update(skill.id, form)
|
||||
else await api.skills.create(form)
|
||||
onSaved()
|
||||
} catch (e: any) { toast(e.message ?? '保存失败', 'error') }
|
||||
}}>保存</button>
|
||||
</>}>
|
||||
<div className="mb-3">
|
||||
<label className="label">名称</label>
|
||||
<input className="field" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">一句话说明</label>
|
||||
<input className="field" value={form.description}
|
||||
onChange={(e) => setForm({ ...form, description: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">指令内容(会拼进 system prompt)</label>
|
||||
<textarea className="field" rows={10} value={form.instructions}
|
||||
placeholder={'分析问题时遵循:\n1. 先给结论\n2. 区分事实与推断'}
|
||||
onChange={(e) => setForm({ ...form, instructions: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">标签(逗号分隔)</label>
|
||||
<input className="field" value={(form.tags ?? []).join(',')}
|
||||
onChange={(e) => setForm({ ...form, tags: e.target.value.split(',').map((s: string) => s.trim()).filter(Boolean) })} />
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { History, RefreshCw, Trash2 } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { formatMs } from '../canvas/NodeCard'
|
||||
import { Empty, Spinner, StatusDot, useToast } from '../components/ui'
|
||||
import type { Run, RunEvent } from '../types'
|
||||
|
||||
/** 运行历史。每次运行的完整事件流都落了库,所以这里能完整回放。 */
|
||||
export function RunsPage() {
|
||||
const toast = useToast()
|
||||
const [runs, setRuns] = useState<Run[]>([])
|
||||
const [selected, setSelected] = useState<Run | null>(null)
|
||||
const [events, setEvents] = useState<RunEvent[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [filter, setFilter] = useState('')
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true)
|
||||
setRuns(await api.runs.list({ limit: 100 }).catch(() => []))
|
||||
setLoading(false)
|
||||
}
|
||||
useEffect(() => { void load() }, [])
|
||||
|
||||
const open = async (run: Run) => {
|
||||
setSelected(run)
|
||||
setEvents(await api.runs.events(run.id).catch(() => []))
|
||||
}
|
||||
|
||||
const shown = runs.filter(
|
||||
(r) => !filter || r.workflow_name.includes(filter) || r.status === filter,
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
<div className="flex w-[380px] shrink-0 flex-col border-r">
|
||||
<div className="flex items-center gap-2 border-b p-2">
|
||||
<input className="field" placeholder="按名称或状态筛选…" value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)} />
|
||||
<button className="btn btn-sm" onClick={load}><RefreshCw size={11} /></button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{loading && <div className="p-4"><Spinner /></div>}
|
||||
{!loading && !shown.length && <Empty icon={<History size={22} />} title="还没有运行记录" />}
|
||||
{shown.map((run) => (
|
||||
<button
|
||||
key={run.id}
|
||||
onClick={() => open(run)}
|
||||
className={clsx(
|
||||
'flex w-full flex-col gap-1 border-b px-3 py-2 text-left hover:bg-hover',
|
||||
selected?.id === run.id && 'bg-hover',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-[12px]">{run.workflow_name || '临时图'}</span>
|
||||
<StatusDot status={run.status} />
|
||||
</div>
|
||||
<div className="flex gap-2 text-[10px] text-faint">
|
||||
<span>{run.created_at ? new Date(run.created_at).toLocaleString('zh-CN') : ''}</span>
|
||||
{run.usage?.duration_ms ? <span>{formatMs(run.usage.duration_ms)}</span> : null}
|
||||
{run.usage?.total_tokens ? <span>{run.usage.total_tokens} tok</span> : null}
|
||||
{run.usage?.cost_usd ? <span>${Number(run.usage.cost_usd).toFixed(4)}</span> : null}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 overflow-y-auto">
|
||||
{!selected && <Empty title="选一条运行记录" hint="左侧点击可以查看完整的执行轨迹、输入输出和用量。" />}
|
||||
{selected && (
|
||||
<div className="p-4">
|
||||
<div className="mb-3 flex items-start gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-semibold">{selected.workflow_name || '临时图'}</div>
|
||||
<div className="mono text-[10.5px] text-faint">{selected.id}</div>
|
||||
</div>
|
||||
<StatusDot status={selected.status} />
|
||||
<button
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={async () => {
|
||||
if (!confirm('删除这条运行记录?')) return
|
||||
await api.runs.remove(selected.id)
|
||||
setSelected(null)
|
||||
await load()
|
||||
toast('已删除', 'ok')
|
||||
}}
|
||||
>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{selected.error && (
|
||||
<pre className="mono mb-3 whitespace-pre-wrap rounded border p-2 text-[11px] text-[var(--err)]"
|
||||
style={{ borderColor: 'var(--err)' }}>
|
||||
{selected.error}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
<Block title="输入" data={selected.input} />
|
||||
<Block title="成果" data={selected.output} />
|
||||
<Block title="用量" data={selected.usage} />
|
||||
|
||||
<div className="mb-1.5 mt-4 text-[11px] font-semibold uppercase tracking-wide text-faint">
|
||||
执行轨迹({events.length} 条事件)
|
||||
</div>
|
||||
<div className="rounded border">
|
||||
{events.map((e) => (
|
||||
<div key={e.seq} className="flex gap-2 border-b px-2 py-1 text-[10.5px] last:border-0">
|
||||
<span className="w-10 shrink-0 text-faint">#{e.seq}</span>
|
||||
<span className="w-32 shrink-0 text-[var(--accent)]">{e.type}</span>
|
||||
<span className="w-24 shrink-0 truncate text-dim">{e.node_id ?? ''}</span>
|
||||
<span className="min-w-0 flex-1 break-all text-faint">
|
||||
{JSON.stringify(e.data).slice(0, 240)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{!events.length && <div className="p-3 text-center text-[11px] text-faint">没有事件记录</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Block({ title, data }: { title: string; data: any }) {
|
||||
if (!data || !Object.keys(data).length) return null
|
||||
return (
|
||||
<div className="mb-3">
|
||||
<div className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-faint">{title}</div>
|
||||
<pre className="mono max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border bg-panel p-2 text-[11px] leading-relaxed">
|
||||
{JSON.stringify(data, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Check, Cpu, KeyRound, Plus, Radio, Trash2, X } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { Empty, Modal, Spinner, Tabs, useToast } from '../components/ui'
|
||||
import type { Provider } from '../types'
|
||||
|
||||
export function SettingsPage() {
|
||||
const [tab, setTab] = useState('providers')
|
||||
return (
|
||||
<div className="mx-auto flex h-full w-full max-w-4xl flex-col">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ key: 'providers', label: '模型接入' },
|
||||
{ key: 'prefs', label: '偏好设置' },
|
||||
{ key: 'system', label: '运行环境' },
|
||||
]}
|
||||
active={tab}
|
||||
onChange={setTab}
|
||||
/>
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{tab === 'providers' && <ProvidersTab />}
|
||||
{tab === 'prefs' && <PrefsTab />}
|
||||
{tab === 'system' && <SystemTab />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function ProvidersTab() {
|
||||
const toast = useToast()
|
||||
const { providers, refresh } = useCatalog()
|
||||
const [editing, setEditing] = useState<Provider | 'new' | null>(null)
|
||||
const [testing, setTesting] = useState<string | null>(null)
|
||||
const [results, setResults] = useState<Record<string, any>>({})
|
||||
|
||||
const test = async (p: Provider) => {
|
||||
setTesting(p.id)
|
||||
try {
|
||||
const res = await api.providers.test(p.id, { model: p.default_model ?? undefined })
|
||||
setResults({ ...results, [p.id]: res })
|
||||
toast(res.ok ? `连通,${res.latency_ms}ms` : `失败:${res.error}`, res.ok ? 'ok' : 'error')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '测试失败', 'error')
|
||||
} finally {
|
||||
setTesting(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-semibold">模型接入</div>
|
||||
<div className="text-[11px] text-faint">
|
||||
API Key 加密后存在本地 SQLite,不会回传给浏览器
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn btn-primary" onClick={() => setEditing('new')}>
|
||||
<Plus size={12} /> 添加
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{providers.map((p) => {
|
||||
const result = results[p.id]
|
||||
return (
|
||||
<div key={p.id} className="rounded-lg border bg-panel p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={clsx('h-2 w-2 rounded-full')}
|
||||
style={{ background: p.enabled ? 'var(--ok)' : 'var(--text-faint)' }} />
|
||||
<span className="text-[12.5px] font-medium">{p.name}</span>
|
||||
<span className="chip">{p.kind}</span>
|
||||
{p.default_model && <span className="chip">{p.default_model}</span>}
|
||||
<div className="flex-1" />
|
||||
<button className="btn btn-sm" disabled={testing === p.id} onClick={() => test(p)}>
|
||||
{testing === p.id ? <Spinner size={11} /> : <Radio size={11} />} 测试
|
||||
</button>
|
||||
<button className="btn btn-sm" onClick={() => setEditing(p)}>编辑</button>
|
||||
<button
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={async () => {
|
||||
if (!confirm(`删除 ${p.name}?`)) return
|
||||
await api.providers.remove(p.id)
|
||||
await refresh()
|
||||
}}
|
||||
>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-1.5 flex flex-wrap gap-3 text-[10.5px] text-faint">
|
||||
{p.base_url && <span className="mono">{p.base_url}</span>}
|
||||
{p.has_key && <span className="mono">key {p.api_key_masked}</span>}
|
||||
{(p.extra as any)?.auth_style === 'bearer' && <span>Bearer 认证</span>}
|
||||
<span>{p.models?.length ?? 0} 个模型</span>
|
||||
</div>
|
||||
{result && (
|
||||
<div
|
||||
className="mt-2 rounded border p-2 text-[11px] leading-relaxed"
|
||||
style={{ borderColor: result.ok ? 'var(--ok)' : 'var(--err)' }}
|
||||
>
|
||||
{result.ok ? (
|
||||
<>
|
||||
<div className="mb-1 text-[var(--ok)]">✓ {result.latency_ms}ms · {result.model}</div>
|
||||
<div className="text-dim">{result.reply}</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-[var(--err)] break-all">{result.error}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{!providers.length && <Empty icon={<KeyRound size={22} />} title="还没有配置模型" />}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<ProviderEditor
|
||||
provider={editing === 'new' ? null : editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => { setEditing(null); void refresh() }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderEditor({ provider, onClose, onSaved }: {
|
||||
provider: Provider | null; onClose: () => void; onSaved: () => void
|
||||
}) {
|
||||
const toast = useToast()
|
||||
const [catalog, setCatalog] = useState<any>(null)
|
||||
const [form, setForm] = useState<any>(() => ({
|
||||
name: provider?.name ?? '',
|
||||
kind: provider?.kind ?? 'anthropic',
|
||||
base_url: provider?.base_url ?? '',
|
||||
api_key: '',
|
||||
default_model: provider?.default_model ?? '',
|
||||
models: provider?.models ?? [],
|
||||
enabled: provider?.enabled ?? true,
|
||||
extra: provider?.extra ?? {},
|
||||
}))
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => { void api.providers.catalog().then(setCatalog) }, [])
|
||||
|
||||
const kindDef = catalog?.kinds?.find((k: any) => k.kind === form.kind)
|
||||
|
||||
const applyPreset = (preset: any) => {
|
||||
setForm({
|
||||
...form,
|
||||
name: form.name || preset.label,
|
||||
base_url: preset.base_url,
|
||||
models: preset.models,
|
||||
default_model: preset.models?.[0]?.id ?? '',
|
||||
})
|
||||
}
|
||||
|
||||
const pickKind = (kind: string) => {
|
||||
const def = catalog?.kinds?.find((k: any) => k.kind === kind)
|
||||
setForm({
|
||||
...form, kind,
|
||||
models: def?.models ?? [],
|
||||
default_model: def?.default_model ?? '',
|
||||
name: form.name || def?.label || '',
|
||||
})
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const payload = { ...form, base_url: form.base_url || null }
|
||||
if (provider && !form.api_key) delete payload.api_key // 不填就保持原 key
|
||||
if (provider) await api.providers.update(provider.id, payload)
|
||||
else await api.providers.create(payload)
|
||||
toast('已保存', 'ok')
|
||||
onSaved()
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '保存失败', 'error')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={onClose}
|
||||
title={provider ? `编辑 ${provider.name}` : '添加模型接入'}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn" onClick={onClose}>取消</button>
|
||||
<button className="btn btn-primary" onClick={submit} disabled={busy || !form.name}>
|
||||
{busy ? <Spinner /> : <Check size={12} />} 保存
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{!provider && (
|
||||
<div className="mb-3">
|
||||
<label className="label">类型</label>
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
{catalog?.kinds?.map((k: any) => (
|
||||
<button
|
||||
key={k.kind}
|
||||
onClick={() => pickKind(k.kind)}
|
||||
className={clsx(
|
||||
'rounded-lg border px-3 py-2 text-left text-[11.5px] hover:bg-hover',
|
||||
form.kind === k.kind && 'border-[var(--accent)]',
|
||||
)}
|
||||
>
|
||||
{k.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!provider && form.kind === 'openai_compatible' && !!kindDef?.presets?.length && (
|
||||
<div className="mb-3">
|
||||
<label className="label">快速填充</label>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{kindDef.presets.map((p: any) => (
|
||||
<button key={p.key} className="chip hover:border-[var(--accent)]" onClick={() => applyPreset(p)}>
|
||||
{p.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="label">名称</label>
|
||||
<input className="field" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</div>
|
||||
|
||||
{form.kind !== 'mock' && (
|
||||
<>
|
||||
<div className="mb-3">
|
||||
<label className="label">Base URL</label>
|
||||
<input className="field mono text-[11px]" value={form.base_url}
|
||||
placeholder={kindDef?.base_url_hint}
|
||||
onChange={(e) => setForm({ ...form, base_url: e.target.value })} />
|
||||
{kindDef?.base_url_hint && (
|
||||
<div className="mt-1 text-[10px] text-faint">{kindDef.base_url_hint}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="label">API Key</label>
|
||||
<input
|
||||
className="field mono text-[11px]" type="password" autoComplete="off"
|
||||
value={form.api_key}
|
||||
placeholder={provider?.has_key ? `已设置(${provider.api_key_masked}),留空则不修改` : 'sk-…'}
|
||||
onChange={(e) => setForm({ ...form, api_key: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{form.kind === 'anthropic' && (
|
||||
<label className="mb-3 flex items-center gap-2 text-[11.5px]">
|
||||
<input
|
||||
type="checkbox" className="accent-[var(--accent)]"
|
||||
checked={form.extra?.auth_style === 'bearer'}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, extra: { ...form.extra, auth_style: e.target.checked ? 'bearer' : undefined } })
|
||||
}
|
||||
/>
|
||||
用 Authorization: Bearer 认证
|
||||
<span className="text-[10px] text-faint">(部分中转网关需要,官方 API 不用勾)</span>
|
||||
</label>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="label">默认模型</label>
|
||||
<input className="field mono text-[11px]" value={form.default_model} list="model-list"
|
||||
onChange={(e) => setForm({ ...form, default_model: e.target.value })} />
|
||||
<datalist id="model-list">
|
||||
{form.models?.map((m: any) => <option key={m.id} value={m.id}>{m.label}</option>)}
|
||||
</datalist>
|
||||
</div>
|
||||
|
||||
<div className="mb-1">
|
||||
<label className="label">可选模型({form.models?.length ?? 0})</label>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{form.models?.map((m: any) => (
|
||||
<span key={m.id} className="chip">
|
||||
{m.label || m.id}
|
||||
<button
|
||||
onClick={() => setForm({ ...form, models: form.models.filter((x: any) => x.id !== m.id) })}
|
||||
className="hover:opacity-60"
|
||||
>
|
||||
<X size={9} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1.5 flex gap-1.5">
|
||||
<input
|
||||
className="field mono text-[11px]" placeholder="模型 id,回车添加"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Enter') return
|
||||
const id = (e.target as HTMLInputElement).value.trim()
|
||||
if (!id) return
|
||||
setForm({ ...form, models: [...(form.models ?? []), { id, label: id }] })
|
||||
;(e.target as HTMLInputElement).value = ''
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="mt-3 flex items-center gap-2 text-[11.5px]">
|
||||
<input type="checkbox" className="accent-[var(--accent)]" checked={form.enabled}
|
||||
onChange={(e) => setForm({ ...form, enabled: e.target.checked })} />
|
||||
启用
|
||||
</label>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function PrefsTab() {
|
||||
const toast = useToast()
|
||||
const [values, setValues] = useState<Record<string, any> | null>(null)
|
||||
|
||||
useEffect(() => { void api.settings.get().then(setValues) }, [])
|
||||
if (!values) return <Spinner />
|
||||
|
||||
const set = (group: string, key: string, value: any) =>
|
||||
setValues({ ...values, [group]: { ...values[group], [key]: value } })
|
||||
|
||||
const save = async () => {
|
||||
await api.settings.put(values)
|
||||
toast('已保存', 'ok')
|
||||
}
|
||||
|
||||
const theme = values.ui?.theme ?? 'system'
|
||||
|
||||
return (
|
||||
<div className="max-w-xl space-y-4">
|
||||
<div>
|
||||
<div className="mb-2 text-sm font-semibold">界面</div>
|
||||
<label className="label">主题</label>
|
||||
<select
|
||||
className="field"
|
||||
value={theme}
|
||||
onChange={(e) => {
|
||||
set('ui', 'theme', e.target.value)
|
||||
applyTheme(e.target.value)
|
||||
}}
|
||||
>
|
||||
<option value="system">跟随系统</option>
|
||||
<option value="dark">深色</option>
|
||||
<option value="light">浅色</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-2 text-sm font-semibold">运行默认值</div>
|
||||
<label className="label">默认记忆作用域</label>
|
||||
<input className="field" value={values.run?.default_memory_scope ?? 'default'}
|
||||
onChange={(e) => set('run', 'default_memory_scope', e.target.value)} />
|
||||
<label className="label mt-2">默认知识库</label>
|
||||
<input className="field" value={values.run?.default_collection ?? 'default'}
|
||||
onChange={(e) => set('run', 'default_collection', e.target.value)} />
|
||||
<label className="mt-3 flex items-center gap-2 text-[11.5px]">
|
||||
<input type="checkbox" className="accent-[var(--accent)]"
|
||||
checked={values.run?.confirm_dangerous_tools ?? true}
|
||||
onChange={(e) => set('run', 'confirm_dangerous_tools', e.target.checked)} />
|
||||
危险工具默认需要人工确认
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button className="btn btn-primary" onClick={save}><Check size={12} /> 保存设置</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function applyTheme(theme: string) {
|
||||
const root = document.documentElement
|
||||
if (theme === 'system') root.removeAttribute('data-theme')
|
||||
else root.setAttribute('data-theme', theme)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function SystemTab() {
|
||||
const [info, setInfo] = useState<any>(null)
|
||||
useEffect(() => { void api.system().then(setInfo) }, [])
|
||||
if (!info) return <Spinner />
|
||||
|
||||
const sandbox = info.sandbox ?? {}
|
||||
return (
|
||||
<div className="max-w-2xl space-y-4">
|
||||
<div className="rounded-lg border bg-panel p-3">
|
||||
<div className="mb-2 flex items-center gap-1.5 text-sm font-semibold">
|
||||
<Cpu size={13} /> 沙箱
|
||||
</div>
|
||||
<div className="space-y-1 text-[11.5px]">
|
||||
<Row label="后端" value={
|
||||
<span style={{ color: sandbox.available ? 'var(--ok)' : 'var(--err)' }}>
|
||||
{sandbox.backend}{sandbox.available ? '(可用)' : '(不可用)'}
|
||||
</span>
|
||||
} />
|
||||
<Row label="选择原因" value={sandbox.selected_because} />
|
||||
{sandbox.image && <Row label="镜像" value={`${sandbox.image}${sandbox.image_pulled ? '' : '(未拉取,首次执行会自动拉)'}`} />}
|
||||
{sandbox.docker_version && <Row label="Docker" value={sandbox.docker_version} />}
|
||||
{sandbox.warning && (
|
||||
<div className="mt-2 rounded border px-2 py-1.5 text-[10.5px]"
|
||||
style={{ borderColor: 'var(--warn)', color: 'var(--warn)' }}>
|
||||
{sandbox.warning}
|
||||
</div>
|
||||
)}
|
||||
{sandbox.defaults && (
|
||||
<Row label="默认限额" value={
|
||||
`${sandbox.defaults.timeout}s · ${sandbox.defaults.memory_mb}MB · ${sandbox.defaults.cpus} CPU · ${sandbox.defaults.network ? '联网' : '断网'}`
|
||||
} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-panel p-3">
|
||||
<div className="mb-2 text-sm font-semibold">运行环境</div>
|
||||
<div className="space-y-1 text-[11.5px]">
|
||||
<Row label="Python" value={info.python} />
|
||||
<Row label="数据目录" value={<code className="mono text-[10.5px]">{info.data_dir}</code>} />
|
||||
<Row label="图最大步数" value={info.limits?.max_graph_steps} />
|
||||
<Row label="Agent 最大步数" value={info.limits?.max_agent_steps} />
|
||||
<Row label="最大并发运行" value={info.limits?.max_concurrent_runs} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ label, value }: { label: string; value: any }) {
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<span className="w-28 shrink-0 text-faint">{label}</span>
|
||||
<span className="min-w-0 flex-1 break-all">{value}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
AlertTriangle, Check, ChevronDown, Copy, LayoutGrid, Plus, Save, Sparkles, Trash2, Wand2,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { FlowCanvas } from '../canvas/FlowCanvas'
|
||||
import { Inspector } from '../canvas/Inspector'
|
||||
import { Palette } from '../canvas/Palette'
|
||||
import { RunPanel } from '../run/RunPanel'
|
||||
import { useStudio, toGraph } from '../store/studio'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { Empty, Modal, Spinner, Tabs, useToast } from '../components/ui'
|
||||
import type { Workflow } from '../types'
|
||||
|
||||
export function StudioPage() {
|
||||
const toast = useToast()
|
||||
const { workflows, refresh } = useCatalog()
|
||||
const workflow = useStudio((s) => s.workflow)
|
||||
const dirty = useStudio((s) => s.dirty)
|
||||
const issues = useStudio((s) => s.issues)
|
||||
const selectedId = useStudio((s) => s.selectedId)
|
||||
const streaming = useStudio((s) => s.streaming)
|
||||
const { load, save, setGraph } = useStudio()
|
||||
|
||||
const [tab, setTab] = useState<'inspect' | 'run'>('run')
|
||||
const [picker, setPicker] = useState(false)
|
||||
const [copilot, setCopilot] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// 首次进来自动打开第一张图
|
||||
useEffect(() => {
|
||||
if (!workflow && workflows.length) load(workflows[0])
|
||||
}, [workflows, workflow, load])
|
||||
|
||||
// 选中节点时自动切到属性页,省一次点击
|
||||
useEffect(() => {
|
||||
if (selectedId) setTab('inspect')
|
||||
}, [selectedId])
|
||||
useEffect(() => {
|
||||
if (streaming) setTab('run')
|
||||
}, [streaming])
|
||||
|
||||
const doSave = useCallback(async () => {
|
||||
if (!workflow) return
|
||||
setSaving(true)
|
||||
try {
|
||||
await save()
|
||||
toast('已保存', 'ok')
|
||||
void refresh()
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '保存失败', 'error')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}, [workflow, save, toast, refresh])
|
||||
|
||||
// Cmd/Ctrl+S 保存
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
|
||||
e.preventDefault()
|
||||
void doSave()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [doSave])
|
||||
|
||||
const errorCount = issues.filter((i) => i.level === 'error').length
|
||||
const warnCount = issues.filter((i) => i.level === 'warning').length
|
||||
|
||||
const relayout = async () => {
|
||||
const { nodes, edges } = useStudio.getState()
|
||||
try {
|
||||
setGraph(await api.copilot.layout(toGraph(nodes, edges)))
|
||||
toast('已重新排版', 'ok')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '排版失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
if (!workflows.length) {
|
||||
return (
|
||||
<Empty
|
||||
title="还没有工作流"
|
||||
hint="新建一张空白图,或者用 Copilot 直接把想法生成出来。"
|
||||
action={<NewWorkflowButton onDone={refresh} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{/* 工具栏 */}
|
||||
<div className="flex shrink-0 items-center gap-2 border-b px-3 py-2">
|
||||
<button className="btn btn-ghost gap-1.5" onClick={() => setPicker(true)}>
|
||||
<span className="max-w-56 truncate font-medium">{workflow?.name ?? '选择工作流'}</span>
|
||||
<ChevronDown size={12} className="text-faint" />
|
||||
</button>
|
||||
|
||||
{dirty && <span className="chip" style={{ color: 'var(--warn)' }}>未保存</span>}
|
||||
{errorCount > 0 && (
|
||||
<span className="chip" style={{ color: 'var(--err)', borderColor: 'var(--err)' }}>
|
||||
<AlertTriangle size={9} /> {errorCount} 个错误
|
||||
</span>
|
||||
)}
|
||||
{errorCount === 0 && warnCount > 0 && (
|
||||
<span className="chip" style={{ color: 'var(--warn)' }}>{warnCount} 个提示</span>
|
||||
)}
|
||||
{errorCount === 0 && warnCount === 0 && useStudio.getState().nodes.length > 0 && (
|
||||
<span className="chip" style={{ color: 'var(--ok)' }}><Check size={9} /> 可运行</span>
|
||||
)}
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
<button className="btn" onClick={() => setCopilot(true)} title="用自然语言生成或修改工作流">
|
||||
<Wand2 size={12} /> Copilot
|
||||
</button>
|
||||
<button className="btn" onClick={relayout} title="自动排版"><LayoutGrid size={12} /></button>
|
||||
<button className="btn btn-primary" onClick={doSave} disabled={saving || !dirty}>
|
||||
{saving ? <Spinner /> : <Save size={12} />} 保存
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 三栏 */}
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<aside className="w-52 shrink-0 border-r bg-panel">
|
||||
<Palette />
|
||||
</aside>
|
||||
<main className="min-w-0 flex-1">
|
||||
<FlowCanvas />
|
||||
</main>
|
||||
<aside className="flex w-[360px] shrink-0 flex-col border-l bg-panel">
|
||||
<Tabs
|
||||
tabs={[{ key: 'run', label: '运行' }, { key: 'inspect', label: '属性' }]}
|
||||
active={tab}
|
||||
onChange={(k) => setTab(k as any)}
|
||||
/>
|
||||
<div className="min-h-0 flex-1">
|
||||
{tab === 'inspect' ? <Inspector /> : <RunPanel />}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<WorkflowPicker open={picker} onClose={() => setPicker(false)} />
|
||||
<CopilotModal open={copilot} onClose={() => setCopilot(false)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function NewWorkflowButton({ onDone }: { onDone: () => void }) {
|
||||
const load = useStudio((s) => s.load)
|
||||
const toast = useToast()
|
||||
return (
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={async () => {
|
||||
const name = prompt('工作流名称', '新工作流')
|
||||
if (!name) return
|
||||
try {
|
||||
const created = await api.workflows.create({
|
||||
name,
|
||||
graph: {
|
||||
nodes: [
|
||||
{
|
||||
id: 'start', type: 'input', position: { x: 100, y: 260 },
|
||||
data: { label: '输入', config: { fields: [{ name: 'question', required: true }] } },
|
||||
},
|
||||
{
|
||||
id: 'done', type: 'output', position: { x: 460, y: 260 },
|
||||
data: { label: '成果', config: { fields: [{ name: '结果', value: '{{ last_message }}' }] } },
|
||||
},
|
||||
],
|
||||
edges: [{ source: 'start', target: 'done' }],
|
||||
},
|
||||
})
|
||||
load(created)
|
||||
onDone()
|
||||
toast('已创建', 'ok')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '创建失败', 'error')
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Plus size={12} /> 新建工作流
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function WorkflowPicker({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const { workflows, refresh } = useCatalog()
|
||||
const load = useStudio((s) => s.load)
|
||||
const current = useStudio((s) => s.workflow)
|
||||
const toast = useToast()
|
||||
|
||||
const act = async (fn: () => Promise<any>, msg: string) => {
|
||||
try {
|
||||
await fn()
|
||||
await refresh()
|
||||
toast(msg, 'ok')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '操作失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="工作流" width={680}
|
||||
footer={<NewWorkflowButton onDone={() => { void refresh(); onClose() }} />}>
|
||||
<div className="space-y-1">
|
||||
{workflows.map((w: Workflow) => (
|
||||
<div
|
||||
key={w.id}
|
||||
className={clsx(
|
||||
'group flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2 hover:bg-hover',
|
||||
current?.id === w.id && 'border-[var(--accent)]',
|
||||
)}
|
||||
onClick={() => { load(w); onClose() }}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-[12.5px] font-medium">{w.name}</span>
|
||||
{w.is_template && <span className="chip">模板</span>}
|
||||
{w.tags?.map((t) => <span key={t} className="chip">{t}</span>)}
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-faint">{w.description}</div>
|
||||
</div>
|
||||
<span className="shrink-0 text-[10px] text-faint">
|
||||
{w.graph?.nodes?.length ?? 0} 节点 · v{w.version}
|
||||
{w.run_count ? ` · 跑过 ${w.run_count} 次` : ''}
|
||||
</span>
|
||||
<button
|
||||
className="btn btn-ghost btn-sm opacity-0 group-hover:opacity-100"
|
||||
title="复制一份"
|
||||
onClick={(e) => { e.stopPropagation(); void act(() => api.workflows.duplicate(w.id), '已复制') }}
|
||||
>
|
||||
<Copy size={11} />
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost btn-sm opacity-0 group-hover:opacity-100"
|
||||
title="删除"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm(`删除「${w.name}」?运行记录也会一并删除。`)) {
|
||||
void act(() => api.workflows.remove(w.id), '已删除')
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function CopilotModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const toast = useToast()
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
const setGraph = useStudio((s) => s.setGraph)
|
||||
const [instruction, setInstruction] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [result, setResult] = useState<{ explanation: string; issues: any[] } | null>(null)
|
||||
const [useBase, setUseBase] = useState(true)
|
||||
|
||||
const generate = async () => {
|
||||
if (!instruction.trim()) return
|
||||
setBusy(true)
|
||||
setResult(null)
|
||||
try {
|
||||
const res = await api.copilot.generate({
|
||||
instruction,
|
||||
base_graph: useBase && nodes.length ? toGraph(nodes, edges) : null,
|
||||
})
|
||||
setGraph(res.graph)
|
||||
setResult({ explanation: res.explanation, issues: res.issues })
|
||||
toast('已生成,记得检查后保存', 'ok')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '生成失败', 'error')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const examples = [
|
||||
'读取用户上传的问题,先查知识库,查到就基于资料回答并标注出处,查不到就联网搜索',
|
||||
'把一段长文本拆成要点,逐条用模型打分,低分的让模型重写一次,最后汇总成表格',
|
||||
'写代码分析数据,在沙箱里跑,出错就把报错喂回去让模型修,最多修三次',
|
||||
]
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={<span className="flex items-center gap-1.5"><Sparkles size={14} /> Copilot 生成工作流</span>}
|
||||
width={620}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn" onClick={onClose}>关闭</button>
|
||||
<button className="btn btn-primary" onClick={generate} disabled={busy || !instruction.trim()}>
|
||||
{busy ? <Spinner /> : <Wand2 size={12} />} 生成到画布
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<label className="label">描述你想要的工作流</label>
|
||||
<textarea
|
||||
className="field"
|
||||
rows={4}
|
||||
value={instruction}
|
||||
onChange={(e) => setInstruction(e.target.value)}
|
||||
placeholder="用大白话说清楚:输入是什么、中间要做哪几步、遇到什么情况走不同分支、最后要什么结果"
|
||||
/>
|
||||
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{examples.map((ex) => (
|
||||
<button key={ex} className="chip hover:border-[var(--accent)]" onClick={() => setInstruction(ex)}>
|
||||
{ex.slice(0, 26)}…
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!!nodes.length && (
|
||||
<label className="mt-3 flex items-center gap-2 text-[11.5px]">
|
||||
<input type="checkbox" checked={useBase} onChange={(e) => setUseBase(e.target.checked)}
|
||||
className="accent-[var(--accent)]" />
|
||||
在当前这张图的基础上修改(不勾则重新生成)
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="mt-2 text-[10.5px] leading-relaxed text-faint">
|
||||
生成结果会直接铺到画布上并自动排版,但<b>不会自动保存</b>——先看一遍再决定。
|
||||
</div>
|
||||
|
||||
{result && (
|
||||
<div className="mt-3 border-t pt-3">
|
||||
<div className="label">Copilot 说明</div>
|
||||
<div className="whitespace-pre-wrap rounded border bg-bg p-2 text-[11.5px] leading-relaxed">
|
||||
{result.explanation || '(无)'}
|
||||
</div>
|
||||
{!!result.issues.length && (
|
||||
<div className="mt-2 space-y-1">
|
||||
{result.issues.map((issue, i) => (
|
||||
<div key={i} className="text-[10.5px]"
|
||||
style={{ color: issue.level === 'error' ? 'var(--err)' : 'var(--warn)' }}>
|
||||
{issue.level === 'error' ? '✕' : '!'} {issue.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Play, Plug, Plus, RefreshCw, Terminal, Trash2, Wrench } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { Empty, JsonInput, Modal, Spinner, Tabs, useToast } from '../components/ui'
|
||||
import type { ToolInfo } from '../types'
|
||||
|
||||
export function ToolsPage() {
|
||||
const [tab, setTab] = useState('tools')
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ key: 'tools', label: '工具库' },
|
||||
{ key: 'sandbox', label: '沙箱试验台' },
|
||||
{ key: 'custom', label: '自定义工具' },
|
||||
{ key: 'mcp', label: 'MCP 接入' },
|
||||
]}
|
||||
active={tab}
|
||||
onChange={setTab}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{tab === 'tools' && <ToolLibrary />}
|
||||
{tab === 'sandbox' && <SandboxLab />}
|
||||
{tab === 'custom' && <CustomTools />}
|
||||
{tab === 'mcp' && <McpServers />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function ToolLibrary() {
|
||||
const tools = useCatalog((s) => s.tools)
|
||||
const [picked, setPicked] = useState<ToolInfo | null>(null)
|
||||
const [args, setArgs] = useState<any>({})
|
||||
const [result, setResult] = useState<any>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
const run = async () => {
|
||||
if (!picked) return
|
||||
setBusy(true)
|
||||
setResult(null)
|
||||
try {
|
||||
setResult(await api.tools.run(picked.id, args ?? {}))
|
||||
} catch (e: any) {
|
||||
setResult({ ok: false, error: e.message })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const shown = tools.filter(
|
||||
(t) => !query || t.name.includes(query) || t.description.includes(query) || t.category.includes(query),
|
||||
)
|
||||
const groups = [...new Set(shown.map((t) => t.category))]
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
<div className="flex w-[340px] shrink-0 flex-col border-r">
|
||||
<div className="border-b p-2">
|
||||
<input className="field" placeholder="搜索工具…" value={query}
|
||||
onChange={(e) => setQuery(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-2">
|
||||
{groups.map((g) => (
|
||||
<div key={g} className="mb-3">
|
||||
<div className="mb-1 px-1 text-[10px] font-semibold uppercase tracking-wider text-faint">{g}</div>
|
||||
{shown.filter((t) => t.category === g).map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => { setPicked(t); setArgs({}); setResult(null) }}
|
||||
className={clsx(
|
||||
'w-full rounded px-2 py-1.5 text-left hover:bg-hover',
|
||||
picked?.id === t.id && 'bg-hover',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="mono text-[11.5px]">{t.name}</span>
|
||||
{t.dangerous && <span className="chip" style={{ color: 'var(--warn)' }}>需确认</span>}
|
||||
</div>
|
||||
<div className="truncate text-[10px] text-faint">{t.description}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
{!shown.length && <Empty icon={<Wrench size={20} />} title="没有匹配的工具" />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 overflow-y-auto p-4">
|
||||
{!picked && <Empty title="选一个工具试试" hint="不用搭图就能单独调用工具,验证参数和返回格式。" />}
|
||||
{picked && (
|
||||
<div className="max-w-2xl">
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<span className="mono text-sm font-semibold">{picked.name}</span>
|
||||
<span className="chip">{picked.source}</span>
|
||||
</div>
|
||||
<div className="mb-3 text-[11.5px] leading-relaxed text-dim">{picked.description}</div>
|
||||
|
||||
<label className="label">参数</label>
|
||||
<JsonInput value={args} onChange={setArgs} rows={6} placeholder="{}" />
|
||||
|
||||
{!!picked.schema?.properties && (
|
||||
<div className="mt-2 rounded border bg-panel p-2">
|
||||
<div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-faint">参数说明</div>
|
||||
{Object.entries(picked.schema.properties as Record<string, any>).map(([key, spec]) => (
|
||||
<div key={key} className="flex gap-2 py-0.5 text-[11px]">
|
||||
<code className="mono w-32 shrink-0 text-[var(--accent)]">{key}</code>
|
||||
<span className="w-16 shrink-0 text-faint">{spec.type}</span>
|
||||
<span className="min-w-0 flex-1 text-dim">
|
||||
{spec.description ?? ''}
|
||||
{(picked.schema.required ?? []).includes(key) && (
|
||||
<span className="ml-1 text-[var(--err)]">必填</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button className="btn btn-primary mt-3" onClick={run} disabled={busy}>
|
||||
{busy ? <Spinner /> : <Play size={12} />} 执行
|
||||
</button>
|
||||
|
||||
{result && (
|
||||
<div className="mt-3">
|
||||
<div className="label">结果 {result.duration_ms != null && `· ${result.duration_ms}ms`}</div>
|
||||
<pre
|
||||
className="mono max-h-96 overflow-auto whitespace-pre-wrap break-words rounded border bg-panel p-2 text-[11px] leading-relaxed"
|
||||
style={{ borderColor: result.ok === false ? 'var(--err)' : undefined }}
|
||||
>
|
||||
{result.ok === false
|
||||
? result.error
|
||||
: typeof result.result === 'string'
|
||||
? result.result
|
||||
: JSON.stringify(result.result, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function SandboxLab() {
|
||||
const [code, setCode] = useState(
|
||||
'import sys, platform\nprint("Python", sys.version.split()[0], "on", platform.machine())\nprint(sum(range(101)))',
|
||||
)
|
||||
const [language, setLanguage] = useState('python')
|
||||
const [network, setNetwork] = useState(false)
|
||||
const [timeout_, setTimeout_] = useState(30)
|
||||
const [result, setResult] = useState<any>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [health, setHealth] = useState<any>(null)
|
||||
|
||||
useEffect(() => { void api.sandbox.health().then(setHealth) }, [])
|
||||
|
||||
const run = async () => {
|
||||
setBusy(true)
|
||||
setResult(null)
|
||||
try {
|
||||
setResult(await api.sandbox.exec({ code, language, network, timeout: timeout_ }))
|
||||
} catch (e: any) {
|
||||
setResult({ ok: false, error: e.message })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl p-4">
|
||||
{health && (
|
||||
<div className="mb-3 flex flex-wrap items-center gap-2 rounded-lg border bg-panel px-3 py-2 text-[11px]">
|
||||
<Terminal size={12} />
|
||||
<span>后端 <b>{health.backend}</b></span>
|
||||
<span className="text-faint">·</span>
|
||||
<span style={{ color: health.available ? 'var(--ok)' : 'var(--err)' }}>
|
||||
{health.available ? '可用' : '不可用'}
|
||||
</span>
|
||||
<span className="text-faint">· {health.selected_because}</span>
|
||||
{health.warning && <span className="text-[var(--warn)]">· {health.warning}</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<select className="field w-28" value={language} onChange={(e) => setLanguage(e.target.value)}>
|
||||
<option value="python">Python</option>
|
||||
<option value="bash">Bash</option>
|
||||
<option value="node">Node.js</option>
|
||||
</select>
|
||||
<label className="flex items-center gap-1.5 text-[11.5px]">
|
||||
超时
|
||||
<input className="field w-16" type="number" value={timeout_}
|
||||
onChange={(e) => setTimeout_(Number(e.target.value))} />
|
||||
秒
|
||||
</label>
|
||||
<label className="flex items-center gap-1.5 text-[11.5px]">
|
||||
<input type="checkbox" className="accent-[var(--accent)]" checked={network}
|
||||
onChange={(e) => setNetwork(e.target.checked)} />
|
||||
允许联网
|
||||
</label>
|
||||
<div className="flex-1" />
|
||||
<button className="btn btn-primary" onClick={run} disabled={busy}>
|
||||
{busy ? <Spinner /> : <Play size={12} />} 执行
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<textarea className="field mono text-[11.5px]" rows={14} spellCheck={false}
|
||||
value={code} onChange={(e) => setCode(e.target.value)} />
|
||||
|
||||
{result && (
|
||||
<div className="mt-3">
|
||||
<div className="mb-1 flex flex-wrap items-center gap-2 text-[11px]">
|
||||
<span style={{ color: result.ok ? 'var(--ok)' : 'var(--err)' }}>
|
||||
{result.ok ? '✓ 成功' : `✕ 失败 (exit ${result.exit_code})`}
|
||||
</span>
|
||||
{result.duration_ms != null && <span className="text-faint">{result.duration_ms}ms</span>}
|
||||
{result.backend && <span className="chip">{result.backend}</span>}
|
||||
{result.timed_out && <span className="chip" style={{ color: 'var(--warn)' }}>超时</span>}
|
||||
</div>
|
||||
{result.stdout && (
|
||||
<pre className="mono max-h-72 overflow-auto whitespace-pre-wrap rounded border bg-panel p-2 text-[11px]">
|
||||
{result.stdout}
|
||||
</pre>
|
||||
)}
|
||||
{result.stderr && (
|
||||
<pre className="mono mt-2 max-h-52 overflow-auto whitespace-pre-wrap rounded border p-2 text-[11px] text-[var(--err)]"
|
||||
style={{ borderColor: 'var(--err)' }}>
|
||||
{result.stderr}
|
||||
</pre>
|
||||
)}
|
||||
{result.error && <div className="mt-2 text-[11px] text-[var(--err)]">{result.error}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function CustomTools() {
|
||||
const toast = useToast()
|
||||
const refresh = useCatalog((s) => s.refresh)
|
||||
const [rows, setRows] = useState<any[]>([])
|
||||
const [editing, setEditing] = useState<any | null>(null)
|
||||
|
||||
const load = async () => setRows(await api.customTools.list().catch(() => []))
|
||||
useEffect(() => { void load() }, [])
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl p-4">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-semibold">自定义工具</div>
|
||||
<div className="text-[11px] text-faint">HTTP 模板,或跑在沙箱里的一段 Python</div>
|
||||
</div>
|
||||
<button className="btn btn-primary" onClick={() => setEditing({ kind: 'http', config: {}, parameters: {} })}>
|
||||
<Plus size={12} /> 新建
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!rows.length && <Empty icon={<Wrench size={20} />} title="还没有自定义工具" />}
|
||||
<div className="space-y-2">
|
||||
{rows.map((row) => (
|
||||
<div key={row.id} className="flex items-center gap-2 rounded-lg border bg-panel p-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="mono text-[12px] font-medium">{row.name}</span>
|
||||
<span className="chip">{row.kind}</span>
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-faint">{row.description}</div>
|
||||
</div>
|
||||
<button className="btn btn-sm" onClick={() => setEditing(row)}>编辑</button>
|
||||
<button
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={async () => {
|
||||
if (!confirm(`删除 ${row.name}?`)) return
|
||||
await api.customTools.remove(row.id)
|
||||
await load(); await refresh()
|
||||
}}
|
||||
>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<CustomToolEditor
|
||||
row={editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={async () => { setEditing(null); await load(); await refresh(); toast('已保存', 'ok') }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CustomToolEditor({ row, onClose, onSaved }: { row: any; onClose: () => void; onSaved: () => void }) {
|
||||
const toast = useToast()
|
||||
const [form, setForm] = useState<any>({
|
||||
name: row.name ?? '', description: row.description ?? '', kind: row.kind ?? 'http',
|
||||
parameters: row.parameters ?? { type: 'object', properties: {}, required: [] },
|
||||
config: row.config ?? {}, enabled: row.enabled ?? true,
|
||||
})
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
if (row.id) await api.customTools.update(row.id, form)
|
||||
else await api.customTools.create(form)
|
||||
onSaved()
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '保存失败', 'error')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={row.id ? '编辑工具' : '新建工具'} width={620}
|
||||
footer={<>
|
||||
<button className="btn" onClick={onClose}>取消</button>
|
||||
<button className="btn btn-primary" onClick={submit} disabled={busy || !form.name}>保存</button>
|
||||
</>}>
|
||||
<div className="mb-3">
|
||||
<label className="label">名称(英文,模型按这个名字调用)</label>
|
||||
<input className="field mono" value={form.name} placeholder="my_tool"
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">描述(模型据此决定什么时候用它,写清楚很重要)</label>
|
||||
<textarea className="field" rows={2} value={form.description}
|
||||
onChange={(e) => setForm({ ...form, description: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">类型</label>
|
||||
<select className="field" value={form.kind} onChange={(e) => setForm({ ...form, kind: e.target.value })}>
|
||||
<option value="http">HTTP 请求</option>
|
||||
<option value="python">Python(沙箱执行)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">参数 JSON Schema</label>
|
||||
<JsonInput value={form.parameters} onChange={(v) => setForm({ ...form, parameters: v })} rows={6} />
|
||||
</div>
|
||||
|
||||
{form.kind === 'http' ? (
|
||||
<>
|
||||
<div className="mb-3">
|
||||
<label className="label">URL(可以用 {'{{ 参数名 }}'} 插值)</label>
|
||||
<input className="field mono text-[11px]" value={form.config.url ?? ''}
|
||||
placeholder="https://api.example.com/search?q={{ query }}"
|
||||
onChange={(e) => setForm({ ...form, config: { ...form.config, url: e.target.value } })} />
|
||||
</div>
|
||||
<div className="mb-3 flex gap-2">
|
||||
<div className="w-32">
|
||||
<label className="label">方法</label>
|
||||
<select className="field" value={form.config.method ?? 'GET'}
|
||||
onChange={(e) => setForm({ ...form, config: { ...form.config, method: e.target.value } })}>
|
||||
{['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((m) => <option key={m}>{m}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<label className="mt-6 flex items-center gap-1.5 text-[11.5px]">
|
||||
<input type="checkbox" className="accent-[var(--accent)]" checked={!!form.config.parse_json}
|
||||
onChange={(e) => setForm({ ...form, config: { ...form.config, parse_json: e.target.checked } })} />
|
||||
把响应按 JSON 解析
|
||||
</label>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">请求头</label>
|
||||
<JsonInput value={form.config.headers ?? {}} rows={3}
|
||||
onChange={(v) => setForm({ ...form, config: { ...form.config, headers: v } })} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">请求体(JSON,可插值)</label>
|
||||
<JsonInput value={form.config.body} rows={4}
|
||||
onChange={(v) => setForm({ ...form, config: { ...form.config, body: v } })} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<label className="label">Python 代码(参数在 args 变量里,用 print 输出结果)</label>
|
||||
<textarea
|
||||
className="field mono text-[11px]" rows={10} spellCheck={false}
|
||||
value={form.config.code ?? ''}
|
||||
placeholder={'import json\nprint(json.dumps({"echo": args}))'}
|
||||
onChange={(e) => setForm({ ...form, config: { ...form.config, code: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function McpServers() {
|
||||
const toast = useToast()
|
||||
const refresh = useCatalog((s) => s.refresh)
|
||||
const [rows, setRows] = useState<any[]>([])
|
||||
const [editing, setEditing] = useState<any | null>(null)
|
||||
const [probing, setProbing] = useState<string | null>(null)
|
||||
|
||||
const load = async () => setRows(await api.mcp.list().catch(() => []))
|
||||
useEffect(() => { void load() }, [])
|
||||
|
||||
const probe = async (row: any) => {
|
||||
setProbing(row.id)
|
||||
try {
|
||||
const res = await api.mcp.probe(row.id)
|
||||
toast(res.ok ? `连通,发现 ${res.tools.length} 个工具` : `失败:${res.error}`, res.ok ? 'ok' : 'error')
|
||||
await load(); await refresh()
|
||||
} finally {
|
||||
setProbing(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl p-4">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-semibold">MCP 接入</div>
|
||||
<div className="text-[11px] text-faint">
|
||||
接入后工具会出现在工具库,节点里用 <code className="mono">mcp:服务名/工具名</code> 引用
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button className="btn" onClick={async () => { await api.mcp.refresh(); await load(); await refresh() }}>
|
||||
<RefreshCw size={12} /> 重新加载
|
||||
</button>
|
||||
<button className="btn btn-primary" onClick={() => setEditing({ transport: 'stdio', args: [], env: {} })}>
|
||||
<Plus size={12} /> 添加
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!rows.length && <Empty icon={<Plug size={20} />} title="还没有接入 MCP server"
|
||||
hint="例如文件系统、数据库、浏览器自动化等现成的 MCP server。" />}
|
||||
<div className="space-y-2">
|
||||
{rows.map((row) => (
|
||||
<div key={row.id} className="rounded-lg border bg-panel p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full"
|
||||
style={{ background: row.status === 'ok' ? 'var(--ok)' : row.status === 'error' ? 'var(--err)' : 'var(--text-faint)' }} />
|
||||
<span className="text-[12.5px] font-medium">{row.name}</span>
|
||||
<span className="chip">{row.transport}</span>
|
||||
{!!row.tools_cache?.length && <span className="chip">{row.tools_cache.length} 个工具</span>}
|
||||
<div className="flex-1" />
|
||||
<button className="btn btn-sm" disabled={probing === row.id} onClick={() => probe(row)}>
|
||||
{probing === row.id ? <Spinner size={11} /> : <Plug size={11} />} 测试
|
||||
</button>
|
||||
<button className="btn btn-sm" onClick={() => setEditing(row)}>编辑</button>
|
||||
<button className="btn btn-sm btn-ghost" onClick={async () => {
|
||||
if (!confirm(`删除 ${row.name}?`)) return
|
||||
await api.mcp.remove(row.id); await load(); await refresh()
|
||||
}}>
|
||||
<Trash2 size={11} className="text-[var(--err)]" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mono mt-1 text-[10.5px] text-faint">
|
||||
{row.transport === 'stdio' ? `${row.command} ${(row.args ?? []).join(' ')}` : row.url}
|
||||
</div>
|
||||
{row.last_error && <div className="mt-1 text-[10.5px] text-[var(--err)]">{row.last_error}</div>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<McpEditor row={editing} onClose={() => setEditing(null)}
|
||||
onSaved={async () => { setEditing(null); await load(); await refresh(); toast('已保存', 'ok') }} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function McpEditor({ row, onClose, onSaved }: { row: any; onClose: () => void; onSaved: () => void }) {
|
||||
const toast = useToast()
|
||||
const [form, setForm] = useState<any>({
|
||||
name: row.name ?? '', transport: row.transport ?? 'stdio', command: row.command ?? '',
|
||||
args: row.args ?? [], env: row.env ?? {}, url: row.url ?? '', enabled: row.enabled ?? true,
|
||||
})
|
||||
const [argsText, setArgsText] = useState((row.args ?? []).join(' '))
|
||||
|
||||
const submit = async () => {
|
||||
try {
|
||||
const payload = { ...form, args: argsText.split(/\s+/).filter(Boolean) }
|
||||
if (row.id) await api.mcp.update(row.id, payload)
|
||||
else await api.mcp.create(payload)
|
||||
onSaved()
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '保存失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={row.id ? '编辑 MCP server' : '添加 MCP server'}
|
||||
footer={<>
|
||||
<button className="btn" onClick={onClose}>取消</button>
|
||||
<button className="btn btn-primary" onClick={submit} disabled={!form.name}>保存</button>
|
||||
</>}>
|
||||
<div className="mb-3">
|
||||
<label className="label">名称</label>
|
||||
<input className="field" value={form.name} placeholder="filesystem"
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">传输方式</label>
|
||||
<select className="field" value={form.transport}
|
||||
onChange={(e) => setForm({ ...form, transport: e.target.value })}>
|
||||
<option value="stdio">stdio(本地子进程)</option>
|
||||
<option value="http">HTTP(远程)</option>
|
||||
</select>
|
||||
</div>
|
||||
{form.transport === 'stdio' ? (
|
||||
<>
|
||||
<div className="mb-3">
|
||||
<label className="label">命令</label>
|
||||
<input className="field mono text-[11px]" value={form.command} placeholder="npx"
|
||||
onChange={(e) => setForm({ ...form, command: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="label">参数(空格分隔)</label>
|
||||
<input className="field mono text-[11px]" value={argsText}
|
||||
placeholder="-y @modelcontextprotocol/server-filesystem /tmp"
|
||||
onChange={(e) => setArgsText(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">环境变量</label>
|
||||
<JsonInput value={form.env} onChange={(v) => setForm({ ...form, env: v })} rows={3} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<label className="label">URL</label>
|
||||
<input className="field mono text-[11px]" value={form.url}
|
||||
placeholder="https://example.com/mcp"
|
||||
onChange={(e) => setForm({ ...form, url: e.target.value })} />
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
AlertTriangle, Ban, Check, ChevronRight, CircleDot, Hand, Play, Square, Wrench,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { api } from '../api/client'
|
||||
import { useStudio } from '../store/studio'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { NODE_DEFS } from '../canvas/nodeDefs'
|
||||
import { formatMs } from '../canvas/NodeCard'
|
||||
import { Empty, StatusDot, Tabs, useToast } from '../components/ui'
|
||||
import type { RunEvent } from '../types'
|
||||
|
||||
export function RunPanel() {
|
||||
const [tab, setTab] = useState('timeline')
|
||||
const run = useStudio((s) => s.run)
|
||||
const streaming = useStudio((s) => s.streaming)
|
||||
const approvals = useCatalog((s) => s.approvals)
|
||||
const pending = approvals.filter((a) => a.run_id === run?.id && a.status === 'pending')
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<RunLauncher />
|
||||
{pending.map((approval) => (
|
||||
<ApprovalCard key={approval.id} approval={approval} />
|
||||
))}
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ key: 'timeline', label: '时间线' },
|
||||
{ key: 'output', label: '成果' },
|
||||
{ key: 'raw', label: '事件' },
|
||||
]}
|
||||
active={tab}
|
||||
onChange={setTab}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{tab === 'timeline' && <Timeline />}
|
||||
{tab === 'output' && <OutputView />}
|
||||
{tab === 'raw' && <RawEvents />}
|
||||
</div>
|
||||
{run && (
|
||||
<div className="flex items-center justify-between gap-2 border-t px-3 py-1.5 text-[10.5px] text-faint">
|
||||
<span className="mono truncate" title={run.id}>#{run.id.slice(0, 8)}</span>
|
||||
<span className="flex items-center gap-2">
|
||||
{streaming && <span className="text-[var(--accent)]">● 实时</span>}
|
||||
{!!run.usage?.total_tokens && <span>{run.usage.total_tokens} tok</span>}
|
||||
{run.usage?.cost_usd ? <span>${Number(run.usage.cost_usd).toFixed(4)}</span> : null}
|
||||
{run.usage?.duration_ms ? <span>{formatMs(run.usage.duration_ms)}</span> : null}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function RunLauncher() {
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const run = useStudio((s) => s.run)
|
||||
const streaming = useStudio((s) => s.streaming)
|
||||
const issues = useStudio((s) => s.issues)
|
||||
const { startRun, stopRun } = useStudio()
|
||||
const toast = useToast()
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
// 入口节点声明了什么字段,这里就渲染什么表单
|
||||
const inputFields = useMemo(() => {
|
||||
const entry = nodes.find((n) => n.data.nodeType === 'input')
|
||||
return (entry?.data.config?.fields ?? []) as any[]
|
||||
}, [nodes])
|
||||
|
||||
const errors = issues.filter((i) => i.level === 'error')
|
||||
|
||||
const launch = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const payload: Record<string, any> = {}
|
||||
for (const field of inputFields) {
|
||||
if (!field.name) continue
|
||||
const raw = values[field.name] ?? field.default ?? ''
|
||||
// 看起来像 JSON 就按 JSON 传,让数组/对象类型的输入能用
|
||||
if (typeof raw === 'string' && /^\s*[[{]/.test(raw)) {
|
||||
try { payload[field.name] = JSON.parse(raw) } catch { payload[field.name] = raw }
|
||||
} else {
|
||||
payload[field.name] = raw
|
||||
}
|
||||
}
|
||||
await startRun(payload)
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '启动失败', 'error')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-b p-3">
|
||||
{inputFields.map((field) => (
|
||||
<div key={field.name} className="mb-2">
|
||||
<label className="label">
|
||||
{field.name}
|
||||
{field.required && <span className="ml-1 text-[var(--err)]">*</span>}
|
||||
{field.description && <span className="ml-1.5 font-normal text-faint">{field.description}</span>}
|
||||
</label>
|
||||
<textarea
|
||||
className="field"
|
||||
rows={2}
|
||||
value={values[field.name] ?? (typeof field.default === 'string' ? field.default : field.default ? JSON.stringify(field.default) : '')}
|
||||
placeholder={field.required ? '必填' : '可留空'}
|
||||
onChange={(e) => setValues({ ...values, [field.name]: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{!inputFields.length && (
|
||||
<div className="mb-2 text-[11px] text-faint">
|
||||
这张图没有输入节点,将直接运行
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!!errors.length && (
|
||||
<div className="mb-2 rounded border px-2 py-1.5 text-[10.5px] leading-snug"
|
||||
style={{ borderColor: 'var(--err)', color: 'var(--err)' }}>
|
||||
{errors.length} 个问题会阻止运行:{errors[0].message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{streaming || run?.status === 'running' ? (
|
||||
<button className="btn btn-danger flex-1 justify-center" onClick={stopRun}>
|
||||
<Square size={12} /> 停止
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="btn btn-primary flex-1 justify-center"
|
||||
onClick={launch}
|
||||
disabled={busy || !!errors.length || !nodes.length}
|
||||
>
|
||||
<Play size={12} /> 运行
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function ApprovalCard({ approval }: { approval: any }) {
|
||||
const toast = useToast()
|
||||
const refreshApprovals = useCatalog((s) => s.refreshApprovals)
|
||||
const attachRun = useStudio((s) => s.attachRun)
|
||||
const [note, setNote] = useState('')
|
||||
const [value, setValue] = useState(() =>
|
||||
approval.payload?.draft != null ? String(approval.payload.draft) : '',
|
||||
)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const payload = approval.payload ?? {}
|
||||
|
||||
const decide = async (approved: boolean) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api.approvals.decide(approval.id, {
|
||||
approved,
|
||||
note,
|
||||
...(approval.mode !== 'approve' ? { value } : {}),
|
||||
})
|
||||
await refreshApprovals()
|
||||
await attachRun(approval.run_id) // 恢复后重新接上事件流
|
||||
toast(approved ? '已放行,运行继续' : '已驳回', 'ok')
|
||||
} catch (e: any) {
|
||||
toast(e.message ?? '操作失败', 'error')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fade-up border-b p-3" style={{ background: 'color-mix(in srgb, var(--warn) 7%, transparent)' }}>
|
||||
<div className="mb-2 flex items-center gap-1.5 text-xs font-semibold" style={{ color: 'var(--warn)' }}>
|
||||
<Hand size={13} /> {approval.title || '需要你确认'}
|
||||
</div>
|
||||
|
||||
{payload.message && (
|
||||
<div className="mb-2 max-h-40 overflow-y-auto whitespace-pre-wrap rounded border bg-bg p-2 text-[11px] leading-relaxed">
|
||||
{payload.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{payload.tool && (
|
||||
<div className="mb-2 rounded border bg-bg p-2">
|
||||
<div className="mb-1 flex items-center gap-1.5 text-[11px]">
|
||||
<Wrench size={11} /> <code className="mono">{payload.tool}</code>
|
||||
</div>
|
||||
<pre className="mono max-h-32 overflow-auto text-[10px] leading-relaxed text-dim">
|
||||
{JSON.stringify(payload.args ?? {}, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{payload.code && (
|
||||
<pre className="mono mb-2 max-h-40 overflow-auto rounded border bg-bg p-2 text-[10px] leading-relaxed">
|
||||
{payload.code}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
{approval.mode !== 'approve' && (
|
||||
<textarea
|
||||
className="field mb-2"
|
||||
rows={4}
|
||||
value={value}
|
||||
placeholder={approval.mode === 'edit' ? '修改后的内容' : '你的输入'}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<input
|
||||
className="field mb-2"
|
||||
placeholder="备注(会传给后续节点)"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button className="btn btn-primary flex-1 justify-center" disabled={busy} onClick={() => decide(true)}>
|
||||
<Check size={12} /> {approval.mode === 'approve' ? '通过' : '提交'}
|
||||
</button>
|
||||
<button className="btn btn-danger flex-1 justify-center" disabled={busy} onClick={() => decide(false)}>
|
||||
<Ban size={12} /> 驳回
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
const HIDDEN_TYPES = new Set(['llm.token', 'llm.thinking'])
|
||||
|
||||
function Timeline() {
|
||||
const events = useStudio((s) => s.events)
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const select = useStudio((s) => s.select)
|
||||
const bottom = useRef<HTMLDivElement>(null)
|
||||
const [expanded, setExpanded] = useState<Record<number, boolean>>({})
|
||||
|
||||
useEffect(() => {
|
||||
bottom.current?.scrollIntoView({ behavior: 'smooth', block: 'end' })
|
||||
}, [events.length])
|
||||
|
||||
const visible = events.filter((e) => !HIDDEN_TYPES.has(e.type))
|
||||
if (!visible.length) {
|
||||
return <Empty icon={<CircleDot size={22} />} title="还没有运行" hint="填好输入点「运行」,这里会实时显示每一步。" />
|
||||
}
|
||||
|
||||
const labelOf = (id: string | null) =>
|
||||
nodes.find((n) => n.id === id)?.data.label ?? id ?? ''
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
{visible.map((event) => {
|
||||
const meta = EVENT_META[event.type] ?? { text: event.type, tone: 'dim' as const }
|
||||
const detail = describe(event)
|
||||
const open = expanded[event.seq]
|
||||
return (
|
||||
<div key={event.seq} className="fade-up group flex gap-2 px-1 py-1">
|
||||
<span
|
||||
className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full"
|
||||
style={{ background: TONE[meta.tone] }}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline gap-1.5">
|
||||
<span className="text-[11.5px]" style={{ color: TONE[meta.tone] }}>
|
||||
{meta.text}
|
||||
</span>
|
||||
{event.node_id && (
|
||||
<button
|
||||
className="truncate text-[11px] text-dim hover:text-fg hover:underline"
|
||||
onClick={() => select(event.node_id)}
|
||||
>
|
||||
{labelOf(event.node_id)}
|
||||
</button>
|
||||
)}
|
||||
{event.data?.duration_ms != null && (
|
||||
<span className="ml-auto shrink-0 text-[10px] text-faint">
|
||||
{formatMs(event.data.duration_ms)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{detail && (
|
||||
<div
|
||||
className={clsx(
|
||||
'mt-0.5 text-[10.5px] leading-snug text-faint',
|
||||
!open && 'line-clamp-2',
|
||||
)}
|
||||
>
|
||||
{detail}
|
||||
</div>
|
||||
)}
|
||||
{detail && detail.length > 90 && (
|
||||
<button
|
||||
className="mt-0.5 flex items-center gap-0.5 text-[10px] text-faint opacity-0 transition-opacity group-hover:opacity-100"
|
||||
onClick={() => setExpanded({ ...expanded, [event.seq]: !open })}
|
||||
>
|
||||
<ChevronRight size={9} className={open ? 'rotate-90' : ''} />
|
||||
{open ? '收起' : '展开'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div ref={bottom} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const TONE = {
|
||||
ok: 'var(--ok)', err: 'var(--err)', warn: 'var(--warn)',
|
||||
accent: 'var(--accent)', dim: 'var(--text-faint)',
|
||||
}
|
||||
|
||||
const EVENT_META: Record<string, { text: string; tone: keyof typeof TONE }> = {
|
||||
'run.started': { text: '开始运行', tone: 'accent' },
|
||||
'run.finished': { text: '运行完成', tone: 'ok' },
|
||||
'run.failed': { text: '运行失败', tone: 'err' },
|
||||
'run.cancelled': { text: '已取消', tone: 'warn' },
|
||||
'run.interrupted': { text: '等待人工介入', tone: 'warn' },
|
||||
'run.resumed': { text: '已恢复', tone: 'accent' },
|
||||
'node.started': { text: '▶', tone: 'accent' },
|
||||
'node.finished': { text: '✓', tone: 'ok' },
|
||||
'node.failed': { text: '✕', tone: 'err' },
|
||||
'node.skipped': { text: '跳过', tone: 'dim' },
|
||||
'edge.taken': { text: '分支', tone: 'warn' },
|
||||
'llm.start': { text: '调用模型', tone: 'dim' },
|
||||
'llm.end': { text: '模型返回', tone: 'dim' },
|
||||
'tool.start': { text: '调用工具', tone: 'dim' },
|
||||
'tool.end': { text: '工具完成', tone: 'ok' },
|
||||
'tool.error': { text: '工具失败', tone: 'err' },
|
||||
'sandbox.start': { text: '沙箱启动', tone: 'dim' },
|
||||
'sandbox.end': { text: '沙箱结束', tone: 'ok' },
|
||||
'agent.step.start': { text: 'Agent 接手', tone: 'accent' },
|
||||
'agent.step.end': { text: 'Agent 交付', tone: 'ok' },
|
||||
'human.requested': { text: '请求人工', tone: 'warn' },
|
||||
'human.resolved': { text: '人工已回复', tone: 'ok' },
|
||||
'log': { text: '日志', tone: 'dim' },
|
||||
}
|
||||
|
||||
function describe(event: RunEvent): string {
|
||||
const d = event.data ?? {}
|
||||
switch (event.type) {
|
||||
case 'edge.taken':
|
||||
return `走 ${d.branch}${d.reason ? ` · ${d.reason}` : ''}${d.iteration != null ? ` · 第 ${d.iteration + 1} 轮` : ''}`
|
||||
case 'tool.start':
|
||||
return `${d.tool}(${JSON.stringify(d.args ?? {}).slice(0, 120)})`
|
||||
case 'tool.end':
|
||||
case 'tool.error':
|
||||
return String(d.preview ?? '').slice(0, 300)
|
||||
case 'llm.end':
|
||||
return `${d.model ?? ''} · ${d.input_tokens ?? 0}+${d.output_tokens ?? 0} tok${d.cost_usd ? ` · $${Number(d.cost_usd).toFixed(4)}` : ''}`
|
||||
case 'sandbox.end':
|
||||
return `exit=${d.exit_code} · ${d.backend}${d.stdout ? `\n${String(d.stdout).slice(0, 300)}` : ''}`
|
||||
case 'agent.step.start':
|
||||
return `${d.agent}:${String(d.instruction ?? '').slice(0, 160)}`
|
||||
case 'agent.step.end':
|
||||
return `${d.agent} → ${String(d.preview ?? '').slice(0, 200)}`
|
||||
case 'node.failed':
|
||||
case 'run.failed':
|
||||
return String(d.error ?? '')
|
||||
case 'log':
|
||||
return String(d.message ?? '')
|
||||
case 'human.requested':
|
||||
return String(d.title ?? d.tool ?? '')
|
||||
case 'node.finished': {
|
||||
if (!d.preview) return ''
|
||||
const text = typeof d.preview === 'string' ? d.preview : JSON.stringify(d.preview)
|
||||
return text.slice(0, 300)
|
||||
}
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function OutputView() {
|
||||
const run = useStudio((s) => s.run)
|
||||
const events = useStudio((s) => s.events)
|
||||
|
||||
// run 对象是启动时拿到的快照,完成事件里才带最终成果
|
||||
const finished = [...events].reverse().find((e) => e.type === 'run.finished')
|
||||
const output = finished?.data?.output ?? run?.output
|
||||
const failed = [...events].reverse().find((e) => e.type === 'run.failed')
|
||||
|
||||
if (failed) {
|
||||
return (
|
||||
<div className="p-3">
|
||||
<div className="mb-2 flex items-center gap-1.5 text-xs font-semibold text-[var(--err)]">
|
||||
<AlertTriangle size={13} /> 运行失败
|
||||
</div>
|
||||
<pre className="mono whitespace-pre-wrap rounded border bg-bg p-2 text-[11px] leading-relaxed text-[var(--err)]">
|
||||
{failed.data?.error}
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!output || !Object.keys(output).length) {
|
||||
return <Empty title="还没有成果" hint="运行完成后,output 节点收集的结构化结果会显示在这里。" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3 p-3">
|
||||
{Object.entries(output).map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<div className="label">{key}</div>
|
||||
<div className="whitespace-pre-wrap break-words rounded border bg-bg p-2 text-[11.5px] leading-relaxed">
|
||||
{typeof value === 'string' ? value : JSON.stringify(value, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RawEvents() {
|
||||
const events = useStudio((s) => s.events)
|
||||
if (!events.length) return <Empty title="暂无事件" />
|
||||
return (
|
||||
<div className="p-2">
|
||||
{events.map((e) => (
|
||||
<div key={e.seq} className="mono border-b px-1 py-1 text-[10px] leading-relaxed last:border-0">
|
||||
<span className="text-faint">#{e.seq}</span>{' '}
|
||||
<span className="text-[var(--accent)]">{e.type}</span>{' '}
|
||||
{e.node_id && <span className="text-dim">{e.node_id}</span>}
|
||||
<div className="break-all text-faint">{JSON.stringify(e.data).slice(0, 500)}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { StatusDot, NODE_DEFS }
|
||||
@@ -0,0 +1,58 @@
|
||||
import { create } from 'zustand'
|
||||
import { api } from '../api/client'
|
||||
import type { Approval, Provider, Skill, ToolInfo, Workflow } from '../types'
|
||||
|
||||
/** 全局参照数据:属性面板的各种下拉都从这里取,只加载一次。 */
|
||||
interface CatalogState {
|
||||
providers: Provider[]
|
||||
tools: ToolInfo[]
|
||||
skills: Skill[]
|
||||
collections: { collection: string; documents: number; chunks: number }[]
|
||||
workflows: Workflow[]
|
||||
approvals: Approval[]
|
||||
loaded: boolean
|
||||
refresh: () => Promise<void>
|
||||
refreshApprovals: () => Promise<void>
|
||||
}
|
||||
|
||||
export const useCatalog = create<CatalogState>((set) => ({
|
||||
providers: [],
|
||||
tools: [],
|
||||
skills: [],
|
||||
collections: [],
|
||||
workflows: [],
|
||||
approvals: [],
|
||||
loaded: false,
|
||||
|
||||
refresh: async () => {
|
||||
// 单项失败不该让整个面板空掉,各自兜底
|
||||
const [providers, tools, skills, collections, workflows, approvals] = await Promise.all([
|
||||
api.providers.list().catch(() => []),
|
||||
api.tools.list().catch(() => []),
|
||||
api.skills.list().catch(() => []),
|
||||
api.kb.collections().catch(() => []),
|
||||
api.workflows.list().catch(() => []),
|
||||
api.approvals.list().catch(() => []),
|
||||
])
|
||||
set({ providers, tools, skills, collections, workflows, approvals, loaded: true })
|
||||
},
|
||||
|
||||
refreshApprovals: async () => {
|
||||
set({ approvals: await api.approvals.list().catch(() => []) })
|
||||
},
|
||||
}))
|
||||
|
||||
/** 把所有 provider 的模型拉平成下拉选项。 */
|
||||
export function modelOptions(providers: Provider[]): { value: string; label: string; group: string }[] {
|
||||
const out: { value: string; label: string; group: string }[] = []
|
||||
for (const p of providers) {
|
||||
if (!p.enabled) continue
|
||||
for (const m of p.models ?? []) {
|
||||
out.push({ value: m.id, label: m.label || m.id, group: p.name })
|
||||
}
|
||||
if (!(p.models ?? []).length && p.default_model) {
|
||||
out.push({ value: p.default_model, label: p.default_model, group: p.name })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import { create } from 'zustand'
|
||||
import {
|
||||
addEdge, applyEdgeChanges, applyNodeChanges,
|
||||
type Connection, type Edge, type EdgeChange, type Node, type NodeChange,
|
||||
} from '@xyflow/react'
|
||||
import { api, streamRun } from '../api/client'
|
||||
import { NODE_DEFS } from '../canvas/nodeDefs'
|
||||
import type {
|
||||
GraphEdge, GraphSpec, NodeRuntime, NodeType, Run, RunEvent, ValidationIssue, Workflow,
|
||||
} from '../types'
|
||||
|
||||
export type FlowNode = Node<{ nodeType: NodeType; label: string; config: Record<string, any> }>
|
||||
|
||||
let idSeq = 0
|
||||
const nextId = (type: string) => `${type}_${Date.now().toString(36).slice(-4)}${(idSeq++ % 100).toString(36)}`
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GraphSpec ↔ React Flow 互转
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
export function toFlow(graph: GraphSpec): { nodes: FlowNode[]; edges: Edge[] } {
|
||||
return {
|
||||
nodes: (graph.nodes ?? []).map((n) => ({
|
||||
id: n.id,
|
||||
type: 'card',
|
||||
position: n.position ?? { x: 0, y: 0 },
|
||||
data: {
|
||||
nodeType: n.type,
|
||||
label: n.data?.label ?? NODE_DEFS[n.type]?.label ?? n.type,
|
||||
config: n.data?.config ?? {},
|
||||
},
|
||||
})),
|
||||
edges: (graph.edges ?? []).map((e, i) => ({
|
||||
id: e.id || `e${i}_${e.source}_${e.sourceHandle ?? ''}_${e.target}`,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
sourceHandle: e.sourceHandle ?? null,
|
||||
targetHandle: e.targetHandle ?? null,
|
||||
label: e.label || undefined,
|
||||
type: 'smoothstep',
|
||||
animated: false,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export function toGraph(nodes: FlowNode[], edges: Edge[]): GraphSpec {
|
||||
return {
|
||||
nodes: nodes.map((n) => ({
|
||||
id: n.id,
|
||||
type: n.data.nodeType,
|
||||
position: { x: Math.round(n.position.x), y: Math.round(n.position.y) },
|
||||
data: { label: n.data.label, config: n.data.config },
|
||||
})),
|
||||
edges: edges.map<GraphEdge>((e) => ({
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
sourceHandle: e.sourceHandle ?? null,
|
||||
label: typeof e.label === 'string' ? e.label : '',
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
interface StudioState {
|
||||
workflow: Workflow | null
|
||||
nodes: FlowNode[]
|
||||
edges: Edge[]
|
||||
selectedId: string | null
|
||||
dirty: boolean
|
||||
issues: ValidationIssue[]
|
||||
|
||||
run: Run | null
|
||||
events: RunEvent[]
|
||||
runtime: Record<string, NodeRuntime>
|
||||
activeEdges: string[]
|
||||
streaming: boolean
|
||||
unsubscribe: (() => void) | null
|
||||
|
||||
// actions
|
||||
load: (workflow: Workflow) => void
|
||||
setGraph: (graph: GraphSpec) => void
|
||||
onNodesChange: (changes: NodeChange[]) => void
|
||||
onEdgesChange: (changes: EdgeChange[]) => void
|
||||
onConnect: (conn: Connection) => void
|
||||
addNode: (type: NodeType, position: { x: number; y: number }) => void
|
||||
updateNode: (id: string, patch: { label?: string; config?: Record<string, any> }) => void
|
||||
removeNode: (id: string) => void
|
||||
duplicateNode: (id: string) => void
|
||||
select: (id: string | null) => void
|
||||
save: () => Promise<void>
|
||||
validate: () => Promise<void>
|
||||
|
||||
startRun: (input: Record<string, any>) => Promise<Run | null>
|
||||
attachRun: (runId: string) => Promise<void>
|
||||
stopRun: () => Promise<void>
|
||||
clearRun: () => void
|
||||
applyEvent: (event: RunEvent) => void
|
||||
}
|
||||
|
||||
const EMPTY_RUNTIME: NodeRuntime = { status: 'idle' }
|
||||
|
||||
export const useStudio = create<StudioState>((set, get) => ({
|
||||
workflow: null,
|
||||
nodes: [],
|
||||
edges: [],
|
||||
selectedId: null,
|
||||
dirty: false,
|
||||
issues: [],
|
||||
run: null,
|
||||
events: [],
|
||||
runtime: {},
|
||||
activeEdges: [],
|
||||
streaming: false,
|
||||
unsubscribe: null,
|
||||
|
||||
load: (workflow) => {
|
||||
const { nodes, edges } = toFlow(workflow.graph)
|
||||
get().unsubscribe?.()
|
||||
set({
|
||||
workflow, nodes, edges, selectedId: null, dirty: false, issues: [],
|
||||
run: null, events: [], runtime: {}, activeEdges: [], streaming: false, unsubscribe: null,
|
||||
})
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
setGraph: (graph) => {
|
||||
const { nodes, edges } = toFlow(graph)
|
||||
set({ nodes, edges, dirty: true })
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
onNodesChange: (changes) => {
|
||||
set({ nodes: applyNodeChanges(changes, get().nodes) as FlowNode[] })
|
||||
// 只有拖动结束和增删才算改动,实时拖动不标脏,否则自动保存会疯狂触发
|
||||
if (changes.some((c) => (c.type === 'position' && !c.dragging) || c.type === 'remove')) {
|
||||
set({ dirty: true })
|
||||
}
|
||||
},
|
||||
|
||||
onEdgesChange: (changes) => {
|
||||
set({ edges: applyEdgeChanges(changes, get().edges), dirty: true })
|
||||
if (changes.some((c) => c.type === 'remove')) void get().validate()
|
||||
},
|
||||
|
||||
onConnect: (conn) => {
|
||||
set({
|
||||
edges: addEdge({ ...conn, type: 'smoothstep' }, get().edges),
|
||||
dirty: true,
|
||||
})
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
addNode: (type, position) => {
|
||||
const def = NODE_DEFS[type]
|
||||
const node: FlowNode = {
|
||||
id: nextId(type),
|
||||
type: 'card',
|
||||
position,
|
||||
data: { nodeType: type, label: def.label, config: structuredClone(def.defaults ?? {}) },
|
||||
}
|
||||
set({ nodes: [...get().nodes, node], selectedId: node.id, dirty: true })
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
updateNode: (id, patch) => {
|
||||
set({
|
||||
nodes: get().nodes.map((n) =>
|
||||
n.id === id
|
||||
? {
|
||||
...n,
|
||||
data: {
|
||||
...n.data,
|
||||
...(patch.label !== undefined ? { label: patch.label } : {}),
|
||||
...(patch.config !== undefined ? { config: patch.config } : {}),
|
||||
},
|
||||
}
|
||||
: n,
|
||||
),
|
||||
dirty: true,
|
||||
})
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
removeNode: (id) => {
|
||||
set({
|
||||
nodes: get().nodes.filter((n) => n.id !== id),
|
||||
edges: get().edges.filter((e) => e.source !== id && e.target !== id),
|
||||
selectedId: get().selectedId === id ? null : get().selectedId,
|
||||
dirty: true,
|
||||
})
|
||||
void get().validate()
|
||||
},
|
||||
|
||||
duplicateNode: (id) => {
|
||||
const source = get().nodes.find((n) => n.id === id)
|
||||
if (!source) return
|
||||
const copy: FlowNode = {
|
||||
...source,
|
||||
id: nextId(source.data.nodeType),
|
||||
position: { x: source.position.x + 40, y: source.position.y + 40 },
|
||||
data: { ...source.data, config: structuredClone(source.data.config) },
|
||||
selected: false,
|
||||
}
|
||||
set({ nodes: [...get().nodes, copy], selectedId: copy.id, dirty: true })
|
||||
},
|
||||
|
||||
select: (id) => set({ selectedId: id }),
|
||||
|
||||
save: async () => {
|
||||
const { workflow, nodes, edges } = get()
|
||||
if (!workflow) return
|
||||
const graph = toGraph(nodes, edges)
|
||||
const updated = await api.workflows.update(workflow.id, { graph })
|
||||
set({ workflow: updated, dirty: false })
|
||||
},
|
||||
|
||||
validate: async () => {
|
||||
const { nodes, edges } = get()
|
||||
if (!nodes.length) {
|
||||
set({ issues: [] })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const result = await api.workflows.validate(toGraph(nodes, edges))
|
||||
set({ issues: result.issues ?? [] })
|
||||
} catch {
|
||||
/* 校验失败不影响编辑 */
|
||||
}
|
||||
},
|
||||
|
||||
// ---- 运行 ----
|
||||
|
||||
startRun: async (input) => {
|
||||
const { workflow, nodes, edges } = get()
|
||||
get().unsubscribe?.()
|
||||
set({ events: [], runtime: {}, activeEdges: [], run: null })
|
||||
try {
|
||||
const run = await api.runs.start({
|
||||
workflow_id: workflow?.id,
|
||||
graph: toGraph(nodes, edges),
|
||||
input,
|
||||
})
|
||||
set({ run, streaming: true })
|
||||
await get().attachRun(run.id)
|
||||
return run
|
||||
} catch (e) {
|
||||
set({ streaming: false })
|
||||
throw e
|
||||
}
|
||||
},
|
||||
|
||||
attachRun: async (runId) => {
|
||||
get().unsubscribe?.()
|
||||
const stop = streamRun(
|
||||
runId,
|
||||
(event) => get().applyEvent(event),
|
||||
() => set({ streaming: false }),
|
||||
)
|
||||
set({ unsubscribe: stop, streaming: true })
|
||||
},
|
||||
|
||||
stopRun: async () => {
|
||||
const run = get().run
|
||||
if (!run) return
|
||||
await api.runs.cancel(run.id).catch(() => undefined)
|
||||
set({ streaming: false })
|
||||
},
|
||||
|
||||
clearRun: () => {
|
||||
get().unsubscribe?.()
|
||||
set({ run: null, events: [], runtime: {}, activeEdges: [], streaming: false, unsubscribe: null })
|
||||
},
|
||||
|
||||
/**
|
||||
* 把一条事件折算成画布上的可见变化。
|
||||
* 这是"实时可视化"的全部秘密:事件流 → 节点状态 → 高亮/动效。
|
||||
*/
|
||||
applyEvent: (event) => {
|
||||
const state = get()
|
||||
const events = [...state.events, event]
|
||||
const runtime = { ...state.runtime }
|
||||
const nodeId = event.node_id
|
||||
const patch = (changes: Partial<NodeRuntime>) => {
|
||||
if (!nodeId) return
|
||||
runtime[nodeId] = { ...(runtime[nodeId] ?? EMPTY_RUNTIME), ...changes }
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'node.started':
|
||||
patch({ status: 'running', tokens: '', thinking: '', error: undefined, toolCalls: [] })
|
||||
break
|
||||
case 'node.finished':
|
||||
patch({ status: 'done', durationMs: event.data.duration_ms, preview: event.data.preview })
|
||||
break
|
||||
case 'node.failed':
|
||||
patch({ status: 'failed', error: event.data.error, durationMs: event.data.duration_ms })
|
||||
break
|
||||
case 'node.skipped':
|
||||
patch({ status: 'skipped' })
|
||||
break
|
||||
case 'llm.token':
|
||||
patch({ tokens: (runtime[nodeId!]?.tokens ?? '') + (event.data.delta ?? '') })
|
||||
break
|
||||
case 'llm.thinking':
|
||||
patch({ thinking: (runtime[nodeId!]?.thinking ?? '') + (event.data.delta ?? '') })
|
||||
break
|
||||
case 'tool.start':
|
||||
patch({
|
||||
toolCalls: [...(runtime[nodeId!]?.toolCalls ?? []), { tool: event.data.tool, args: event.data.args }],
|
||||
})
|
||||
break
|
||||
case 'tool.end':
|
||||
case 'tool.error': {
|
||||
const calls = [...(runtime[nodeId!]?.toolCalls ?? [])]
|
||||
const idx = calls.map((c) => c.tool).lastIndexOf(event.data.tool)
|
||||
if (idx >= 0) {
|
||||
calls[idx] = { ...calls[idx], result: event.data.preview, ok: event.type === 'tool.end' }
|
||||
}
|
||||
patch({ toolCalls: calls })
|
||||
break
|
||||
}
|
||||
case 'human.requested':
|
||||
patch({ status: 'waiting' })
|
||||
break
|
||||
case 'run.interrupted':
|
||||
if (nodeId) patch({ status: 'waiting' })
|
||||
break
|
||||
case 'run.finished':
|
||||
case 'run.failed':
|
||||
case 'run.cancelled':
|
||||
set({ streaming: false })
|
||||
break
|
||||
}
|
||||
|
||||
// 高亮当前正在流动的边:从已完成节点指向正在运行的节点
|
||||
const running = Object.entries(runtime)
|
||||
.filter(([, r]) => r.status === 'running' || r.status === 'waiting')
|
||||
.map(([id]) => id)
|
||||
const activeEdges = state.edges
|
||||
.filter((e) => running.includes(e.target) && runtime[e.source]?.status === 'done')
|
||||
.map((e) => e.id)
|
||||
|
||||
set({ events, runtime, activeEdges })
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,151 @@
|
||||
export type NodeType =
|
||||
| 'input' | 'output' | 'llm' | 'agent' | 'supervisor' | 'tool' | 'code'
|
||||
| 'branch' | 'loop' | 'subgraph' | 'memory' | 'retrieve' | 'transform'
|
||||
| 'human' | 'validate'
|
||||
|
||||
export interface GraphNode {
|
||||
id: string
|
||||
type: NodeType
|
||||
position: { x: number; y: number }
|
||||
data: { label?: string; description?: string; config: Record<string, any> }
|
||||
}
|
||||
|
||||
export interface GraphEdge {
|
||||
id?: string
|
||||
source: string
|
||||
target: string
|
||||
sourceHandle?: string | null
|
||||
targetHandle?: string | null
|
||||
label?: string
|
||||
}
|
||||
|
||||
export interface GraphSpec {
|
||||
nodes: GraphNode[]
|
||||
edges: GraphEdge[]
|
||||
viewport?: Record<string, any>
|
||||
defaults?: Record<string, any>
|
||||
}
|
||||
|
||||
export interface Workflow {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
graph: GraphSpec
|
||||
tags: string[]
|
||||
version: number
|
||||
is_template: boolean
|
||||
run_count?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export type RunStatus =
|
||||
| 'queued' | 'running' | 'interrupted' | 'succeeded' | 'failed' | 'cancelled'
|
||||
|
||||
export interface Run {
|
||||
id: string
|
||||
workflow_id: string | null
|
||||
workflow_name: string
|
||||
status: RunStatus
|
||||
input: Record<string, any>
|
||||
output: Record<string, any>
|
||||
error: string | null
|
||||
usage: Record<string, any>
|
||||
created_at?: string
|
||||
started_at?: string
|
||||
finished_at?: string
|
||||
}
|
||||
|
||||
export interface RunEvent {
|
||||
seq: number
|
||||
type: string
|
||||
node_id: string | null
|
||||
ts: number
|
||||
data: Record<string, any>
|
||||
replay?: boolean
|
||||
}
|
||||
|
||||
export interface Approval {
|
||||
id: string
|
||||
run_id: string
|
||||
node_id: string
|
||||
mode: 'approve' | 'input' | 'edit'
|
||||
title: string
|
||||
payload: Record<string, any>
|
||||
status: string
|
||||
response: Record<string, any>
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface Provider {
|
||||
id: string
|
||||
name: string
|
||||
kind: string
|
||||
base_url: string | null
|
||||
default_model: string | null
|
||||
models: { id: string; label?: string; context?: number; pricing?: any }[]
|
||||
enabled: boolean
|
||||
extra: Record<string, any>
|
||||
api_key_masked: string
|
||||
has_key: boolean
|
||||
}
|
||||
|
||||
export interface ToolInfo {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
category: string
|
||||
source: 'builtin' | 'custom' | 'mcp'
|
||||
dangerous: boolean
|
||||
schema: Record<string, any>
|
||||
}
|
||||
|
||||
export interface Skill {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
instructions: string
|
||||
examples: { input?: string; output?: string }[]
|
||||
suggested_tools: string[]
|
||||
tags: string[]
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export interface MemoryItem {
|
||||
id: string
|
||||
scope: string
|
||||
kind: string
|
||||
content: string
|
||||
importance: number
|
||||
use_count: number
|
||||
meta: Record<string, any>
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface KbDocument {
|
||||
id: string
|
||||
collection: string
|
||||
title: string
|
||||
source: string
|
||||
mime: string
|
||||
chunk_count: number
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface ValidationIssue {
|
||||
level: 'error' | 'warning'
|
||||
node_id?: string | null
|
||||
edge_id?: string | null
|
||||
message: string
|
||||
}
|
||||
|
||||
/** 单个节点在一次运行中的实时状态,驱动画布上的高亮。 */
|
||||
export interface NodeRuntime {
|
||||
status: 'idle' | 'running' | 'done' | 'failed' | 'waiting' | 'skipped'
|
||||
durationMs?: number
|
||||
preview?: any
|
||||
error?: string
|
||||
tokens?: string
|
||||
thinking?: string
|
||||
toolCalls?: { tool: string; args?: any; result?: string; ok?: boolean }[]
|
||||
}
|
||||
Reference in New Issue
Block a user