diff --git a/frontend/src/api/appCopilot.ts b/frontend/src/api/appCopilot.ts new file mode 100644 index 00000000..096ec778 --- /dev/null +++ b/frontend/src/api/appCopilot.ts @@ -0,0 +1,91 @@ +/** + * 应用润色的助手(POST /api/copilot/app-stream,SSE):应用编辑器右侧的助手面板用它。 + * + * 和 streamCopilot(画布生成)同一种帧:一帧一行 `data: `,空行分隔。操作有三类(§3.11): + * - 应用操作:app_add / app_update / app_remove / app_move / app_page / app_set,形状同服务端 app/apps/ops.py, + * 编辑器按到达顺序落到草稿上(pages/apps/edit/appOps.ts 的 applyAppOp); + * - look(查看了哪些工作流版本、能力)、ask(问回来一句,这一轮到此结束)、thinking、heartbeat、check、reply、error; + * - final:{spec, issues, explanation},服务端落地后的整份 spec(以它为准,替换前面边收边改的草稿)。 + * + * 系统先代为查看固定的版本(look 的 by=system),模型可以再查看;岗位绑定只能由人做,助手只留空并提示。 + * 请求函数从 ./http 导入,不要从 ./client 导入(循环导入,见 http.ts 开头)。 + */ +import type { AppBindings, AppSpec } from '../typesApp' +import { ApiError, BASE, NETWORK_MESSAGE, actorHeader, codeOf, describeDetail, isGatewayFailure, parseBody, report } from './http' + +/** 请求体同服务端 api/copilot.AppStreamIn */ +export interface AppCopilotRequest { + app_id: string + instruction: string + /** 编辑器里此刻的草稿(可能还没保存):助手在它上面改 */ + spec: AppSpec + /** 草稿里的岗位绑定(不进 spec):服务端的应用检查按它判断岗位绑没绑 */ + bindings?: AppBindings + /** 应用编辑时的助手对话(conversations.app_id 归属这个应用),带上它这一轮才接得上前面聊过的 */ + conversation_id?: string | null + model?: string | null +} + +/** 返回取消函数。开流之前就被拒(4xx/5xx)时 onEnd 带服务端那句话、状态码和机读码 */ +export function streamAppCopilot( + body: AppCopilotRequest, + onOp: (op: any) => void, + onEnd: (error?: string, info?: { status?: number; code?: string }) => void, +): () => void { + const controller = new AbortController() + const path = '/copilot/app-stream' + void (async () => { + try { + const res = await fetch(`${BASE}${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream', ...actorHeader() }, + body: JSON.stringify(body), + signal: controller.signal, + }) + if (!res.ok || !res.body) { + const text = await res.text().catch(() => '') + let parsed: any + let isJson = false + try { parsed = JSON.parse(text); isJson = true } catch { /* 响应体不是 JSON */ } + if (isGatewayFailure(res.status, text, isJson)) { + report(false, new ApiError(res.status, NETWORK_MESSAGE, { kind: 'network' })) + onEnd(NETWORK_MESSAGE) + return + } + report(true) + onEnd(isJson ? describeDetail(parsed?.detail ?? parsed, path) + : res.status >= 500 ? `服务端错误(${res.status}),详情请查看服务日志` + : `请求失败(HTTP ${res.status})`, { status: res.status, code: isJson ? codeOf(parsed) : undefined }) + return + } + report(true) + const reader = res.body.getReader() + const decoder = new TextDecoder() + let buffer = '' + for (;;) { + const { done, value } = await reader.read() + if (done) break + buffer += decoder.decode(value, { stream: true }) + let idx: number + while ((idx = buffer.indexOf('\n\n')) >= 0) { + const frame = buffer.slice(0, idx) + buffer = buffer.slice(idx + 2) + if (!frame.startsWith('data: ')) continue + try { + onOp(parseBody(frame.slice(6))) + } catch { /* 半截帧,忽略 */ } + } + } + onEnd() + } catch (e: any) { + if (e?.name === 'AbortError') { onEnd(); return } + if (e instanceof TypeError) { + report(false, new ApiError(0, NETWORK_MESSAGE, { kind: 'network', raw: String(e) })) + onEnd(NETWORK_MESSAGE) + return + } + onEnd(e?.message ?? '连接中断,请重试') + } + })() + return () => controller.abort() +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 3e40b162..1db565fd 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -232,6 +232,10 @@ export const api = { /** 某个版本的完整快照(含 graph)。正式运行的输入字段要从已发布版本取,不能取画布 */ version: (id: string, v: number) => get(`/workflows/${id}/versions/${v}`), restore: (id: string, v: number) => post(`/workflows/${id}/versions/${v}/restore`), + /** 退役一个已发布的版本(A1):当前发布版 409;返回受影响的应用。只有管理员(关登录时所有人) */ + retire: (id: string, v: number, note?: string) => + post<{ retired: boolean; affected_apps: { app_id: string; name: string; app_version: number }[] }>( + `/workflows/${id}/versions/${v}/retire`, { note: note ?? null }), publish: (id: string, level: 'published' | 'governed', version?: number) => post<{ ok: boolean; level?: string; version?: number; issues: any[] }>( `/workflows/${id}/publish`, { level, version }), @@ -513,6 +517,8 @@ export const api = { list: (params?: { workflow_id?: string; status?: RunStatus | RunStatus[] | string; run_class?: 'formal' | 'exploratory' q?: string; limit?: number; before?: string + /** 按运行来源筛(X3);none 是来源未记录的老运行 */ + origin_kind?: string }) => get(`/runs${qs(params)}`), get: (id: string) => get(`/runs/${id}`), /** 这次运行实际跑的那张图(运行时的快照),不是工作流现在的样子 */ @@ -522,6 +528,8 @@ export const api = { workflow_id?: string; graph?: GraphSpec; input?: Record memory_scope?: string; collection?: string run_class?: 'formal' | 'exploratory'; version?: number + /** 运行来源(X3):客户端只能声明 chat、canvas、launcher、api(不传按 api 记),其余由服务端写 */ + origin?: 'chat' | 'canvas' | 'launcher' | 'api' }) => post('/runs', body), artifacts: (id: string) => get(`/runs/${id}/artifacts`), /** 从失败的节点接着跑。graph 只能带改过配置的同一张图,结构必须一致 */ @@ -813,8 +821,9 @@ export const api = { }>('/copilot/generate', body), explain: (graph: GraphSpec) => post<{ explanation: string }>('/copilot/explain', { graph }), layout: (graph: GraphSpec) => post('/copilot/layout', { graph }), - fromRun: (runId: string, name?: string) => - post('/copilot/from-run', { run_id: runId, name }), + /** from:问数据回答上点「做成应用」时带上这次运行出自哪段对话的哪一轮,记进新工作流的来源 */ + fromRun: (runId: string, name?: string, from?: { conversation_id?: string | null; turn_id?: string | null }) => + post('/copilot/from-run', { run_id: runId, name, ...(from ?? {}) }), getModel: () => get('/copilot/model'), setModel: (body: { provider?: string | null; model?: string | null }) => put('/copilot/model', body), diff --git a/frontend/src/canvas/Inspector.tsx b/frontend/src/canvas/Inspector.tsx index ca9ace96..aed3b0d4 100644 --- a/frontend/src/canvas/Inspector.tsx +++ b/frontend/src/canvas/Inspector.tsx @@ -12,7 +12,7 @@ import { datasourceTools, modelOptions, providerOfModel, useCatalog, useDatasour import { api } from '../api/client' import { IconButton, JsonInput, Modal, isComposing, useRadioGroup } from '../components/ui' import { formatShortcut } from '../lib/keys' -import { JUDGE_FIELD_LABEL, JUDGE_ON_UNSUPPORTED_HINT, JUDGE_ON_UNSUPPORTED_LABEL, JUDGE_SETTING_TEXT, MERGE_TEXT, CATALOG_UI_TEXT, NODE_TYPE_LABEL, PROVIDER_REF_TEXT, SUBGRAPH_UPGRADE_HELP, judgeByModelText, upgradeNewerText } from '../lib/terms' +import { INPUT_FIELD_TEXT, JUDGE_FIELD_LABEL, JUDGE_ON_UNSUPPORTED_HINT, JUDGE_ON_UNSUPPORTED_LABEL, JUDGE_SETTING_TEXT, MERGE_TEXT, CATALOG_UI_TEXT, NODE_TYPE_LABEL, PROVIDER_REF_TEXT, SUBGRAPH_UPGRADE_HELP, judgeByModelText, upgradeNewerText } from '../lib/terms' import { TemplateText } from './TemplateText' import { MERGE_ALIAS, isQueryNode, mergeAlias } from './mergeInputs' import type { NodeType, Provider, ValidationIssue, WorkflowVersion } from '../types' @@ -1360,6 +1360,7 @@ function IoFieldList({ nodeId, value, issues, onChange }: { onChange={(e) => update(i, { default: e.target.value })} /> + update(i, patch)} /> )} {own.map((x, k) => )} @@ -1374,6 +1375,52 @@ function IoFieldList({ nodeId, value, issues, onChange }: { ) } +/** + * 入口字段的类型、格式、可选值(X2):服务端按它们把入口字段转成发起表单(agentlab.form/1),正式运行、画布试运行、 + * 应用入口的表单都照它画。没写类型的按文本处理,老图照常运行;写回时空的键删掉,不在配置里留空值 + */ +function InputFieldType({ uid, field, onChange }: { + uid: string; field: Record; onChange: (patch: Record) => void +}) { + const type = typeof field.type === 'string' ? field.type : 'string' + const options: string[] = Array.isArray(field.enum) ? field.enum.map(String) : [] + const [enumText, setEnumText] = useState(options.join('\n')) + useEffect(() => { setEnumText(options.join('\n')) }, [options.join('\n')]) // eslint-disable-line react-hooks/exhaustive-deps + return ( +
+
+ + + + {type === 'string' && ( + + + + )} +
+ {type !== 'boolean' && ( + +