diff --git a/frontend-v2/README.md b/frontend-v2/README.md index c78f0327..a741c756 100644 --- a/frontend-v2/README.md +++ b/frontend-v2/README.md @@ -103,13 +103,13 @@ e2e/ Playwright 端到端测试 运行由 v2-server 执行(见 `v2-server/README.md` 的"工作流执行"一节),客户端和工作流定义一样由 `v2-server/workflows.openapi.json` 生成。`server-runs.ts` 把创建、启动、修改启动输入、取消、删除、再跑一次、续跑预览和从失败处继续接到生成的客户端上(续跑预览挂在运行的查询键下面,运行每次失效时一起重新读取,不缓存),拒绝同样转成 `ContractError`;运行详情、冻结的图和项目下的运行列表由 TanStack Query 读取。运行没结束时,运行页照 desktop 订阅它的失效事件流(`GET …/workflow-runs/{rid}/events`,`run-events.ts`):每条 `workflow_run_invalidated` 都让运行详情和项目运行列表重新读取,事件本身不带状态,页面只信 HTTP 读到的持久状态。轮询是兜底(`runRefreshMs`):事件流连着时每 4 秒(desktop 的兜底间隔),没连上或断开时每 1 秒;运行结束后关闭事件流。侧边栏的项目运行列表照旧在有未结束的运行时每 1 秒读一次。刷新页面后运行还在,执行也不依赖页面开着。 -`server-run-adapter.ts` 把服务端的节点运行按 desktop 读取后端运行时的规则投影成节点状态:节点状态、开始结束时间、输入输出、失败原因和失败详情(`payload.error_detail`)照搬。运行详情的 `variables`(根变量池)和 `failedAttempts`(被替换的失败尝试)也照 desktop 的运行适配器读:开始节点显示这次运行的初始输入,输入变量显示运行变量池里的值(声明了但没赋值的显示为空;运行开始前还没有变量池,先保留快照里的值),所以节点详情的“输入变量”是这次运行实际用的值;之前失败的尝试按节点归到“之前失败的尝试”,从旧到新,带着各自的会话和失败原因,根作用域、Iteration 轮和 Loop 轮内的尝试各归各轮(v2 对非交互 Agent 一律自动重试,是否重试由 v2-server 决定,见其 README 的「Agent 自动重试」);“已自动重试”“已安排自动重试”只按服务端持久化的 `retry_chain` 标,不从配置推导。“已手动续跑”照 desktop 的 `markReplacements`,对根作用域的节点和 Iteration 成员(每一轮按同一 `(节点, 迭代轮)` 的当前行比较,不拿别的轮的行来标);Loop 成员在续跑开出的新轮里尝试号从 1 重新数,旧轮没有可比的当前行,所以不标:自动重试总会把被替换的尝试记进当前行的 `retry_chain`,所以比这条链(没有链时比当前行)更早的最新一次尝试是被“从失败处继续”(见上文)替换的;知道尝试号时要求两者相邻,中间隔着被清掉的行就不标。desktop 还要求当前行自己记下尝试号,v2 对刚续跑、还没记下号的新行也标,因为 v2 里只有续跑会软删根作用域的失败行而不留链接。等待重试的尝试显示倒计时;运行已结束时,留下的等待行显示为已取消。节点会话按节点尝试(`nodeRunId`,适配器从节点行带上)读:尝试绑定了会话后,`node-session.ts` 订阅 `GET …/workflow-runs/{rid}/nodes/{nodeRunId}/events`,帧格式和对话页的事件流相同,用对话页的 `applySessionEvent` / `conversationOf` 归并,所以能看到 Agent 的思考、工具调用和回答,运行中也实时更新。执行桥在一轮结束后就结束普通节点的会话,所以不显示对话页“会话已结束”的标记。会话只有启动运行的人能读(公共执行服务按用户隔离会话),其他成员读到 404,浏览器只看到事件流一开始就被永久关闭:这时节点会话说明只有启动这次运行的人能看实时会话,不再一直显示“正在等待”;还没有收到任何事件时也一样,节点会话退回两条消息:发给 Agent 的任务(服务端记下的渲染后任务 `payload.task`,没有时用节点的输入)和 Agent 的回答。成功的 Agent 还带着 v2 自己记下的三项:实际使用的执行器(`payload.executor`,Agent 名和插件版本)、模型(`payload.model`;新运行里配置的模型找不到或没配时节点以 `workflow_model_not_found` 失败、不启动会话,所以 `fallback` 总为假,只有旧运行可能为真)和没有应用的设置(`payload.unapplied`)。节点详情在配置的"Agent 模型"下面显示"实际执行";旧运行退回过默认模型的,仍说明原因。 +`server-run-adapter.ts` 把服务端的节点运行按 desktop 读取后端运行时的规则投影成节点状态:节点状态、开始结束时间、输入输出、失败原因和失败详情(`payload.error_detail`)照搬。运行详情的 `variables`(根变量池)和 `failedAttempts`(被替换的失败尝试)也照 desktop 的运行适配器读:开始节点显示这次运行的初始输入,输入变量显示运行变量池里的值(声明了但没赋值的显示为空;运行开始前还没有变量池,先保留快照里的值),所以节点详情的“输入变量”是这次运行实际用的值;之前失败的尝试按节点归到“之前失败的尝试”,从旧到新,带着各自的会话和失败原因,根作用域、Iteration 轮和 Loop 轮内的尝试各归各轮(v2 对非交互 Agent 一律自动重试,是否重试由 v2-server 决定,见其 README 的「Agent 自动重试」);“已自动重试”“已安排自动重试”只按服务端持久化的 `retry_chain` 标,不从配置推导。“已手动续跑”照 desktop 的 `markReplacements`,对根作用域的节点和 Iteration 成员(每一轮按同一 `(节点, 迭代轮)` 的当前行比较,不拿别的轮的行来标);Loop 成员在续跑开出的新轮里尝试号从 1 重新数,旧轮没有可比的当前行,所以不标:自动重试总会把被替换的尝试记进当前行的 `retry_chain`,所以比这条链(没有链时比当前行)更早的最新一次尝试是被“从失败处继续”(见上文)替换的;知道尝试号时要求两者相邻,中间隔着被清掉的行就不标。desktop 还要求当前行自己记下尝试号,v2 对刚续跑、还没记下号的新行也标,因为 v2 里只有续跑会软删根作用域的失败行而不留链接。等待重试的尝试显示倒计时;运行已结束时,留下的等待行显示为已取消。运行列表行与运行头部在服务端返回了发起人姓名时展示“由 <发起人> 发起”;节点会话按节点尝试(`nodeRunId`,适配器从节点行带上)读:尝试绑定了会话后,`node-session.ts` 订阅 `GET …/workflow-runs/{rid}/nodes/{nodeRunId}/events`,服务端校验当前用户的租户成员身份后按启动者的会话读出完整事件流(没有记录发起人的运行回退为调用者;续跑这样的运行会把续跑的人记为发起人),帧格式和对话页的事件流相同,用对话页的 `applySessionEvent` / `conversationOf` 归并,所以节点会话对整个租户可见,包括 Agent 读取的文件内容和工具调用,在共享运行里选用个人 Skill 就等于把它的内容共享给能看到这次运行的所有成员(从任务评论里发起的运行同样适用,发起人就是评论人),运行中和历史回放都会完整呈现。执行桥在一轮结束后就结束节点的会话,所以不显示对话页“会话已结束”的标记。若事件流尚未派发或被服务端拒收(浏览器看到事件流一开始就被永久关闭),节点会话提示无法读取实时会话,不再一直显示“正在等待”;还没有收到任何事件时,节点会话退回两条消息:发给 Agent 的任务(服务端记下的渲染后任务 `payload.task`,没有时用节点的输入)和 Agent 的回答。成功的 Agent 还带着 v2 自己记下的三项:实际使用的执行器(`payload.executor`,Agent 名和插件版本)、模型(`payload.model`;新运行里配置的模型找不到或没配时节点以 `workflow_model_not_found` 失败、不启动会话,所以 `fallback` 总为假,只有旧运行可能为真)和没有应用的设置(`payload.unapplied`)。节点详情在配置的"Agent 模型"下面显示"实际执行";旧运行退回过默认模型的,仍说明原因。 节点详情列出"v2 未应用",按服务端的顺序,前端不从节点配置推导(规则在 v2-server,见其 README):尝试在结果 `payload.unapplied` 里记下了列表(v2-server 只在成功时写)就显示它,哪怕是空的;没有记录时(还没运行、运行中、失败、取消、中断,或没有这项记录的旧运行)显示 v2-server 对这次运行冻结图的 analyze 结果里该节点的 `unappliedSettings`。这个结果按当前服务端的规则给出,不是那次运行当时的规则,所以根 Agent 自动重试上线前就已结束、又没有记录列表的运行不会显示自动重试的提示,虽然它当时没有重试。运行面板对它展示的每次运行都分析一次冻结图(按运行缓存、不重新请求),启动对话框的预检读的也是这一次分析。启用 MCP 的节点当前会在生命周期门禁处拒绝运行:Node 缺少 session_mcp_lifecycle 时显示 mcp_node_capability_missing,有该能力但服务端生命周期尚未接入时显示 mcp_lifecycle_not_ready;空 MCP 不受影响。插件或设置问题显示稳定失败码及相关插件 ID、设置 ID,Node 或服务级错误不归因到某个插件。新运行不再标记 MCP 为未应用。历史运行记下的 `unapplied` 仍保留,所以旧运行不会被改写成已经应用 Skill。 -交互式 Agent 节点(简化版,服务端规则见 `v2-server/README.md` 的“交互式 Agent 节点”):服务端从首轮开始就在 `payload.interactive` 里记下会话摘要,只给它当作交互会话执行的节点记;适配器据此得到 `interactiveSession`(轮数、会话是否已结束、能否完成、阻止原因、完成会采用的回答、发起人发过几条消息、最后一条是否没有送达),运行详情的 `startedBy` 得到发起人。是否把节点当交互会话看只认这份摘要,不看 `agentConfig.interactive`:Loop 里开了交互模式的 Agent 由 v2 自动执行、没有摘要,所以不显示“停止本轮”和简化版说明。舞台卡片和路径条显示“等待输入”;打开节点会话后,发起人(`run-pane.tsx` 用登录用户和 `startedBy` 比较,经 `RunStarterContext` 传下去)看到输入框(Enter 发送)、执行中的“停止本轮”和“完成”,以及“当前为简化版:由发起人确认完成”“停止后不能继续对话”的说明;会话结束后(停止了本轮或 Agent 断开;运行里其他 Agent 开始执行不影响等待中的会话)输入框收起,只能用最后一次正常结束的回答完成,不能完成时按钮禁用并说明原因。发消息的接口先返回成功、服务端之后才把消息交给会话;交不进去时摘要带 `last_turn_error: "not_delivered"`,说的是第 `sent` 条消息,输入框上方提示“上一条消息未送达,请重发”。未送达提示只对发起人显示:只有发起人能重发,其他成员看到的仍是只读说明。发出这条消息的视图记着它的内容和发消息接口返回的序号(响应里的 `sent`,由服务端编号,不从屏幕上的摘要推算,所以发起人的另一个标签页同时在发也不会认错),序号和摘要的 `sent` 对得上时可以“重新填入”(会话已结束的只提示,不能重发);被服务端拒绝的发送不记;屏幕上的摘要比这个视图刚发出的消息还旧时,提示说的是更早的消息,先不显示。下一条消息被接受后提示消失。其他成员只能看:读不到发起人的会话时退回任务和到目前为止的回答。消息、停止和完成调用 `server-runs.ts` 的 `sendNodeTurn`、`stopNodeTurn`、`completeNode`(生成自 `v2-server/workflows.openapi.json`),回答经节点会话事件流到达。desktop 的步骤卡片、确认门禁和强制完成不搬。交互节点会话没能建立时,服务端用 v2 自己的失败类型 `interactive_session`(不自动重试),`node-failure-kinds.ts` 在 desktop 的列表后加了这一项和它的文案。 +交互式 Agent 节点(简化版,服务端规则见 `v2-server/README.md` 的“交互式 Agent 节点”):服务端从首轮开始就在 `payload.interactive` 里记下会话摘要,只给它当作交互会话执行的节点记;适配器据此得到 `interactiveSession`(轮数、会话是否已结束、能否完成、阻止原因、完成会采用的回答、发起人发过几条消息、最后一条是否没有送达),运行详情的 `startedBy` 得到发起人。是否把节点当交互会话看只认这份摘要,不看 `agentConfig.interactive`:Loop 里开了交互模式的 Agent 由 v2 自动执行、没有摘要,所以不显示“停止本轮”和简化版说明。舞台卡片和路径条显示“等待输入”;打开节点会话后,发起人(`run-pane.tsx` 用登录用户和 `startedBy` 比较,经 `RunStarterContext` 传下去)看到输入框(Enter 发送)、执行中的“停止本轮”和“完成”,以及“当前为简化版:由发起人确认完成”“停止后不能继续对话”的说明;会话结束后(停止了本轮或 Agent 断开;运行里其他 Agent 开始执行不影响等待中的会话)输入框收起,只能用最后一次正常结束的回答完成,不能完成时按钮禁用并说明原因。发消息的接口先返回成功、服务端之后才把消息交给会话;交不进去时摘要带 `last_turn_error: "not_delivered"`,说的是第 `sent` 条消息,输入框上方提示“上一条消息未送达,请重发”。未送达提示只对发起人显示:只有发起人能重发,其他成员看到的仍是只读说明。发出这条消息的视图记着它的内容和发消息接口返回的序号(响应里的 `sent`,由服务端编号,不从屏幕上的摘要推算,所以发起人的另一个标签页同时在发也不会认错),序号和摘要的 `sent` 对得上时可以“重新填入”(会话已结束的只提示,不能重发);被服务端拒绝的发送不记;屏幕上的摘要比这个视图刚发出的消息还旧时,提示说的是更早的消息,先不显示。下一条消息被接受后提示消失。其他成员同样能看到完整会话和回放,但没有输入框、“停止本轮”和“完成”;会话还没派发或读不到时,退回任务和到目前为止的回答。消息、停止和完成调用 `server-runs.ts` 的 `sendNodeTurn`、`stopNodeTurn`、`completeNode`(生成自 `v2-server/workflows.openapi.json`),回答经节点会话事件流到达。desktop 的步骤卡片、确认门禁和强制完成不搬。交互节点会话没能建立时,服务端用 v2 自己的失败类型 `interactive_session`(不自动重试),`node-failure-kinds.ts` 在 desktop 的列表后加了这一项和它的文案。 -Interactive Agent nodes (simplified; server rules in `v2-server/README.md`, "Interactive Agent nodes"): from its first turn on, v2-server records a session summary in `payload.interactive`, only for a node it runs as an interactive session, and the adapter reads it into `interactiveSession` (turns, whether the session ended, whether it can complete, the blocker, the answer completion would accept, how many messages the starter has sent and whether the last of them was not delivered) and the run detail's `startedBy` into the run. Only that summary makes a node an interactive session, never `agentConfig.interactive`: a Loop member with interactive mode runs automatically in v2 and has no summary, so it shows neither "停止本轮" nor the simplified-version note. The stage card and the path rail say "等待输入"; in the node session the starter (compared with the signed-in user in `run-pane.tsx` and passed down through `RunStarterContext`) gets a composer (Enter sends), "停止本轮" while a turn runs and "完成", with the notes that completion is confirmed by the starter in this simplified version and that a stopped session cannot continue. Once the session has ended (the turn was stopped or the agent disconnected; other agents of the run starting leave a waiting session alone) the composer goes away and only completion with the last normal answer is left; a blocked completion is disabled with its reason. Sending a message returns before the server hands it to the session; when that fails the summary carries `last_turn_error: "not_delivered"`, which is about message number `sent`, and a notice above the composer says the last message was not delivered. Only the starter sees the notice: nobody else can send again, so other members keep the read-only line. The view that sent the message remembers its text and the number the send answered with (`sent` in the response, assigned by the server rather than counted from the summary on screen, so another tab of the starter's sending at the same time is never mistaken for it), and offers to put the text back when that number equals the summary's `sent` (a session that has ended gets the notice only). A send the server refused is not remembered. A summary older than the message this view just sent has a notice about an earlier message, so it is not shown yet. The notice goes once the next message is accepted. Other members read only, falling back to the task and the answer so far when they cannot read the starter's session. Turns, stops and completion call `sendNodeTurn`, `stopNodeTurn` and `completeNode` in `server-runs.ts`, generated from `v2-server/workflows.openapi.json`; answers arrive over the node's session events. Desktop's step card, confirmation gates and forced completion are not ported. When an interactive node's session cannot be set up, the server uses v2's own failure kind `interactive_session` (never auto-retried); `node-failure-kinds.ts` appends it to desktop's list, with its labels. +Interactive Agent nodes (simplified; server rules in `v2-server/README.md`, "Interactive Agent nodes"): from its first turn on, v2-server records a session summary in `payload.interactive`, only for a node it runs as an interactive session, and the adapter reads it into `interactiveSession` (turns, whether the session ended, whether it can complete, the blocker, the answer completion would accept, how many messages the starter has sent and whether the last of them was not delivered) and the run detail's `startedBy` into the run. Only that summary makes a node an interactive session, never `agentConfig.interactive`: a Loop member with interactive mode runs automatically in v2 and has no summary, so it shows neither "停止本轮" nor the simplified-version note. The stage card and the path rail say "等待输入"; in the node session the starter (compared with the signed-in user in `run-pane.tsx` and passed down through `RunStarterContext`) gets a composer (Enter sends), "停止本轮" while a turn runs and "完成", with the notes that completion is confirmed by the starter in this simplified version and that a stopped session cannot continue. Once the session has ended (the turn was stopped or the agent disconnected; other agents of the run starting leave a waiting session alone) the composer goes away and only completion with the last normal answer is left; a blocked completion is disabled with its reason. Sending a message returns before the server hands it to the session; when that fails the summary carries `last_turn_error: "not_delivered"`, which is about message number `sent`, and a notice above the composer says the last message was not delivered. Only the starter sees the notice: nobody else can send again, so other members keep the read-only line. The view that sent the message remembers its text and the number the send answered with (`sent` in the response, assigned by the server rather than counted from the summary on screen, so another tab of the starter's sending at the same time is never mistaken for it), and offers to put the text back when that number equals the summary's `sent` (a session that has ended gets the notice only). A send the server refused is not remembered. A summary older than the message this view just sent has a notice about an earlier message, so it is not shown yet. The notice goes once the next message is accepted. Other members can read the whole session and its replay but get no composer, "停止本轮" or "完成"; before dispatch, or when the session cannot be read, they fall back to the task and the answer so far. Turns, stops and completion call `sendNodeTurn`, `stopNodeTurn` and `completeNode` in `server-runs.ts`, generated from `v2-server/workflows.openapi.json`; answers arrive over the node's session events. Desktop's step card, confirmation gates and forced completion are not ported. When an interactive node's session cannot be set up, the server uses v2's own failure kind `interactive_session` (never auto-retried); `node-failure-kinds.ts` appends it to desktop's list, with its labels. v2 只做核心执行,有几项界面在、但不会出现或不可用:服务端不执行 desktop 的人工介入(HITL)闸门,回答人工介入的 hook 直接拒绝(交互式 Agent 节点见上文);非交互 Agent(根作用域与 Loop / Iteration 成员)都自动重试,没有从失败处恢复,Iteration 内重试耗尽后按配置继续;AI 诊断、会话索引和文件变更评审没有搬。条件分支没走的节点投影为“未激活分支”,规则沿用 desktop 的 `computeInactiveNodes`。根决策读取 `conditionDecisions`;Iteration 以 `iterationConditionDecisions` 和 0 基 `iteration` 投影 `roundStates`,包含本轮未走的成员;Loop 按 scope 的 1 基 `roundIndex`、独立决策和节点行投影 `rounds`。切换轮次只展示该轮会话与输出,循环结果区分条件满足、达到上限和 LoopExit 主动退出。 @@ -140,7 +140,7 @@ v2 只做核心执行,有几项界面在、但不会出现或不可用:服 Agent 和模型清单读取与 Chat 相同的 `/chat/executors`,保存后端返回的 `agentId` / `modelId`,目录为空或读取失败时不提供演示选项。旧占位配置保留并提示重新选择。角色目录读取工作区服务端目录(与设置页同一份数据);Skill 清单合并当前用户的服务端技能库与租户各空间已确认安装的 Skill 插件,插件标识保留 `namespace/identifier`,运行时检查目标项目的安装回执。MCP 候选读取租户真实安装目录,展示配置是否完整。卸载后已有绑定保留并提示不可用。每个节点最多启用 16 个 MCP,配置使用团队共享设置。安装和选择可以保存,非空执行须待 Node 与服务端完整生命周期接入;当前明确报错,不会忽略已启用的 MCP 后继续运行。 -Agent 检查器在交互模式旁标「暂不生效」和一句原因(`editor/workflow-unapplied-setting-hint.tsx`)。标哪几项只看 v2-server analyze 返回的 `unappliedSettings`,它和运行结果里的 `payload.unapplied` 出自同一段服务端代码;前端只知道每项放在哪个字段旁、原因怎么说,不自己判断。角色、Skill、MCP 与重试已经应用,新分析不再列出它们;历史运行 payload 里保存的 `role`、`skill`、`retry` 标记仍按原样显示。服务端列出某项时提示出现,不再列出时自动消失;列出前端还没有对应字段的项时,在 Agent 设置末尾统一说明。浏览器里的旧工作流库(`local-workflow-backend.ts`)不执行运行,这两项总是空的。工作流页本身不运行工作流,运行在对话页里(见"运行工作流")。 +Agent 检查器在「必需 Skill」下方提示“运行的节点会话对团队可见,所选个人 Skill 的内容也会被看到”,并在交互模式旁标「暂不生效」和一句原因(`editor/workflow-unapplied-setting-hint.tsx`)。标哪几项只看 v2-server analyze 返回的 `unappliedSettings`,它和运行结果里的 `payload.unapplied` 出自同一段服务端代码;前端只知道每项放在哪个字段旁、原因怎么说,不自己判断。角色、Skill、MCP 与重试已经应用,新分析不再列出它们;历史运行 payload 里保存的 `role`、`skill`、`retry` 标记仍按原样显示。服务端列出某项时提示出现,不再列出时自动消失;列出前端还没有对应字段的项时,在 Agent 设置末尾统一说明。浏览器里的旧工作流库(`local-workflow-backend.ts`)不执行运行,这两项总是空的。工作流页本身不运行工作流,运行在对话页里(见"运行工作流")。 ### Unapplied settings and start warnings (English) diff --git a/frontend-v2/e2e/workflow-runs.spec.ts b/frontend-v2/e2e/workflow-runs.spec.ts index 0696ccfe..e1c67fde 100644 --- a/frontend-v2/e2e/workflow-runs.spec.ts +++ b/frontend-v2/e2e/workflow-runs.spec.ts @@ -1,5 +1,9 @@ import { expect, test, type Page } from '@playwright/test' -import { signIn } from './login.ts' +import { randomUUID } from 'node:crypto' +import { Client } from 'pg' +import { ownerName, signIn, signInAsInvitedMember } from './login.ts' + +const database = () => new Client({ connectionString: process.env.E2E_DATABASE_URL ?? 'postgres://ora:ora-local@127.0.0.1:55432/ora_v2_e2e?sslmode=disable' }) // With prepared Node assets (`task v2:node:prepare`, then V2_NODE_ASSETS_DIR) v2-server runs real // Agents on the fixture model; without them, as in CI, it has no Agent to run. @@ -191,6 +195,8 @@ test('workflow runs: a Condition takes one branch and the other shows as inactiv await start.getByLabel('初始 Prompt').fill('客户反馈导出按钮偶尔无响应') await start.getByRole('button', { name: '启动' }).click() await expect(row(realAgents ? '成功' : '失败')).toBeVisible({ timeout: 150_000 }) + await expect(pane.getByText(`由 ${ownerName} 发起`)).toBeVisible() + await expect(row(realAgents ? '成功' : '失败')).toContainText(`由 ${ownerName} 发起`) await pane.getByRole('button', { name: '全图', exact: true }).click() const overview = pane.getByLabel('工作流全图俯瞰') @@ -220,3 +226,236 @@ test('workflow runs: a Condition takes one branch and the other shows as inactiv await expect(pane.getByLabel('实际执行').filter({ visible: true }).first()).toContainText('· Fixture') await screenshot(page, testInfo.outputPath('s2-branch-agent-details.png')) }) + +test('workflow runs: another workspace member sees starter, full live and replayed node session, and cross-tenant stays 404', async ({ browser, page }, testInfo) => { + test.setTimeout(240_000) + await page.goto('/chat') + await signIn(page) + + const tenantId = ((await (await page.request.get('/api/v1/me/tenants')).json()) as { items: { id: string }[] }).items[0]!.id + const suffix = Date.now().toString(36) + const name = `双人协作 ${suffix}` + const runName = `双人可见运行 ${suffix}` + const created = await page.request.post(`/api/v2/tenants/${tenantId}/workflows`, { data: { name, graph: chain } }) + expect(created.status()).toBe(201) + const workflowId = ((await created.json()) as { draft: { workflowId: string } }).draft.workflowId + expect((await page.request.post(`/api/v2/tenants/${tenantId}/workflows/${workflowId}/publish`, { data: { version: 'v1' } })).ok()).toBe(true) + + await page.reload() + await page.getByRole('button', { name: '选择项目' }).click() + await page.getByRole('option', { name: 'Demo', exact: true }).click() + const createdRunResponse = page.waitForResponse((r) => r.request().method() === 'POST' && new RegExp(`/workflows/${workflowId}/runs$`).test(new URL(r.url()).pathname)) + const demo = page.getByRole('complementary', { name: '聊天记录' }).getByRole('region', { name: '项目 Demo' }) + await page.getByRole('button', { name: '运行工作流', exact: true }).click() + await page.getByRole('menuitem', { name: new RegExp(name) }).click() + const dialog = page.getByRole('dialog', { name: '运行工作流' }) + await dialog.getByLabel('运行名称').fill(runName) + await dialog.getByRole('button', { name: '创建运行' }).click() + const runId = ((await (await createdRunResponse).json()) as { run: { id: string } }).run.id + + const pane = page.getByRole('region', { name: '工作流运行' }) + await expect(pane.getByRole('heading', { name: runName })).toBeVisible() + await expect(pane.getByText(/由 .+ 发起/)).toHaveCount(0) + + const colleagueContext = await browser.newContext() + const colleague = await colleagueContext.newPage() + try { + await signInAsInvitedMember(colleague, `/chat?run=${encodeURIComponent(runId)}`) + const colleaguePane = colleague.getByRole('region', { name: '工作流运行' }) + await expect(colleaguePane.getByRole('heading', { name: runName })).toBeVisible({ timeout: 30_000 }) + const colleagueDemo = colleague.getByRole('complementary', { name: '聊天记录' }).getByRole('region', { name: '项目 Demo' }) + const colleagueRow = (status: string) => colleagueDemo.getByRole('button', { name: `工作流运行 ${runName}(${status})` }) + await expect(colleagueRow('未运行')).toBeVisible() + + // Owner starts the run while colleague is watching, so colleague observes both live and finished states. + await pane.getByRole('button', { name: '启动' }).click() + const start = page.getByRole('dialog') + await start.getByLabel('初始 Prompt').fill('请检查双人节点会话可见性') + await start.getByRole('button', { name: '启动' }).click() + + await expect(pane.getByText(`由 ${ownerName} 发起`)).toBeVisible() + await expect(demo.getByRole('button', { name: new RegExp(`工作流运行 ${runName}(`) })).toContainText(`由 ${ownerName} 发起`) + + await expect(colleaguePane.getByText(`由 ${ownerName} 发起`)).toBeVisible({ timeout: 15_000 }) + await expect(colleagueDemo.getByRole('button', { name: new RegExp(`工作流运行 ${runName}(`) })).toContainText(`由 ${ownerName} 发起`) + + let draftNodeRunId = '' + let seededSessionId = '' + let otherTenantId = '' + const db = database() + try { + if (!realAgents) { + await expect(colleagueRow('失败')).toBeVisible({ timeout: 60_000 }) + await expect(colleagueRow('失败')).toContainText(`由 ${ownerName} 发起`) + + // Seed a persisted execution session owned by the run starter so CI mode (without Node assets) + // still exercises starter-scoped session replay for another workspace member. + await db.connect() + const runRow = await db.query<{ started_by: string | null }>('SELECT started_by FROM v2_workflow_runs WHERE id = $1', [runId]) + const starterId = runRow.rows[0]?.started_by + expect(starterId).toBeTruthy() + const nodeRow = await db.query<{ id: string }>( + `SELECT id FROM v2_workflow_node_runs WHERE run_id = $1 AND node_id = 'draft' AND deleted_at IS NULL`, + [runId], + ) + draftNodeRunId = nodeRow.rows[0]?.id ?? '' + expect(draftNodeRunId).toBeTruthy() + + seededSessionId = `e2e-team-session-${randomUUID()}` + const seededTurnId = `e2e-team-turn-${randomUUID()}` + const starterPrompt = `发起人节点会话专属提示词 ${suffix}` + const starterAnswer = `发起人节点会话回答 ${suffix}` + const nowIso = new Date().toISOString() + const caller = { Kind: 'workflow', ID: runId, NodeID: 'draft', AttemptID: 'e2e-ci' } + const turnResult = { Status: 'completed', Answer: starterAnswer, AnswerComplete: true, StopReason: 'end_turn' } + const historyRecords = [ + { + sequence: 1, + data: { at: nowIso, seq: 1, type: 'update', update: { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: starterPrompt } } }, + }, + { + sequence: 2, + data: { at: nowIso, seq: 2, type: 'update', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: starterAnswer } } }, + }, + { sequence: 3, data: { at: nowIso, seq: 3, type: 'turnEnded', stop_reason: 'end_turn' } }, + ] + await db.query( + `INSERT INTO v2_execution_sessions (id, tenant_id, user_id, data, ended_at, event_sequence, turn_position) + VALUES ($1, $2, $3, $4::jsonb, now(), 3, 1)`, + [seededSessionId, tenantId, starterId, JSON.stringify({ ID: seededSessionId, Model: { ID: 'fixture', Name: 'Fixture', BindingVersion: 'v1' }, CreatedAt: nowIso, EndedAt: nowIso })], + ) + await db.query( + `INSERT INTO v2_execution_turns (id, session_id, tenant_id, user_id, caller, position, data, ended_at) + VALUES ($1, $2, $3, $4, $5::jsonb, 1, $6::jsonb, now())`, + [ + seededTurnId, + seededSessionId, + tenantId, + starterId, + JSON.stringify(caller), + JSON.stringify({ + Ref: { SessionID: seededSessionId, TurnID: seededTurnId }, + Caller: caller, + Prompt: [{ type: 'text', text: starterPrompt }], + StartedAt: nowIso, + EndedAt: nowIso, + Result: turnResult, + }), + ], + ) + await db.query( + `INSERT INTO v2_execution_events (session_id, sequence, data) VALUES ($1, 1, $2::jsonb), ($1, 2, $3::jsonb), ($1, 3, $4::jsonb)`, + [ + seededSessionId, + JSON.stringify({ Ref: { SessionID: seededSessionId, TurnID: seededTurnId }, Sequence: 1, OccurredAt: nowIso, Kind: 'history_snapshot', History: { records: historyRecords, incomplete: false } }), + JSON.stringify({ Ref: { SessionID: seededSessionId, TurnID: seededTurnId }, Sequence: 2, OccurredAt: nowIso, Kind: 'turn_ended', Result: turnResult }), + JSON.stringify({ Ref: { SessionID: seededSessionId, TurnID: '' }, Sequence: 3, OccurredAt: nowIso, Kind: 'session_ended' }), + ], + ) + await db.query(`UPDATE v2_workflow_node_runs SET session_id = $1 WHERE id = $2`, [seededSessionId, draftNodeRunId]) + + await colleague.reload() + await expect(colleaguePane.getByRole('heading', { name: runName })).toBeVisible({ timeout: 30_000 }) + await expect(colleaguePane.getByText(`由 ${ownerName} 发起`)).toBeVisible() + await expect(colleagueRow('失败')).toContainText(`由 ${ownerName} 发起`) + await colleaguePane.getByRole('button', { name: '全图', exact: true }).click() + await colleaguePane.getByLabel('工作流全图俯瞰').getByText('起草', { exact: true }).click() + const nodeStreamResponse = colleague.waitForResponse( + (r) => new RegExp(`/workflow-runs/${runId}/nodes/${draftNodeRunId}/events$`).test(new URL(r.url()).pathname), + ) + await colleaguePane.getByRole('button', { name: '查看节点会话' }).click() + const streamRes = await nodeStreamResponse + expect(streamRes.status()).toBe(200) + expect(streamRes.headers()['content-type']).toBe('text/event-stream') + await expect(colleaguePane.getByText(starterPrompt)).toBeVisible({ timeout: 15_000 }) + await expect(colleaguePane.getByText(starterAnswer)).toBeVisible({ timeout: 15_000 }) + + const rawStream = await colleague.request.get(`/api/v2/tenants/${tenantId}/workflow-runs/${runId}/nodes/${draftNodeRunId}/events`) + expect(rawStream.status()).toBe(200) + const streamBody = await rawStream.text() + expect(streamBody).toContain(starterPrompt) + expect(streamBody).toContain(starterAnswer) + expect(streamBody).toContain('event: end') + } else { + // Wait for 起草's session stream to become active while the workflow runs or finishes, and read full session as colleague. + await colleaguePane.getByRole('button', { name: '全图', exact: true }).click() + await expect(colleaguePane.getByLabel('工作流全图俯瞰').getByText('起草', { exact: true })).toBeVisible() + await colleaguePane.getByLabel('工作流全图俯瞰').getByText('起草', { exact: true }).click() + await colleaguePane.getByRole('button', { name: '查看节点会话' }).click() + await expect(colleaguePane.getByText(/根据需求起草方案:请检查双人节点会话可见性/)).toBeVisible({ timeout: 60_000 }) + await expect(colleaguePane.getByText('', { exact: false }).first()).toBeVisible({ timeout: 60_000 }) + await screenshot(colleague, testInfo.outputPath('member-live-session.png')) + + await expect(colleagueRow('成功')).toBeVisible({ timeout: 150_000 }) + await screenshot(colleague, testInfo.outputPath('member-finished-header-sidebar.png')) + await colleaguePane.getByRole('button', { name: '全图', exact: true }).click() + await colleaguePane.getByLabel('工作流全图俯瞰').getByText('审阅', { exact: true }).click() + await colleaguePane.getByRole('button', { name: '查看节点会话' }).click() + await expect(colleaguePane.getByText(/审阅上一步的方案:V2 fixture complete\./)).toBeVisible({ timeout: 30_000 }) + const toEnd = colleaguePane.getByRole('button', { name: '滚动到底部' }) + if (await toEnd.isVisible()) await toEnd.click() + await expect(colleaguePane.getByText(/v2 fixture tool executed/).first()).toBeVisible() + + // Reloading the page keeps starter display and full session replay for the non-starter colleague. + await colleague.reload() + await expect(colleaguePane.getByRole('heading', { name: runName })).toBeVisible({ timeout: 30_000 }) + await expect(colleaguePane.getByText(`由 ${ownerName} 发起`)).toBeVisible() + await expect(colleagueRow('成功')).toContainText(`由 ${ownerName} 发起`) + await colleaguePane.getByRole('button', { name: '全图', exact: true }).click() + await colleaguePane.getByLabel('工作流全图俯瞰').getByText('审阅', { exact: true }).click() + await colleaguePane.getByRole('button', { name: '查看节点会话' }).click() + await expect(colleaguePane.getByText(/审阅上一步的方案:V2 fixture complete\./)).toBeVisible({ timeout: 30_000 }) + const toEndAfterReload = colleaguePane.getByRole('button', { name: '滚动到底部' }) + if (await toEndAfterReload.isVisible()) await toEndAfterReload.click() + await expect(colleaguePane.getByText(/v2 fixture tool executed/).first()).toBeVisible() + await screenshot(colleague, testInfo.outputPath('member-reloaded-session.png')) + + const detail = (await (await colleague.request.get(`/api/v2/tenants/${tenantId}/workflow-runs/${runId}`)).json()) as { + nodes: Array<{ id: string; nodeId: string }> + } + draftNodeRunId = detail.nodes.find((n) => n.nodeId === 'draft')?.id ?? '' + expect(draftNodeRunId).toBeTruthy() + await db.connect() + } + + // Cross-tenant requests from a tenant the colleague DOES belong to reach the workflow handlers + // and must still be rejected with 404 workflow_run_not_found. + const colleagueMe = (await (await colleague.request.get('/api/v1/me')).json()) as { id: string } + const otherTenantRow = await db.query<{ id: string }>( + `INSERT INTO tenants (name) VALUES ($1) RETURNING id::text`, + [`跨租户隔离检查-${suffix}`], + ) + otherTenantId = otherTenantRow.rows[0]!.id + await db.query(`INSERT INTO memberships (tenant_id, user_id, role) VALUES ($1, $2, 'member')`, [otherTenantId, colleagueMe.id]) + + const otherTenantRun = await colleague.request.get(`/api/v2/tenants/${otherTenantId}/workflow-runs/${runId}`) + expect(otherTenantRun.status()).toBe(404) + expect((await otherTenantRun.json()).code).toBe('workflow_run_not_found') + const otherTenantEvents = await colleague.request.get( + `/api/v2/tenants/${otherTenantId}/workflow-runs/${runId}/nodes/${draftNodeRunId}/events`, + ) + expect(otherTenantEvents.status()).toBe(404) + expect((await otherTenantEvents.json()).code).toBe('workflow_run_not_found') + + // Requests targeting a tenant the colleague does not belong to stay 404 as well. + const crossRun = await colleague.request.get(`/api/v2/tenants/00000000-0000-0000-0000-000000000000/workflow-runs/${runId}`) + expect(crossRun.status()).toBe(404) + const crossEvents = await colleague.request.get(`/api/v2/tenants/00000000-0000-0000-0000-000000000000/workflow-runs/${runId}/nodes/${draftNodeRunId}/events`) + expect(crossEvents.status()).toBe(404) + } finally { + if (seededSessionId) { + await db.query(`UPDATE v2_workflow_node_runs SET session_id = NULL WHERE id = $1`, [draftNodeRunId]) + await db.query(`DELETE FROM v2_execution_events WHERE session_id = $1`, [seededSessionId]) + await db.query(`DELETE FROM v2_execution_turns WHERE session_id = $1`, [seededSessionId]) + await db.query(`DELETE FROM v2_execution_sessions WHERE id = $1`, [seededSessionId]) + } + if (otherTenantId) { + await db.query(`DELETE FROM memberships WHERE tenant_id = $1`, [otherTenantId]) + await db.query(`DELETE FROM tenants WHERE id = $1`, [otherTenantId]) + } + await db.end().catch(() => undefined) + } + } finally { + await colleagueContext.close() + } +}) diff --git a/frontend-v2/src/features/chat/workflow-run/node-session.ts b/frontend-v2/src/features/chat/workflow-run/node-session.ts index 003dfc89..0dd40a2e 100644 --- a/frontend-v2/src/features/chat/workflow-run/node-session.ts +++ b/frontend-v2/src/features/chat/workflow-run/node-session.ts @@ -6,11 +6,11 @@ import type { Conversation } from '@/components/agent-thread/model/types' /** * Follows one node attempt's session over v2-server's node events stream and folds it as the chat * page folds a conversation's, so the run page shows the Agent's whole turn: its thinking, tool - * calls and answer, live while it runs. `conversation` is null until the first event arrives, and - * stays null when the stream is refused (an attempt not dispatched yet, or a session that belongs - * to whoever else started the run), so the page keeps showing what the attempt recorded; `refused` - * says the server turned the stream away, which the browser only shows as a stream that closed for - * good before sending anything. + * calls and answer, live while it runs for any member of the workspace. `conversation` is null + * until the first event arrives, and stays null when the stream is unavailable (e.g. an attempt not + * dispatched yet), so the page keeps showing what the attempt recorded; `refused` says the server + * turned the stream away, which the browser only shows as a stream that closed for good before + * sending anything. */ export function useNodeSession( tenantId: string, diff --git a/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx b/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx index 5f35e3f9..6e589707 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx @@ -149,6 +149,8 @@ describe('workflow runs in chat', () => { await user.click(within(start).getByRole('button', { name: '启动' })) expect(within(pane).getByRole('button', { name: '舞台' })).toHaveAttribute('aria-pressed', 'true') await waitFor(() => expect(within(project()).getByRole('button', { name: '工作流运行 审查 cloud#210(成功)' })).toBeInTheDocument(), { timeout: 25_000 }) + expect(within(pane).getByText('由 演示用户 发起')).toBeInTheDocument() + expect(within(within(project()).getByRole('button', { name: '工作流运行 审查 cloud#210(成功)' })).getByText('由 演示用户 发起')).toBeInTheDocument() // The run went pending → running → succeeded under polling; its frozen graph was analyzed once. expect(workflows.seen.filter((request) => request.endsWith('/workflows/analyze'))).toHaveLength(1) expect(await within(pane).findByText('运行完成')).toBeInTheDocument() @@ -418,24 +420,57 @@ describe('workflow runs in chat', () => { expect(stream.closed).toBe(true) }, 30_000) - it("tells a member that a running node's live session belongs to whoever started the run", async () => { + it('lets another workspace member see the starter and follow the full live node session', async () => { runs.hold = true const user = userEvent.setup() await renderPage() await createRun(user, '别人的运行') const pane = await screen.findByRole('region', { name: '工作流运行' }) await within(pane).findByRole('heading', { level: 2, name: '别人的运行' }, { timeout: 10_000 }) + const [entry] = [...runs.runs.values()] + entry!.detail.startedBy = 'user-alice' + entry!.detail.run.startedByName = '爱丽丝' + await user.click(within(pane).getByRole('button', { name: '启动' })) + await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: '启动' })) + + expect(await within(pane).findByText('由 爱丽丝 发起')).toBeInTheDocument() + const row = within(project()).getByRole('button', { name: '工作流运行 别人的运行(运行中)' }) + expect(within(row).getByText('由 爱丽丝 发起')).toBeInTheDocument() + + await user.click(await within(pane).findByRole('button', { name: '查看节点会话' })) + expect(within(pane).getByText('正在准备…')).toBeInTheDocument() + + const attempt = entry!.detail.nodes.find((n) => n.nodeType === 'agent')! + const stream = FakeEventSource.all.find((s) => s.url.endsWith(`/nodes/${attempt.id}/events`))! + act(() => { + stream.emit({ + kind: 'history_snapshot', + history: { records: [line.user(1, '请审查变更'), line.say(2, '正在检查差异…')], incomplete: true }, + }) + }) + expect(await within(pane).findByText('请审查变更')).toBeInTheDocument() + expect(within(pane).getByText('正在检查差异…')).toBeInTheDocument() + expect(within(pane).queryByText(/只有启动这次运行的人能查看实时会话/)).not.toBeInTheDocument() + }, 30_000) + + it('shows an unavailable notice when a node session stream closes before any event arrives', async () => { + runs.hold = true + const user = userEvent.setup() + await renderPage() + await createRun(user, '失效会话的运行') + const pane = await screen.findByRole('region', { name: '工作流运行' }) + await within(pane).findByRole('heading', { level: 2, name: '失效会话的运行' }, { timeout: 10_000 }) await user.click(within(pane).getByRole('button', { name: '启动' })) await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: '启动' })) await user.click(await within(pane).findByRole('button', { name: '查看节点会话' })) expect(within(pane).getByText('正在准备…')).toBeInTheDocument() - // v2-server answers 404 to anyone but the run's starter; the browser closes the stream for good. const [entry] = [...runs.runs.values()] const attempt = entry!.detail.nodes.find((n) => n.nodeType === 'agent')! const stream = FakeEventSource.all.find((s) => s.url.endsWith(`/nodes/${attempt.id}/events`))! act(() => stream.refuse()) - expect(within(pane).getByText('只有启动这次运行的人能查看实时会话;节点完成后会显示任务和回答。')).toBeInTheDocument() + expect(within(pane).getByText('无法读取这个节点的实时会话;节点完成后会显示任务和回答。')).toBeInTheDocument() + expect(within(pane).queryByText(/只有启动这次运行的人能查看实时会话/)).not.toBeInTheDocument() }, 30_000) it('stops a run that is still executing', async () => { diff --git a/frontend-v2/src/features/chat/workflow-run/run-pane.tsx b/frontend-v2/src/features/chat/workflow-run/run-pane.tsx index 6c37398b..bfd0049a 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-pane.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-pane.tsx @@ -317,6 +317,9 @@ function RunWorkspace({ tenantId, run, readOnly, hostedWorkspace, leading, refre {run.taskId && 返回任务} + {run.startedByName && ( + 由 {run.startedByName} 发起 + )} {runStatusLabel(run.status)} diff --git a/frontend-v2/src/features/chat/workflow-run/run-resume-dialog.test.tsx b/frontend-v2/src/features/chat/workflow-run/run-resume-dialog.test.tsx index acc11c57..f53abe5a 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-resume-dialog.test.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-resume-dialog.test.tsx @@ -25,7 +25,7 @@ const definition = normalizeWorkflowDefinition({ }) const emptyDetail = (id: string): WorkflowRunDetail => ({ - run: { id, workflowId: 'wf', snapshotId: 's', projectId: 'p', name: '运行', status: 'failed', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 }, + run: { id, workflowId: 'wf', snapshotId: 's', projectId: 'p', name: '运行', status: 'failed', startedByName: '', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 }, nodes: [], scopes: [], conditionDecisions: {}, iterationConditionDecisions: {}, variables: [], failedAttempts: [], startedBy: null, }) @@ -143,3 +143,4 @@ describe('resume eligibility', () => { expect(runKeys.resumePreview('t', 'r').slice(0, runKeys.run('t', 'r').length)).toEqual([...runKeys.run('t', 'r')]) }) }) + diff --git a/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx b/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx index 6f3fcff7..5c81b730 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx @@ -200,16 +200,21 @@ function RunRow({ tenantId, projectId, run }: { tenantId: string; projectId: str const tone = runStatusTone(run.status) const label = runStatusLabel(run.status) return ( -
+
diff --git a/frontend-v2/src/features/chat/workflow-run/run-theater-interactive.test.tsx b/frontend-v2/src/features/chat/workflow-run/run-theater-interactive.test.tsx index bc3e95b4..706cf89f 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-theater-interactive.test.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-theater-interactive.test.tsx @@ -97,7 +97,7 @@ function nodeRun(over: Partial): WorkflowNodeRun { function rail(a: Partial) { const detail: WorkflowRunDetail = { run: { - id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'awaitingInput', state: '{"current_nodes":["a"]}', + id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'awaitingInput', startedByName: 'Alice', state: '{"current_nodes":["a"]}', input: '需求', output: null, error: null, startedAt: 1_000, finishedAt: null, createdAt: 500, updatedAt: 2_000, }, nodes: [nodeRun({ id: 'start-run' }), nodeRun({ id: 'a-run', nodeId: 'a', nodeType: 'agent', sessionId: 'session-1', finishedAt: null, ...a })], diff --git a/frontend-v2/src/features/chat/workflow-run/server-run-adapter.test.ts b/frontend-v2/src/features/chat/workflow-run/server-run-adapter.test.ts index 1fabe71c..5709b0a7 100644 --- a/frontend-v2/src/features/chat/workflow-run/server-run-adapter.test.ts +++ b/frontend-v2/src/features/chat/workflow-run/server-run-adapter.test.ts @@ -35,7 +35,7 @@ function graphNode(id: string, kind: (typeof definition.nodes)[number]['data'][' function detail(over: Partial, nodes: WorkflowNodeRun[], conditionDecisions: Record = {}): WorkflowRunDetail { return { run: { - id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'running', state: '{"current_nodes":["a"]}', + id: 'run', workflowId: 'wf', snapshotId: 'snap', projectId: 'p', name: '运行', status: 'running', startedByName: '', state: '{"current_nodes":["a"]}', input: '需求', output: null, error: null, startedAt: 1_000, finishedAt: null, createdAt: 500, updatedAt: 2_000, ...over, }, @@ -517,4 +517,11 @@ describe('attempts a resume from failure replaced', () => { const adjacent = nodeRun({ id: 'a4', nodeId: 'a', nodeType: 'agent', status: 'failed', payload: JSON.stringify({ error_detail: { kind: 'session', attempt: 4 } }) }) expect(labels([adjacent], [3])).toEqual([[3, 'manual_resume']]) }) + + it('preserves the starter identity and display name on the adapted run', () => { + const graph = normalizeWorkflowDefinition({ ...definition, nodes: [graphNode('start', 'start'), graphNode('a', 'agent')], edges: [{ id: 'e1', source: 'start', target: 'a' }] }) + const adapted = toGraphWorkflowRun({ ...detail({ startedByName: 'Alice' }, []), startedBy: 'user-alice' }, graph) + expect(adapted.startedBy).toBe('user-alice') + expect(adapted.startedByName).toBe('Alice') + }) }) diff --git a/frontend-v2/src/features/chat/workflow-run/server-run-adapter.ts b/frontend-v2/src/features/chat/workflow-run/server-run-adapter.ts index 408c7c3f..d4073de7 100644 --- a/frontend-v2/src/features/chat/workflow-run/server-run-adapter.ts +++ b/frontend-v2/src/features/chat/workflow-run/server-run-adapter.ts @@ -375,6 +375,7 @@ export function toGraphWorkflowRun(detail: WorkflowRunDetail, definition: Workfl definitionSnapshot: withRunStartValues(definition, detail), name: run.name, status, + startedByName: run.startedByName, nodeStates, rounds, roundStates, diff --git a/frontend-v2/src/features/chat/workflow-run/server-runs.test.tsx b/frontend-v2/src/features/chat/workflow-run/server-runs.test.tsx index 1a7ea46b..beb82c7a 100644 --- a/frontend-v2/src/features/chat/workflow-run/server-runs.test.tsx +++ b/frontend-v2/src/features/chat/workflow-run/server-runs.test.tsx @@ -6,7 +6,7 @@ import type { ReactNode } from 'react' import { beforeEach, describe, expect, it } from 'vitest' import { sampleWorkflowBackend, serveWorkflows, type WorkflowServer } from '@/lib/workflows/test/workflow-server' import { chatBackend, tenantId } from '../test-backend' -import { runSnapshotQuery, useRunStartPreflight, useRunUnappliedSettings } from './server-runs' +import { projectRunsQuery, runSnapshotQuery, useRunStartPreflight, useRunUnappliedSettings } from './server-runs' import { serveRuns, type RunServer } from './test-run-server' const wrapper = ({ children }: { children: ReactNode }) => ( @@ -47,7 +47,7 @@ describe('the run analysis', () => { const { published } = workflows.backend.get({ workflowId }) runs.runs.set(runId, { detail: { - run: { id: runId, workflowId, snapshotId: published!.id, projectId: 'p', name: '冻结', status: 'failed', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 }, + run: { id: runId, workflowId, snapshotId: published!.id, projectId: 'p', name: '冻结', status: 'failed', startedByName: '', state: '{}', input: null, output: null, error: null, startedAt: 1, finishedAt: 2, createdAt: 1, updatedAt: 2 }, nodes: [], scopes: [], conditionDecisions: {}, iterationConditionDecisions: {}, variables: [], failedAttempts: [], startedBy: null, }, graph: published!.graph, @@ -79,4 +79,15 @@ describe('the run analysis', () => { await expect(waitFor(() => expect(analyses()).toBeGreaterThan(1), { timeout: 300 })).rejects.toThrow() expect(snapshotReads()).toBe(1) }) + + it('keeps the starter display name on project run list items', async () => { + const entry = runs.runs.get(runId)! + entry.detail.run.startedByName = '爱丽丝' + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + const own = ({ children }: { children: ReactNode }) => {children} + const { result } = renderHook(() => useQuery(projectRunsQuery(tenantId, 'p')), { wrapper: own }) + await waitFor(() => expect(result.current.data).toHaveLength(1)) + expect(result.current.data![0]).toMatchObject({ id: runId, startedByName: '爱丽丝' }) + }) }) + diff --git a/frontend-v2/src/features/chat/workflow-run/server-runs.ts b/frontend-v2/src/features/chat/workflow-run/server-runs.ts index 2c74f375..f57aa3bb 100644 --- a/frontend-v2/src/features/chat/workflow-run/server-runs.ts +++ b/frontend-v2/src/features/chat/workflow-run/server-runs.ts @@ -225,11 +225,18 @@ export interface RunListItem { id: string name: string status: GraphWorkflowRunStatus + startedByName?: string createdAt: string } function listItem(summary: WorkflowRunSummary): RunListItem { - return { id: summary.id, name: summary.name, status: toDisplayRunStatus(summary.status), createdAt: new Date(summary.createdAt).toISOString() } + return { + id: summary.id, + name: summary.name, + status: toDisplayRunStatus(summary.status), + startedByName: summary.startedByName, + createdAt: new Date(summary.createdAt).toISOString(), + } } /** A project's runs, newest first; read again while any of them still executes. */ @@ -239,7 +246,13 @@ export function projectRunsQuery(tenantId: string, projectId: string) { staleTime: 0, queryFn: async ({ signal }) => { const { runs } = await call(() => listWorkflowRuns(tenantId, { projectId }, undefined, signal)) - const local = cdaseProjectRuns(tenantId, projectId).map(({ id, name, status, createdAt }) => ({ id, name, status, createdAt })) + const local = cdaseProjectRuns(tenantId, projectId).map(({ id, name, status, startedByName, createdAt }) => ({ + id, + name, + status, + startedByName, + createdAt, + })) return [...local, ...runs.map(listItem)].sort((a, b) => b.createdAt.localeCompare(a.createdAt)) }, refetchInterval: (query) => (query.state.data?.some((run) => !isTerminalRunStatus(run.status)) ? runRefreshMs.interval : false), diff --git a/frontend-v2/src/features/chat/workflow-run/test-run-server.ts b/frontend-v2/src/features/chat/workflow-run/test-run-server.ts index 93469a8c..f2a6c364 100644 --- a/frontend-v2/src/features/chat/workflow-run/test-run-server.ts +++ b/frontend-v2/src/features/chat/workflow-run/test-run-server.ts @@ -147,7 +147,8 @@ export function serveRuns(tenantId: string, backend: LocalWorkflowBackend): RunS const at = now() const run: WorkflowRun = { id: `run-${++ids}`, workflowId: created[1]!, snapshotId: published.id, projectId: body.projectId as string, - name: (body.name as string | undefined) ?? '', status: 'pending', state: JSON.stringify({ current_nodes: [] }), + name: (body.name as string | undefined) ?? '', status: 'pending', startedByName: '', + state: JSON.stringify({ current_nodes: [] }), input: null, output: null, error: null, startedAt: null, finishedAt: null, createdAt: at, updatedAt: at, } server.runs.set(run.id, { detail: { run, nodes: [], scopes: [], conditionDecisions: {}, iterationConditionDecisions: {}, variables: [], failedAttempts: [], startedBy: null }, graph: published.graph, version: published.version }) @@ -157,7 +158,10 @@ export function serveRuns(tenantId: string, backend: LocalWorkflowBackend): RunS const projectId = (config.params as { projectId?: string } | undefined)?.projectId const runs = [...server.runs.values()] .filter(({ detail }) => projectId === undefined || detail.run.projectId === projectId) - .map(({ detail: { run }, version }) => ({ id: run.id, name: run.name, projectId: run.projectId, workflowId: run.workflowId, version, status: run.status, startedAt: run.startedAt, finishedAt: run.finishedAt, createdAt: run.createdAt })) + .map(({ detail: { run }, version }) => ({ + id: run.id, name: run.name, projectId: run.projectId, workflowId: run.workflowId, version, status: run.status, + startedByName: run.startedByName, startedAt: run.startedAt, finishedAt: run.finishedAt, createdAt: run.createdAt, + })) return respond(config, 200, { runs }) } const [, runId, action = ''] = url.slice(runsBase.length).match(/^\/([^/]+)(\/[a-z-]+)?$/) ?? [] @@ -182,6 +186,8 @@ export function serveRuns(tenantId: string, backend: LocalWorkflowBackend): RunS if (action === '/start') { if (run.status !== 'pending') return refuse(config, 400, 'workflow_run_start_failed') run.status = 'running' + entry.detail.startedBy = entry.detail.startedBy || 'user-me' + run.startedByName = run.startedByName || '演示用户' run.startedAt = now() execute(entry) return respond(config, 200, { run }) diff --git a/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.test.ts b/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.test.ts new file mode 100644 index 00000000..fe3fba24 --- /dev/null +++ b/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { animateOverlayWidth } from "./theater-overlay-motion"; + +describe("animateOverlayWidth", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("anchors progress to the first animation frame clock rather than performance.now()", () => { + const frames: Array<(time: number) => void> = []; + vi.spyOn(window, "matchMedia").mockReturnValue({ + matches: false, + } as MediaQueryList); + vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => { + frames.push(cb); + return frames.length; + }); + vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined); + // Simulate a large offset between performance.now() and rAF frame timestamps. + vi.spyOn(performance, "now").mockReturnValue(10_000); + + const widths: number[] = []; + const onCollapsed = vi.fn(); + const onComplete = vi.fn(); + const animationRef = { current: null as number | null }; + + animateOverlayWidth({ + animationRef, + duration: 200, + fromWidth: 0, + targetWidth: 320, + onFrame: (width) => widths.push(width), + onCollapsed, + onComplete, + }); + + expect(frames).toHaveLength(1); + frames[0]!(50); + frames[1]!(150); + frames[2]!(250); + + expect(widths[0]).toBe(0); + expect(widths[1]).toBe(280); + expect(widths[2]).toBe(320); + expect(onCollapsed).not.toHaveBeenCalled(); + expect(onComplete).toHaveBeenCalledTimes(1); + expect(animationRef.current).toBeNull(); + }); +}); diff --git a/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.ts b/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.ts index f2c1b6e9..8faaea3e 100644 --- a/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.ts +++ b/frontend-v2/src/features/chat/workflow-run/theater-overlay-motion.ts @@ -51,9 +51,14 @@ export function animateOverlayWidth({ return; } - const startedAt = window.performance.now(); + // Anchor to the first rAF timestamp so progress uses the same clock as frames even when rAF and + // performance.now() have different origins (e.g. after module-load offset in jsdom). + let startedAt: number | null = null; const animate = (now: number): void => { - const progress = Math.min(1, (now - startedAt) / duration); + if (startedAt === null) { + startedAt = now; + } + const progress = duration <= 0 ? 1 : Math.max(0, Math.min(1, (now - startedAt) / duration)); const easedProgress = 1 - (1 - progress) ** 3; onFrame(fromWidth + (targetWidth - fromWidth) * easedProgress); if (progress < 1) { diff --git a/frontend-v2/src/features/chat/workflow-run/translations.ts b/frontend-v2/src/features/chat/workflow-run/translations.ts index 7ff4c7cd..78ab378d 100644 --- a/frontend-v2/src/features/chat/workflow-run/translations.ts +++ b/frontend-v2/src/features/chat/workflow-run/translations.ts @@ -556,7 +556,7 @@ export const workflowRunTranslations = { "回答不符合这个节点要求的结构化输出,请继续对话让 Agent 按格式回答后再完成。", "workflowRun.v2.sessionWaiting": "正在等待 Agent 的会话…", "workflowRun.v2.sessionRefused": - "只有启动这次运行的人能查看实时会话;节点完成后会显示任务和回答。", + "无法读取这个节点的实时会话;节点完成后会显示任务和回答。", }, "en-US": { "workflowRun.loopExit.completed": "Loop ended through an exit node", @@ -1166,6 +1166,6 @@ export const workflowRunTranslations = { "The answer does not match this node's structured output. Continue the conversation until the agent answers in that format.", "workflowRun.v2.sessionWaiting": "Waiting for the Agent's session…", "workflowRun.v2.sessionRefused": - "Only whoever started this run can follow its live session; the task and answer show once the node finishes.", + "Could not follow this node's live session; the task and answer show once the node finishes.", }, } as const; diff --git a/frontend-v2/src/features/workflows/editor/workflow-inspector.test.tsx b/frontend-v2/src/features/workflows/editor/workflow-inspector.test.tsx index b70cdf54..2c2617ad 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-inspector.test.tsx +++ b/frontend-v2/src/features/workflows/editor/workflow-inspector.test.tsx @@ -162,6 +162,14 @@ describe("WorkflowInspector layout", () => { const addSkill = screen.getByRole("button", { name: "添加 Skill" }); expect(addSkill).toBeInTheDocument(); + expect(addSkill).toHaveAccessibleDescription( + /运行的节点会话对团队可见,所选个人 Skill 的内容也会被看到/, + ); + expect( + screen.getByText( + "运行的节点会话对团队可见,所选个人 Skill 的内容也会被看到。", + ), + ).toBeInTheDocument(); expect( screen.getByRole("button", { name: "添加 MCP" }), ).toBeInTheDocument(); diff --git a/frontend-v2/src/features/workflows/editor/workflow-inspector.tsx b/frontend-v2/src/features/workflows/editor/workflow-inspector.tsx index a63fd705..d77a9487 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-inspector.tsx +++ b/frontend-v2/src/features/workflows/editor/workflow-inspector.tsx @@ -7,7 +7,7 @@ import { WorkflowUnappliedSettingHint, } from "./workflow-unapplied-setting-hint"; import type { WorkflowMcpCatalogStatus } from "./mcp-catalog"; -import { useState } from "react"; +import { useId, useState } from "react"; import { useTranslation } from "react-i18next"; import { IconCheck, @@ -471,6 +471,8 @@ function AgentConfigurationFields({ onChange: (config: WorkflowAgentConfig) => void; }) { const { t } = useTranslation(); + const skillRequirementHintId = useId(); + const skillTeamVisibilityHintId = useId(); const [modelPickerOpen, setModelPickerOpen] = useState(false); const [rolePickerOpen, setRolePickerOpen] = useState(false); const [skillPickerOpen, setSkillPickerOpen] = useState(false); @@ -853,6 +855,7 @@ function AgentConfigurationFields({ catalogsLoading && capabilities.skills.length === 0 } aria-label={t("settings.workflow.addSkill")} + aria-describedby={`${skillRequirementHintId} ${skillTeamVisibilityHintId}`} /> } > @@ -918,9 +921,18 @@ function AgentConfigurationFields({
-

+

{t("settings.workflow.skillRequirementHint")}

+

+ {t("settings.workflow.skillTeamVisibilityHint")} +

{config.skills.map((configuredSkill) => { const skill = capabilities.skills.find( diff --git a/frontend-v2/src/lib/workflows/api/generated.ts b/frontend-v2/src/lib/workflows/api/generated.ts index be99c309..9ac0f27f 100644 --- a/frontend-v2/src/lib/workflows/api/generated.ts +++ b/frontend-v2/src/lib/workflows/api/generated.ts @@ -321,6 +321,8 @@ export interface WorkflowRun { projectId: string; name: string; status: WorkflowRunStatus; + /** Starter display name, or empty before the run starts or when unknown. The starter id is the run detail envelope's `startedBy`. */ + startedByName: string; /** @nullable */ state: string | null; /** @nullable */ @@ -356,6 +358,8 @@ export interface WorkflowRunSummary { workflowId: string; version: string; status: WorkflowRunSummaryStatus; + /** Starter display name, or empty before the run starts or when unknown. */ + startedByName: string; /** @nullable */ startedAt: number | null; /** @nullable */ @@ -2799,7 +2803,7 @@ export function useStreamWorkflowRunEvents.<名字>`,按键排序),`sourceNodeId` 取 `writer`,没赋值的不带 `value`,赋了 `null` 的带 `null`;跳过旧的 `selected_branch_id` 路由项,键不合法的项跳过而不让整个详情失败(desktop 在这里报 payload 损坏)。运行开始前没有变量池,读出空列表。`failedAttempts` 是被软删的 `failed` 节点行(desktop 的 `list_failed_attempts`),取各行 `payload.error_detail`,没有的跳过;只有重试、续跑和整次重跑会软删失败行;v2 由自动重试(根作用域与 Loop / Iteration 成员)和「从失败处继续」软删(v2 没有整次重跑),其余情况下为空,当前失败的尝试就是节点自己的行。 - **能力边界**:支持在同一次运行里「从失败处继续」(只保留现状,不回滚文件,见下文);整次运行 restart、checkpoint 回滚和换用新发布版本续跑不在演示范围,顶栏“再跑一次”创建新运行。重启中断由执行桥提供,见下文“工作流执行”。 @@ -740,11 +740,11 @@ The failed attempt is soft-deleted with its real session, answer and failure det - 进程内的派发:每次续跑让运行的进程状态换一代,派发的 Agent 记下自己所属的代;还没开始或已经过了放弃检查、正在解析执行器的旧派发,在登记为执行中的尝试后都会再检查一次(代是否还是当前的、节点行是否还在运行),不满足就撤销登记、不启动会话。所以取消再续跑之后,取消前派发的尝试不会为已软删的行启动 Agent,续跑的新尝试照常执行;同一检查也让兄弟节点在解析执行器期间让运行失败时,这个尝试不再启动。 - 取消与续跑按运行串行:续跑进行中开始的取消会等它结束,再在运行门禁下连同重试门禁重新读运行状态(`FenceRetriesForCancel`),于是看到 running 并停止续跑派发的 Agent;取消进行中时续跑按 `run_settling` 拒绝。这把锁只在先按租户查到运行之后才建,有人持有或等待时才存在,用完即删,所以未知或别的租户的运行 id 不会留下状态;取消先读运行状态,读到之后才设重试门禁、取消重试计时器;状态读失败时取消到此为止,运行原样保留,门禁不设,计时器照常(被取消的计时器不会再有人重新武装)。 - 进程内的重试状态与 #1168 的结算一致:运行离开 running 时等待中的重试已在 PostgreSQL 里收尾,续跑成功后再取消该运行仍挂着的定时器并去掉取消门禁(`CancelRetries` 留下的),否则门禁会吞掉续跑后的下一次可重试失败。 -- 续跑的 Agent 在运行持久化的发起者名下执行,运行的会话始终属于同一个人;没有记录发起者时用调用者。权限与取消相同(本租户成员)。 +- 续跑的 Agent 在运行持久化的发起者名下执行,运行的会话始终属于同一个人;没有记录发起人的运行回退为调用者,续跑这样的运行会把续跑的人记为发起人(`EnsureWorkflowStarter`)。权限与取消相同(本租户成员)。 - 与 desktop 相同的边界:同波次失败后仍保留 `running` 的根作用域 swift 行(见下文“与 desktop 的差异”)会让空闲门一直关着;v2 用 `node_stuck` 说明这种情况,让用户「再跑一次」。 - 只有续跑能帮上忙的失败才在节点详情里提示「从失败处继续」:失败详情 `resumable` 为假的配置类失败(例如 `missing_agent_ref`,同一冻结快照续跑必然再失败)不提示,除非下次尝试会被告知这次失败。 -Follows desktop's `resume_from_failure` (`crates/application/src/workflow_run/engine/engine.rs:169-211`, `crates/db/src/repository/workflow_run_engine/resume.rs:12-146` at `ebd5b725`) with only desktop's keep mode: workspace files are left as they are. Both `GET …/resume-preview` and `POST …/resume` take their plan from `planResume` in `internal/workflow`; the resume replans from the locked rows, so a stale preview cannot bypass a rule. Only failed or cancelled runs resume (`run_not_ended`); a node still executing refuses it (`node_running`, the idle gate; Loop and Iteration rows parked by the ended run do not count, `region.rs:12-24`), as does a run with no failed or cancelled node (`no_failed_node`; the page then hides the action). Owner decision D25 (2026-11-15): a task's handling run (a link in `v2_task_workflow_runs`) is refused as `task_handling`. Its link settles once, so a resume would execute for the task again with the link settled, leave the task's status behind and admit a second handling run on the same task; the page sends the user back to the task and hides the action and the node detail's resume hint. Owner decision D30 (2026-11-16) extends this to the review form's “Retry task creation” (`POST …/form/retry`), the other path that returns a failed run to running: the retry transaction reads the task link under the run lock with the same check as resume (`runTaskLink`) and refuses with 409 `task_handling`, leaving the run, the task and its link unchanged; the page hides that button and points back to the task, and the node error recorded for its failed task creation, on the first dispatch and on a replay alike, points back to the task instead of suggesting a retry (the same text is the failure the task page's workflow history shows), while unowned runs keep it. Owner decision D32 (2026-11-16) extends both refusals to a task decomposition's run (`v2_task_decompositions.workflow_run_id`): its decomposition settles once, when the run ends, so a resumed run would carry on detached from it, its subtasks never written, and, no longer tied to a running decomposition, would be absorbed by the boot sweep across a restart. The preview and `POST …/resume` refuse it as `task_decomposition` in the resume transaction under the run lock, the form retry answers 409 `task_decomposition`, the node error of a failed task creation sends the user back to the task to decompose again, and the page hides “Resume from failure”, the node detail's hint and “Retry task creation” for it. The check runs in the resume transaction under the run lock (the link is created with the run), and inspection and review-source runs, which no task owns (no `run.taskLink`), stay resumable; a decomposition link is inserted after its run is created pending and before it starts, so a run that can resume already has it; `run.taskLink` (`handle` / `decomposition`) tells the page which link owns the run. A frozen review form in the clear set is refused as `review_form` when it was never submitted, as `review_form_retry` when it was submitted, sits behind a restarting container and the failed run's task creation failed (the form's `…/form/retry` precondition, so the page points to its “Retry task creation”), and as `review_form_submitted` otherwise (the form cannot be filled again: “Run again”). The cancel/resume lock exists only while held or awaited, after the run was found in the caller's tenant, and a cancellation reads the run status before it sets the retry fence and cancels the retry timers, so one whose status read fails leaves the run as it was: unfenced, with its timers still armed (nothing would re-arm a cancelled one). v2 adds three more refusals: `node_stuck` when only swift rows a same-wave failure left `running` block the gate (desktop leaves them too, `engine.rs:406-439`; they never end, so the page points to “Run again”); the form refusals above, while a run whose task creation failed after submission, with no container restarting, keeps its form node and resumes normally, rerunning only the task creation; and `run_settling`, in the preview and the resume alike, while the bridge still starts or ends an Agent turn of the run (a stopped session that has not finished ending). Each resume advances the run's process generation and every Agent dispatch carries its generation; once a dispatch holds the start slot it checks again that its generation is current and its row still runs, and otherwise releases the slot without starting a session, so an attempt queued before a cancellation never starts for the row a later resume soft-deleted, and one whose run a sibling failed while it resolved its executor does not start either. Cancellation and resume are serialized per run: a cancellation that begins during a resume waits for it, then re-reads the status together with the retry fence under the run gate (`FenceRetriesForCancel`) and stops the resumed Agent, and a resume during a cancellation is refused as `run_settling`. The node detail suggests resuming only where it can help: not for a failure whose detail says `resumable: false` (a configuration failure such as `missing_agent_ref` that the frozen snapshot cannot change) unless the next attempt is told about it. The clear set is `resume_clear_node_ids` (`region.rs:56-120`): each failed or cancelled node with all its root-graph descendants; anything in a Loop body or Iteration region, and the container itself, resumes through the container, which is cleared with all its members and descendants and restarts from round 1. As in desktop, an Iteration that absorbed member failures under `continue` and succeeded restarts too. One transaction soft-deletes the cleared nodes' live rows in every scope, cancels the round scopes of cleared Loop rows and soft-deletes their rows, removes pool values written by cleared nodes (the catalog stays, `revision` increments), their Condition decisions, Iteration ledgers and per-round decisions, and returns the run to `running` without error, finish instant or current nodes; the normal scheduling pass then recomputes the ready set under the same run gate. Succeeded nodes and unrelated branches stay. For root nodes and Iteration members, attempt numbers continue per `(run, node, iteration)`: a resume after three failed attempts runs attempt 4, without `auto_retry`, so its retry budget is fresh. Loop members are the exception: the resume replaces the Loop row, so its new rounds are new scopes and, under the per-round counting of Loop members (`workflowNodeAttempt`, see “Agent automatic retry”), start again at 1. Replaced attempts stay in `failedAttempts`; the run view labels those of root nodes and Iteration members "resumed manually", each against the live row of the same `(node, iteration)`, and leaves the old Loop rounds' unlabelled. Waits are already settled in PostgreSQL when a run leaves running; after a resume the engine also cancels the run's leftover timers and drops a cancellation fence left by `CancelRetries`, which would otherwise swallow the resumed run's next retryable failure. Resumed Agents execute under the run's persisted starter, so the run's sessions keep one owner (the caller when none is recorded); the permission is the cancellation's. Desktop's boundary remains: a root swift row left `running` after a same-wave failure keeps the idle gate closed, reported as `node_stuck`. A root sibling that finishes after another node failed the run records its outcome without changing the run, so the gate can open and the resume reuses that answer; for a late failure v2 deliberately keeps the original failure anchor (see “A late sibling outcome is recorded”). +Follows desktop's `resume_from_failure` (`crates/application/src/workflow_run/engine/engine.rs:169-211`, `crates/db/src/repository/workflow_run_engine/resume.rs:12-146` at `ebd5b725`) with only desktop's keep mode: workspace files are left as they are. Both `GET …/resume-preview` and `POST …/resume` take their plan from `planResume` in `internal/workflow`; the resume replans from the locked rows, so a stale preview cannot bypass a rule. Only failed or cancelled runs resume (`run_not_ended`); a node still executing refuses it (`node_running`, the idle gate; Loop and Iteration rows parked by the ended run do not count, `region.rs:12-24`), as does a run with no failed or cancelled node (`no_failed_node`; the page then hides the action). Owner decision D25 (2026-11-15): a task's handling run (a link in `v2_task_workflow_runs`) is refused as `task_handling`. Its link settles once, so a resume would execute for the task again with the link settled, leave the task's status behind and admit a second handling run on the same task; the page sends the user back to the task and hides the action and the node detail's resume hint. Owner decision D30 (2026-11-16) extends this to the review form's “Retry task creation” (`POST …/form/retry`), the other path that returns a failed run to running: the retry transaction reads the task link under the run lock with the same check as resume (`runTaskLink`) and refuses with 409 `task_handling`, leaving the run, the task and its link unchanged; the page hides that button and points back to the task, and the node error recorded for its failed task creation, on the first dispatch and on a replay alike, points back to the task instead of suggesting a retry (the same text is the failure the task page's workflow history shows), while unowned runs keep it. Owner decision D32 (2026-11-16) extends both refusals to a task decomposition's run (`v2_task_decompositions.workflow_run_id`): its decomposition settles once, when the run ends, so a resumed run would carry on detached from it, its subtasks never written, and, no longer tied to a running decomposition, would be absorbed by the boot sweep across a restart. The preview and `POST …/resume` refuse it as `task_decomposition` in the resume transaction under the run lock, the form retry answers 409 `task_decomposition`, the node error of a failed task creation sends the user back to the task to decompose again, and the page hides “Resume from failure”, the node detail's hint and “Retry task creation” for it. The check runs in the resume transaction under the run lock (the link is created with the run), and inspection and review-source runs, which no task owns (no `run.taskLink`), stay resumable; a decomposition link is inserted after its run is created pending and before it starts, so a run that can resume already has it; `run.taskLink` (`handle` / `decomposition`) tells the page which link owns the run. A frozen review form in the clear set is refused as `review_form` when it was never submitted, as `review_form_retry` when it was submitted, sits behind a restarting container and the failed run's task creation failed (the form's `…/form/retry` precondition, so the page points to its “Retry task creation”), and as `review_form_submitted` otherwise (the form cannot be filled again: “Run again”). The cancel/resume lock exists only while held or awaited, after the run was found in the caller's tenant, and a cancellation reads the run status before it sets the retry fence and cancels the retry timers, so one whose status read fails leaves the run as it was: unfenced, with its timers still armed (nothing would re-arm a cancelled one). v2 adds three more refusals: `node_stuck` when only swift rows a same-wave failure left `running` block the gate (desktop leaves them too, `engine.rs:406-439`; they never end, so the page points to “Run again”); the form refusals above, while a run whose task creation failed after submission, with no container restarting, keeps its form node and resumes normally, rerunning only the task creation; and `run_settling`, in the preview and the resume alike, while the bridge still starts or ends an Agent turn of the run (a stopped session that has not finished ending). Each resume advances the run's process generation and every Agent dispatch carries its generation; once a dispatch holds the start slot it checks again that its generation is current and its row still runs, and otherwise releases the slot without starting a session, so an attempt queued before a cancellation never starts for the row a later resume soft-deleted, and one whose run a sibling failed while it resolved its executor does not start either. Cancellation and resume are serialized per run: a cancellation that begins during a resume waits for it, then re-reads the status together with the retry fence under the run gate (`FenceRetriesForCancel`) and stops the resumed Agent, and a resume during a cancellation is refused as `run_settling`. The node detail suggests resuming only where it can help: not for a failure whose detail says `resumable: false` (a configuration failure such as `missing_agent_ref` that the frozen snapshot cannot change) unless the next attempt is told about it. The clear set is `resume_clear_node_ids` (`region.rs:56-120`): each failed or cancelled node with all its root-graph descendants; anything in a Loop body or Iteration region, and the container itself, resumes through the container, which is cleared with all its members and descendants and restarts from round 1. As in desktop, an Iteration that absorbed member failures under `continue` and succeeded restarts too. One transaction soft-deletes the cleared nodes' live rows in every scope, cancels the round scopes of cleared Loop rows and soft-deletes their rows, removes pool values written by cleared nodes (the catalog stays, `revision` increments), their Condition decisions, Iteration ledgers and per-round decisions, and returns the run to `running` without error, finish instant or current nodes; the normal scheduling pass then recomputes the ready set under the same run gate. Succeeded nodes and unrelated branches stay. For root nodes and Iteration members, attempt numbers continue per `(run, node, iteration)`: a resume after three failed attempts runs attempt 4, without `auto_retry`, so its retry budget is fresh. Loop members are the exception: the resume replaces the Loop row, so its new rounds are new scopes and, under the per-round counting of Loop members (`workflowNodeAttempt`, see “Agent automatic retry”), start again at 1. Replaced attempts stay in `failedAttempts`; the run view labels those of root nodes and Iteration members "resumed manually", each against the live row of the same `(node, iteration)`, and leaves the old Loop rounds' unlabelled. Waits are already settled in PostgreSQL when a run leaves running; after a resume the engine also cancels the run's leftover timers and drops a cancellation fence left by `CancelRetries`, which would otherwise swallow the resumed run's next retryable failure. Resumed Agents execute under the run's persisted starter, so the run's sessions keep one owner (falling back to the caller when none is recorded, and persisting that resuming caller as the run's starter via `EnsureWorkflowStarter`); the permission is the cancellation's. Desktop's boundary remains: a root swift row left `running` after a same-wave failure keeps the idle gate closed, reported as `node_stuck`. A root sibling that finishes after another node failed the run records its outcome without changing the run, so the gate can open and the resume reuses that answer; for a late failure v2 deliberately keeps the original failure anchor (see “A late sibling outcome is recorded”). 容器的普通业务失败(Loop 上限、反馈/结束判断、LoopExit 结算失败、Iteration 的 `fail` 策略)只写错误消息,沿用 desktop 的轮次失败语义;初始化、计划或持久状态无效才标记 `invalid_run_payload`。Loop 子节点的 `error_detail` 归属于子节点,父节点只继承错误消息并保留自己的 payload;同轮活动兄弟节点取消时保留 `sibling_failed` 原因。 diff --git a/v2-server/internal/server/workflow_run_events.go b/v2-server/internal/server/workflow_run_events.go index f752a05e..a71a921d 100644 --- a/v2-server/internal/server/workflow_run_events.go +++ b/v2-server/internal/server/workflow_run_events.go @@ -76,9 +76,9 @@ func (h *handler) workflowRunEvents(w http.ResponseWriter, r *http.Request, a ac // workflowNodeEvents relays one node attempt's session the way the chat routes relay a // conversation's, so the run page draws it with the chat page's own rendering. The shared -// execution service keeps a session in the scope of whoever started the run, and it is read in the -// caller's own scope: another member of the tenant gets workflow_node_session_not_found and the -// page keeps showing the task and answer the attempt recorded. +// execution service keeps a session in the scope of whoever started the run; after checking the +// caller's tenant membership and locating the run in that tenant, the handler reads the session in +// the starter's scope so any workspace member can follow live and replayed events. func (h *handler) workflowNodeEvents(w http.ResponseWriter, r *http.Request, a access) { s, tenant, ok := h.workflowRunScope(w, a) if !ok { @@ -89,7 +89,8 @@ func (h *handler) workflowNodeEvents(w http.ResponseWriter, r *http.Request, a a fault(w, http.StatusNotFound, "workflow_run_not_found") return } - if _, err := s.WorkflowRun(r.Context(), tenant, runID); err != nil { + run, err := s.WorkflowRun(r.Context(), tenant, runID) + if err != nil { workflowRunFault(w, err, "workflow node events") return } @@ -128,7 +129,11 @@ func (h *handler) workflowNodeEvents(w http.ResponseWriter, r *http.Request, a a fault(w, http.StatusBadRequest, "invalid_cursor") return } - scope := execution.Scope{TenantID: tenant, UserID: a.UserID} + starter := run.StartedBy + if starter == "" { + starter = a.UserID + } + scope := execution.Scope{TenantID: tenant, UserID: starter} stream, err := h.opts.Execution.Subscribe(r.Context(), scope, *sessionID, after) switch { case err == nil: diff --git a/v2-server/internal/server/workflow_run_events_test.go b/v2-server/internal/server/workflow_run_events_test.go index 1a0acb3a..df367a1e 100644 --- a/v2-server/internal/server/workflow_run_events_test.go +++ b/v2-server/internal/server/workflow_run_events_test.go @@ -14,6 +14,7 @@ import ( "github.com/wanglongan587/cloud/v2-server/internal/execution" "github.com/wanglongan587/cloud/v2-server/internal/server" "github.com/wanglongan587/cloud/v2-server/internal/store" + "github.com/wanglongan587/cloud/v2-server/internal/store/storetest" ) // fakeRunEvents is a run invalidation hub a test publishes on by hand. @@ -184,6 +185,9 @@ func TestWorkflowNodeEventsRelayTheAttemptSession(t *testing.T) { call, s, srv := workflowServerWithClient(t, func(o *server.Options) { o.Execution, o.Catalog = rt, rt }) tenant, user, runID := pendingRun(t, call, s) ctx := context.Background() + if err := s.SetWorkflowStarter(ctx, tenant, runID, user); err != nil { + t.Fatal(err) + } if _, err := s.StartWorkflowRun(ctx, tenant, runID); err != nil { t.Fatal(err) } @@ -239,7 +243,7 @@ func TestWorkflowNodeEventsRelayTheAttemptSession(t *testing.T) { if replaced := read(""); len(replaced) != 8 { t.Fatalf("replaced session = %q", replaced) } - // The session is read in the caller's own scope, never another member's. + // The session is read in the starter's scope. mu.Lock() for _, scope := range seen { if scope != (execution.Scope{TenantID: tenant, UserID: user}) { @@ -261,15 +265,39 @@ func TestWorkflowNodeEventsRelayTheAttemptSession(t *testing.T) { } } -func TestWorkflowNodeEventsOfAnotherMembersSessionAreNotFound(t *testing.T) { +func TestWorkflowNodeEventsReadableByTenantMember(t *testing.T) { rt, _ := chatRuntime() - // The execution service keeps the session in its starter's scope; anyone else does not find it. - rt.SubscribeFunc = func(context.Context, execution.Scope, string, uint64) (execution.Stream, error) { - return nil, execution.ErrNotFound + call, s, srv := workflowServerWithClient(t, func(o *server.Options) { o.Execution, o.Catalog = rt, rt }) + tenant, starter, runID := pendingRun(t, call, s) + starterScope := execution.Scope{TenantID: tenant, UserID: starter} + + var mu sync.Mutex + var seenSubscribe, seenTurns []execution.Scope + replay := rt.SubscribeFunc + rt.SubscribeFunc = func(ctx context.Context, scope execution.Scope, sid string, after uint64) (execution.Stream, error) { + mu.Lock() + seenSubscribe = append(seenSubscribe, scope) + mu.Unlock() + if scope != starterScope { + return nil, execution.ErrNotFound + } + return replay(ctx, scope, sid, after) } - call, s, _ := workflowServerWithClient(t, func(o *server.Options) { o.Execution, o.Catalog = rt, rt }) - tenant, _, runID := pendingRun(t, call, s) + readTurns := rt.ReadTurnsFunc + rt.ReadTurnsFunc = func(ctx context.Context, scope execution.Scope, sid, cursor string, limit int) (execution.TurnPage, error) { + mu.Lock() + seenTurns = append(seenTurns, scope) + mu.Unlock() + if scope != starterScope { + return execution.TurnPage{}, execution.ErrNotFound + } + return readTurns(ctx, scope, sid, cursor, limit) + } + ctx := context.Background() + if err := s.SetWorkflowStarter(ctx, tenant, runID, starter); err != nil { + t.Fatal(err) + } if _, err := s.StartWorkflowRun(ctx, tenant, runID); err != nil { t.Fatal(err) } @@ -280,8 +308,86 @@ func TestWorkflowNodeEventsOfAnotherMembersSessionAreNotFound(t *testing.T) { if _, err := s.BindWorkflowNodeSession(ctx, tenant, runID, node.ID, "s-starter"); err != nil { t.Fatal(err) } + + memberToken := storetest.SignIn(t, s, "workflow-member", "鲍勃", store.RoleMember) + memberClient := &http.Client{} + getAsMember := func(url string) *http.Response { + t.Helper() + req, err := http.NewRequest("GET", url, nil) + if err != nil { + t.Fatal(err) + } + req.AddCookie(&http.Cookie{Name: server.SessionCookie, Value: memberToken}) + res, err := memberClient.Do(req) + if err != nil { + t.Fatal(err) + } + return res + } + path := "/api/v2/tenants/" + tenant + "/workflow-runs/" + runID + "/nodes/" + node.ID + "/events" - if status, failure := call("GET", path, nil); status != 404 || failure["code"] != "workflow_node_session_not_found" { - t.Fatalf("another member's session = %d %v", status, failure) + res := getAsMember(srv.base + path) + defer res.Body.Close() + if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" { + t.Fatalf("member events = %d %s", res.StatusCode, res.Header.Get("Content-Type")) + } + var lines []string + for l := range sseLines(t, res.Body) { + lines = append(lines, l) + } + if len(lines) != 8 || lines[0] != "id: 1" || lines[2] != "id: 2" || lines[4] != "id: 3" || lines[6] != "event: end" { + t.Fatalf("member stream = %q", lines) + } + var ended map[string]any + _ = json.Unmarshal([]byte(strings.TrimPrefix(lines[3], "data: ")), &ended) + if ended["kind"] != "turn_ended" || ended["prompt"] != "你好" || ended["result"].(map[string]any)["answer"] != "好" { + t.Fatalf("member turn_ended = %v", ended) + } + + resAfter := getAsMember(srv.base + path + "?after=2") + defer resAfter.Body.Close() + if resAfter.StatusCode != 200 { + t.Fatalf("member replay = %d", resAfter.StatusCode) + } + var replayed []string + for l := range sseLines(t, resAfter.Body) { + replayed = append(replayed, l) + } + if len(replayed) != 4 || replayed[0] != "id: 3" || replayed[2] != "event: end" { + t.Fatalf("member replay stream = %q", replayed) + } + + mu.Lock() + for _, scope := range append(seenSubscribe, seenTurns...) { + if scope != starterScope { + t.Errorf("expected starter scope %+v, got %+v", starterScope, scope) + } + } + mu.Unlock() + + // Cross-tenant requests are still rejected with 404. + crossTenant := getAsMember(srv.base + "/api/v2/tenants/00000000-0000-0000-0000-000000000000/workflow-runs/" + runID + "/nodes/" + node.ID + "/events") + defer crossTenant.Body.Close() + if crossTenant.StatusCode != 404 { + t.Fatalf("cross-tenant status = %d", crossTenant.StatusCode) + } + + // Non-member detail and list also include the starter's identity and display name. + detailRes := getAsMember(srv.base + "/api/v2/tenants/" + tenant + "/workflow-runs/" + runID) + defer detailRes.Body.Close() + if detailRes.StatusCode != 200 { + t.Fatalf("member run detail = %d", detailRes.StatusCode) + } + var detail struct { + Run struct { + StartedByName string `json:"startedByName"` + } `json:"run"` + StartedBy string `json:"startedBy"` + } + if err := json.NewDecoder(detailRes.Body).Decode(&detail); err != nil { + t.Fatal(err) + } + if detail.StartedBy != starter || detail.Run.StartedByName != "Owner" { + t.Fatalf("member run detail starter = %+v started by %v", detail.Run, detail.StartedBy) } } diff --git a/v2-server/internal/server/workflow_runs.go b/v2-server/internal/server/workflow_runs.go index e1b08a09..4565d73e 100644 --- a/v2-server/internal/server/workflow_runs.go +++ b/v2-server/internal/server/workflow_runs.go @@ -33,34 +33,36 @@ type workflowStarterStore interface { } type workflowRunView struct { - TaskID string `json:"taskId,omitempty"` - TaskLink string `json:"taskLink,omitempty"` - ID string `json:"id"` - WorkflowID string `json:"workflowId"` - SnapshotID string `json:"snapshotId"` - ProjectID string `json:"projectId"` - Name string `json:"name"` - Status string `json:"status"` - State *string `json:"state"` - Input *string `json:"input"` - Output *string `json:"output"` - Error *string `json:"error"` - StartedAt *int64 `json:"startedAt"` - FinishedAt *int64 `json:"finishedAt"` - CreatedAt int64 `json:"createdAt"` - UpdatedAt int64 `json:"updatedAt"` + TaskID string `json:"taskId,omitempty"` + TaskLink string `json:"taskLink,omitempty"` + ID string `json:"id"` + WorkflowID string `json:"workflowId"` + SnapshotID string `json:"snapshotId"` + ProjectID string `json:"projectId"` + Name string `json:"name"` + Status string `json:"status"` + StartedByName string `json:"startedByName"` + State *string `json:"state"` + Input *string `json:"input"` + Output *string `json:"output"` + Error *string `json:"error"` + StartedAt *int64 `json:"startedAt"` + FinishedAt *int64 `json:"finishedAt"` + CreatedAt int64 `json:"createdAt"` + UpdatedAt int64 `json:"updatedAt"` } type workflowRunSummaryView struct { - ID string `json:"id"` - Name string `json:"name"` - ProjectID string `json:"projectId"` - WorkflowID string `json:"workflowId"` - Version string `json:"version"` - Status string `json:"status"` - StartedAt *int64 `json:"startedAt"` - FinishedAt *int64 `json:"finishedAt"` - CreatedAt int64 `json:"createdAt"` + ID string `json:"id"` + Name string `json:"name"` + ProjectID string `json:"projectId"` + WorkflowID string `json:"workflowId"` + Version string `json:"version"` + Status string `json:"status"` + StartedByName string `json:"startedByName"` + StartedAt *int64 `json:"startedAt"` + FinishedAt *int64 `json:"finishedAt"` + CreatedAt int64 `json:"createdAt"` } type workflowNodeRunView struct { @@ -113,34 +115,36 @@ func optionalString(raw []byte) *string { func toWorkflowRunView(run store.WorkflowRun) workflowRunView { return workflowRunView{ - ID: run.ID, - WorkflowID: run.WorkflowID, - SnapshotID: run.SnapshotID, - ProjectID: run.ProjectID, - Name: run.Name, - Status: run.Status, - State: optionalString(run.State), - Input: run.Input, - Output: run.Output, - Error: run.Error, - StartedAt: millisPtr(run.StartedAt), - FinishedAt: millisPtr(run.FinishedAt), - CreatedAt: millis(run.CreatedAt), - UpdatedAt: millis(run.UpdatedAt), + ID: run.ID, + WorkflowID: run.WorkflowID, + SnapshotID: run.SnapshotID, + ProjectID: run.ProjectID, + Name: run.Name, + Status: run.Status, + StartedByName: run.StartedByName, + State: optionalString(run.State), + Input: run.Input, + Output: run.Output, + Error: run.Error, + StartedAt: millisPtr(run.StartedAt), + FinishedAt: millisPtr(run.FinishedAt), + CreatedAt: millis(run.CreatedAt), + UpdatedAt: millis(run.UpdatedAt), } } func toWorkflowRunSummaryView(run store.WorkflowRunSummary) workflowRunSummaryView { return workflowRunSummaryView{ - ID: run.ID, - Name: run.Name, - ProjectID: run.ProjectID, - WorkflowID: run.WorkflowID, - Version: run.Version, - Status: run.Status, - StartedAt: millisPtr(run.StartedAt), - FinishedAt: millisPtr(run.FinishedAt), - CreatedAt: millis(run.CreatedAt), + ID: run.ID, + Name: run.Name, + ProjectID: run.ProjectID, + WorkflowID: run.WorkflowID, + Version: run.Version, + Status: run.Status, + StartedByName: run.StartedByName, + StartedAt: millisPtr(run.StartedAt), + FinishedAt: millisPtr(run.FinishedAt), + CreatedAt: millis(run.CreatedAt), } } diff --git a/v2-server/internal/server/workflow_runs_test.go b/v2-server/internal/server/workflow_runs_test.go index 7510f730..b7d449f7 100644 --- a/v2-server/internal/server/workflow_runs_test.go +++ b/v2-server/internal/server/workflow_runs_test.go @@ -80,7 +80,7 @@ func TestWorkflowRunsOverHTTP(t *testing.T) { t.Fatalf("workflow runs = %v", listed) } summary := runs[0].(map[string]any) - if summary["version"] != "v1" || summary["id"] != runID || summary["projectId"] != project.ID { + if summary["version"] != "v1" || summary["id"] != runID || summary["projectId"] != project.ID || summary["startedByName"] != "" { t.Fatalf("summary = %v", summary) } task, err := s.CreateTask(ctx, tid, user, store.TaskInput{Title: "Owned run", ProjectID: project.ID, Assignee: &store.TaskAssigneeRef{Type: "human", ID: user}}) @@ -150,9 +150,10 @@ func TestWorkflowRunsOverHTTP(t *testing.T) { } // The execution bridge owns starting and dispatching; parking is what turns the run into the - // derived awaitingInput the page renders. The starter it records is the one member who may - // talk to the parked node, so the detail names them. - if err := s.SetWorkflowStarter(ctx, tid, runID, me["id"].(string)); err != nil { + // derived awaitingInput the page renders. The starter it records owns the node's session and is + // the only member who may talk to the parked node, so the detail names them; every other member + // of the tenant can still read that session. + if err := s.SetWorkflowStarter(ctx, tid, runID, user); err != nil { t.Fatal(err) } if _, err := s.StartWorkflowRun(ctx, tid, runID); err != nil { @@ -167,8 +168,16 @@ func TestWorkflowRunsOverHTTP(t *testing.T) { } _, detail = call("GET", "/api/v2/tenants/"+tid+"/workflow-runs/"+runID, nil) run = detail["run"].(map[string]any) - if run["status"] != "awaitingInput" || run["startedAt"] == nil || detail["startedBy"] != me["id"] { - t.Fatalf("derived status = %v, started by %v", run, detail["startedBy"]) + if run["status"] != "awaitingInput" || run["startedAt"] == nil || detail["startedBy"] != me["id"] || run["startedByName"] != "Owner" { + t.Fatalf("derived status = %v, started by %v (%v)", run, detail["startedBy"], run["startedByName"]) + } + _, byProjectAfterStart := call("GET", "/api/v2/tenants/"+tid+"/workflow-runs?projectId="+project.ID, nil) + if got := byProjectAfterStart["runs"].([]any)[0].(map[string]any); got["startedByName"] != "Owner" { + t.Fatalf("project runs starter = %v", got) + } + _, byWorkflowAfterStart := call("GET", base+"/"+id+"/runs", nil) + if got := byWorkflowAfterStart["runs"].([]any)[0].(map[string]any); got["startedByName"] != "Owner" { + t.Fatalf("workflow runs starter = %v", got) } nodes := detail["nodes"].([]any) if len(nodes) != 1 { diff --git a/v2-server/internal/store/workflow_engine.go b/v2-server/internal/store/workflow_engine.go index 91f4e7e0..782ce603 100644 --- a/v2-server/internal/store/workflow_engine.go +++ b/v2-server/internal/store/workflow_engine.go @@ -39,8 +39,9 @@ func (s *Store) WorkflowEngineContext(ctx context.Context, runID string) (Workfl FROM v2_workflow_runs r JOIN v2_workflow_snapshots snap ON snap.id = r.snapshot_id WHERE r.id = $1 AND r.deleted_at IS NULL`, runID) run := &out.Run + var starter *string err := row.Scan(&run.ID, &run.TenantID, &run.WorkflowID, &run.SnapshotID, &run.ProjectID, - &run.Name, &run.Status, &run.State, &run.Input, &run.Output, &run.Error, &run.RuntimePayload, + &run.Name, &run.Status, &starter, &run.State, &run.Input, &run.Output, &run.Error, &run.RuntimePayload, &run.StartedAt, &run.FinishedAt, &run.CreatedAt, &run.UpdatedAt, &out.Graph) if errors.Is(err, pgx.ErrNoRows) { return WorkflowEngineRun{}, ErrWorkflowRunNotFound @@ -48,6 +49,9 @@ func (s *Store) WorkflowEngineContext(ctx context.Context, runID string) (Workfl if err != nil { return WorkflowEngineRun{}, fmt.Errorf("read workflow engine context: %w", err) } + if starter != nil { + run.StartedBy = *starter + } return out, nil } diff --git a/v2-server/internal/store/workflow_forms.go b/v2-server/internal/store/workflow_forms.go index 36ad63dc..6db41fbe 100644 --- a/v2-server/internal/store/workflow_forms.go +++ b/v2-server/internal/store/workflow_forms.go @@ -80,6 +80,13 @@ func (s *Store) SetWorkflowStarter(ctx context.Context, tenant, runID, user stri return err } +// EnsureWorkflowStarter records a starter on a legacy run that predated started_by so team +// members can read resumed sessions under one consistent starter identity. +func (s *Store) EnsureWorkflowStarter(ctx context.Context, runID, user string) error { + _, err := s.pool.Exec(ctx, `UPDATE v2_workflow_runs SET started_by=$2::uuid WHERE id=$1 AND started_by IS NULL`, runID, user) + return err +} + // OpenWorkflowForm freezes evidence and parks its node in one transaction. func (s *Store) OpenWorkflowForm(ctx context.Context, runID, nodeRunID string, in WorkflowForm) (WorkflowForm, error) { var out WorkflowForm diff --git a/v2-server/internal/store/workflow_run_lifecycle.go b/v2-server/internal/store/workflow_run_lifecycle.go index 35781665..5eb9e7e4 100644 --- a/v2-server/internal/store/workflow_run_lifecycle.go +++ b/v2-server/internal/store/workflow_run_lifecycle.go @@ -328,7 +328,10 @@ func (s *Store) FinishWorkflowRun(ctx context.Context, tenant, runID, status str finished_at = now(), updated_at = now() WHERE tenant_id = $1 AND id = $2 RETURNING `+workflowRunColumns, tenant, runID, status, output, runError)) - return err + if err != nil { + return err + } + return fillWorkflowStarterName(ctx, tx, &run) }) return run, err } @@ -364,7 +367,10 @@ func cancelWorkflowRun(ctx context.Context, tx pgx.Tx, tenant, runID string) (Wo run, err = scanWorkflowRun(tx.QueryRow(ctx, ` SELECT `+workflowRunColumns+` FROM v2_workflow_runs WHERE tenant_id = $1 AND id = $2`, tenant, runID)) - return err + if err != nil { + return err + } + return fillWorkflowStarterName(ctx, tx, &run) case WorkflowStatusPending, WorkflowStatusRunning: default: return ErrWorkflowRunState @@ -395,7 +401,10 @@ func cancelWorkflowRun(ctx context.Context, tx pgx.Tx, tenant, runID string) (Wo finished_at = now(), updated_at = now() WHERE tenant_id = $1 AND id = $2 RETURNING `+workflowRunColumns, tenant, runID)) - return err + if err != nil { + return err + } + return fillWorkflowStarterName(ctx, tx, &run) }() return run, err } diff --git a/v2-server/internal/store/workflow_runs.go b/v2-server/internal/store/workflow_runs.go index 992d40e4..3419c566 100644 --- a/v2-server/internal/store/workflow_runs.go +++ b/v2-server/internal/store/workflow_runs.go @@ -74,6 +74,8 @@ type WorkflowRun struct { ProjectID string Name string Status string + StartedBy string + StartedByName string State []byte Input *string Output *string @@ -87,15 +89,17 @@ type WorkflowRun struct { // WorkflowRunSummary is a run list row: identity, frozen version and lifecycle, no graph or payload. type WorkflowRunSummary struct { - ID string - Name string - ProjectID string - WorkflowID string - Version string - Status string - StartedAt *time.Time - FinishedAt *time.Time - CreatedAt time.Time + ID string + Name string + ProjectID string + WorkflowID string + Version string + Status string + StartedBy string + StartedByName string + StartedAt *time.Time + FinishedAt *time.Time + CreatedAt time.Time } // WorkflowNodeRun is one node attempt. Failed attempts are soft-deleted rows, so a detail read sees @@ -133,7 +137,7 @@ type WorkflowScope struct { UpdatedAt time.Time } -const workflowRunColumns = `id, tenant_id, workflow_id, snapshot_id, project_id, name, status, state, +const workflowRunColumns = `id, tenant_id, workflow_id, snapshot_id, project_id, name, status, started_by, state, input, output, error, payload, started_at, finished_at, created_at, updated_at` const workflowNodeRunColumns = `id, tenant_id, run_id, scope_id, node_id, node_type, session_id, @@ -156,8 +160,9 @@ const derivedRunStatus = `CASE WHEN r.status = 'running' AND EXISTS ( func scanWorkflowRun(row pgx.Row) (WorkflowRun, error) { var run WorkflowRun + var starter *string err := row.Scan(&run.ID, &run.TenantID, &run.WorkflowID, &run.SnapshotID, &run.ProjectID, - &run.Name, &run.Status, &run.State, &run.Input, &run.Output, &run.Error, &run.RuntimePayload, + &run.Name, &run.Status, &starter, &run.State, &run.Input, &run.Output, &run.Error, &run.RuntimePayload, &run.StartedAt, &run.FinishedAt, &run.CreatedAt, &run.UpdatedAt) if errors.Is(err, pgx.ErrNoRows) { return WorkflowRun{}, ErrWorkflowRunNotFound @@ -165,9 +170,44 @@ func scanWorkflowRun(row pgx.Row) (WorkflowRun, error) { if err != nil { return WorkflowRun{}, fmt.Errorf("scan workflow run: %w", err) } + if starter != nil { + run.StartedBy = *starter + } + return run, nil +} + +func scanWorkflowRunWithStarter(row pgx.Row) (WorkflowRun, error) { + var run WorkflowRun + err := row.Scan(&run.ID, &run.TenantID, &run.WorkflowID, &run.SnapshotID, &run.ProjectID, + &run.Name, &run.Status, &run.StartedBy, &run.StartedByName, &run.State, &run.Input, &run.Output, &run.Error, + &run.RuntimePayload, &run.StartedAt, &run.FinishedAt, &run.CreatedAt, &run.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return WorkflowRun{}, ErrWorkflowRunNotFound + } + if err != nil { + return WorkflowRun{}, fmt.Errorf("scan workflow run: %w", err) + } return run, nil } +func fillWorkflowStarterName(ctx context.Context, q interface { + QueryRow(context.Context, string, ...any) pgx.Row +}, run *WorkflowRun) error { + if run.StartedBy == "" { + return nil + } + var name string + err := q.QueryRow(ctx, `SELECT COALESCE(display_name, '') FROM users WHERE id = $1::uuid`, run.StartedBy).Scan(&name) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return fmt.Errorf("read workflow starter name: %w", err) + } + run.StartedByName = name + return nil +} + // CreateWorkflowRun freezes a published version and the project into a pending run, and opens the // run's root scope in the same transaction so no run ever exists without the scope its first node // needs. The definition row is locked so a concurrent delete or publish cannot move the pointer @@ -330,7 +370,13 @@ func (s *Store) StartWorkflowRun(ctx context.Context, tenant, runID string) (Wor UPDATE v2_workflow_runs SET status = 'running', started_at = now(), updated_at = now() WHERE tenant_id = $1 AND id = $2 AND status = 'pending' AND deleted_at IS NULL RETURNING `+workflowRunColumns, tenant, runID)) - if err == nil || !errors.Is(err, ErrWorkflowRunNotFound) { + if err == nil { + if ferr := fillWorkflowStarterName(ctx, s.pool, &run); ferr != nil { + return WorkflowRun{}, ferr + } + return run, nil + } + if !errors.Is(err, ErrWorkflowRunNotFound) { return run, err } // The update matched nothing: tell "gone" apart from "not pending". @@ -421,9 +467,11 @@ func (s *Store) WorkflowRuns(ctx context.Context, tenant, workflowID, projectID } rows, err := s.pool.Query(ctx, ` SELECT r.id, r.name, r.project_id, r.workflow_id, COALESCE(s.version, ''), `+derivedRunStatus+`, + COALESCE(r.started_by::text, ''), COALESCE(u.display_name, ''), r.started_at, r.finished_at, r.created_at FROM v2_workflow_runs r LEFT JOIN v2_workflow_snapshots s ON s.id = r.snapshot_id + LEFT JOIN users u ON u.id = r.started_by WHERE r.tenant_id = $1 AND r.deleted_at IS NULL AND ($2::uuid IS NULL OR r.workflow_id = $2::uuid) AND ($3::text IS NULL OR r.project_id = $3) @@ -434,7 +482,8 @@ func (s *Store) WorkflowRuns(ctx context.Context, tenant, workflowID, projectID summaries, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (WorkflowRunSummary, error) { var summary WorkflowRunSummary err := row.Scan(&summary.ID, &summary.Name, &summary.ProjectID, &summary.WorkflowID, - &summary.Version, &summary.Status, &summary.StartedAt, &summary.FinishedAt, &summary.CreatedAt) + &summary.Version, &summary.Status, &summary.StartedBy, &summary.StartedByName, + &summary.StartedAt, &summary.FinishedAt, &summary.CreatedAt) return summary, err }) if err != nil { @@ -445,20 +494,24 @@ func (s *Store) WorkflowRuns(ctx context.Context, tenant, workflowID, projectID // WorkflowRun reads one live run in the tenant. func (s *Store) WorkflowRun(ctx context.Context, tenant, runID string) (WorkflowRun, error) { - return scanWorkflowRun(s.pool.QueryRow(ctx, ` + return scanWorkflowRunWithStarter(s.pool.QueryRow(ctx, ` SELECT r.id, r.tenant_id, r.workflow_id, r.snapshot_id, r.project_id, r.name, `+derivedRunStatus+`, + COALESCE(r.started_by::text, ''), COALESCE(u.display_name, ''), r.state, r.input, r.output, r.error, r.payload, r.started_at, r.finished_at, r.created_at, r.updated_at FROM v2_workflow_runs r + LEFT JOIN users u ON u.id = r.started_by WHERE r.tenant_id = $1 AND r.id = $2 AND r.deleted_at IS NULL`, tenant, runID)) } // ScheduledWorkflowRun returns the run a scheduled trigger created, found by the trigger's stable // reference (its occurrence ID), so a dispatcher that lost track of it never creates another. func (s *Store) ScheduledWorkflowRun(ctx context.Context, tenant, triggerRef string) (WorkflowRun, error) { - return scanWorkflowRun(s.pool.QueryRow(ctx, ` + return scanWorkflowRunWithStarter(s.pool.QueryRow(ctx, ` SELECT r.id, r.tenant_id, r.workflow_id, r.snapshot_id, r.project_id, r.name, `+derivedRunStatus+`, + COALESCE(r.started_by::text, ''), COALESCE(u.display_name, ''), r.state, r.input, r.output, r.error, r.payload, r.started_at, r.finished_at, r.created_at, r.updated_at FROM v2_workflow_runs r + LEFT JOIN users u ON u.id = r.started_by WHERE r.tenant_id = $1 AND r.trigger_kind = 'schedule' AND r.trigger_ref = $2 AND r.deleted_at IS NULL`, tenant, triggerRef)) } diff --git a/v2-server/internal/store/workflow_runs_test.go b/v2-server/internal/store/workflow_runs_test.go index 055d7620..c9b7e361 100644 --- a/v2-server/internal/store/workflow_runs_test.go +++ b/v2-server/internal/store/workflow_runs_test.go @@ -194,7 +194,7 @@ func TestWorkflowRunReadsNodesAndScopes(t *testing.T) { if len(runs) != 2 || runs[0].ID != first.ID || runs[1].ID != second.ID { t.Fatalf("run list order = %+v", runs) } - if runs[0].Version != "v1" || runs[0].ProjectID != project.ID || runs[0].Status != store.WorkflowStatusPending { + if runs[0].Version != "v1" || runs[0].ProjectID != project.ID || runs[0].Status != store.WorkflowStatusPending || runs[0].StartedBy != "" || runs[0].StartedByName != "" { t.Fatalf("summary = %+v", runs[0]) } if byProject, err := s.WorkflowRuns(ctx, tenant, "", project.ID); err != nil || len(byProject) != 2 { @@ -204,10 +204,21 @@ func TestWorkflowRunReadsNodesAndScopes(t *testing.T) { t.Fatalf("unknown project filter = %+v %v", none, err) } + if err := s.SetWorkflowStarter(ctx, tenant, first.ID, user); err != nil { + t.Fatal(err) + } started, err := s.StartWorkflowRun(ctx, tenant, first.ID) - if err != nil || started.Status != store.WorkflowStatusRunning || started.StartedAt == nil { + if err != nil || started.Status != store.WorkflowStatusRunning || started.StartedAt == nil || started.StartedBy != user || started.StartedByName != "history-owner" { t.Fatalf("start = %+v %v", started, err) } + listedAfterStart, err := s.WorkflowRuns(ctx, tenant, w.ID, "") + if err != nil || listedAfterStart[0].StartedBy != user || listedAfterStart[0].StartedByName != "history-owner" { + t.Fatalf("summary after start = %+v %v", listedAfterStart, err) + } + engineCtx, err := s.WorkflowEngineContext(ctx, first.ID) + if err != nil || engineCtx.Run.StartedBy != user { + t.Fatalf("engine context starter = %+v %v", engineCtx.Run, err) + } if _, err := s.StartWorkflowRun(ctx, tenant, first.ID); !errors.Is(err, store.ErrWorkflowRunState) { t.Fatalf("double start = %v", err) } @@ -255,7 +266,7 @@ func TestWorkflowRunReadsNodesAndScopes(t *testing.T) { t.Fatalf("park missing node = %v", err) } detail, err := s.WorkflowRun(ctx, tenant, first.ID) - if err != nil || detail.Status != "awaitingInput" { + if err != nil || detail.Status != "awaitingInput" || detail.StartedBy != user || detail.StartedByName != "history-owner" { t.Fatalf("derived run status = %+v %v", detail, err) } // A pending node in a different run does not make this one await input. diff --git a/v2-server/internal/workflowhost/resume.go b/v2-server/internal/workflowhost/resume.go index f3362c37..c764416e 100644 --- a/v2-server/internal/workflowhost/resume.go +++ b/v2-server/internal/workflowhost/resume.go @@ -83,6 +83,9 @@ func (h *Host) ResumeRun(ctx context.Context, scope server.WorkflowRunScope, run } if owner == "" { owner = scope.UserID + if err := h.store.EnsureWorkflowStarter(ctx, runID, owner); err != nil { + return store.WorkflowRun{}, fmt.Errorf("persist workflow run starter: %w", err) + } } // A run that a sibling failed may still have interactive nodes parked in this process, their // rows pending and their sessions open. Close them before planning, so the resume restarts diff --git a/v2-server/workflows.openapi.json b/v2-server/workflows.openapi.json index 3a39946f..a816d8e6 100644 --- a/v2-server/workflows.openapi.json +++ b/v2-server/workflows.openapi.json @@ -525,7 +525,7 @@ "operationId": "streamWorkflowNodeRunEvents", "tags": ["workflowRuns"], "summary": "Follow one node attempt's session events, as Server-Sent Events", - "description": "The same stream as chat.openapi.json's conversation events: each message's id is its session sequence and its data a ChatEvent (a turn_ended carries its prompt); an `end` event follows session_ended and `failure` (data `{code}`) reports a broken stream. The session is read in the caller's own scope, so only whoever started the run can read it. 404 workflow_node_run_not_found when the attempt is not this run's; 404 workflow_node_session_not_found before the attempt was dispatched or when the session is not the caller's.", + "description": "The same stream as chat.openapi.json's conversation events: each message's id is its session sequence and its data a ChatEvent (a turn_ended carries its prompt); an `end` event follows session_ended and `failure` (data `{code}`) reports a broken stream. Any member of the tenant can follow the session; the server checks tenant membership and reads the shared execution session under the run starter's scope. 404 workflow_node_run_not_found when the attempt is not this run's; 404 workflow_node_session_not_found before the attempt was dispatched.", "parameters": [{"$ref": "#/components/parameters/EventCursor"}], "responses": { "200": {"description": "An event stream of the attempt's session events.", "content": {"text/event-stream": {"schema": {"type": "string"}}}}, @@ -1223,7 +1223,7 @@ }, "WorkflowRun": { "type": "object", - "required": ["id", "workflowId", "snapshotId", "projectId", "name", "status", "state", "input", "output", "error", "startedAt", "finishedAt", "createdAt", "updatedAt"], + "required": ["id", "workflowId", "snapshotId", "projectId", "name", "status", "startedByName", "state", "input", "output", "error", "startedAt", "finishedAt", "createdAt", "updatedAt"], "additionalProperties": false, "properties": { "taskId": { "type": "string", "description": "Owning handling or decomposition task, when present." }, @@ -1234,6 +1234,7 @@ "projectId": {"type": "string"}, "name": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "running", "awaitingInput", "succeeded", "failed", "cancelled"]}, + "startedByName": {"type": "string", "description": "Starter display name, or empty before the run starts or when unknown. The starter id is the run detail envelope's `startedBy`."}, "state": {"type": "string", "nullable": true}, "input": {"type": "string", "nullable": true}, "output": {"type": "string", "nullable": true}, @@ -1246,7 +1247,7 @@ }, "WorkflowRunSummary": { "type": "object", - "required": ["id", "name", "projectId", "workflowId", "version", "status", "startedAt", "finishedAt", "createdAt"], + "required": ["id", "name", "projectId", "workflowId", "version", "status", "startedByName", "startedAt", "finishedAt", "createdAt"], "additionalProperties": false, "properties": { "id": {"type": "string", "format": "uuid"}, @@ -1255,6 +1256,7 @@ "workflowId": {"type": "string", "format": "uuid"}, "version": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "running", "awaitingInput", "succeeded", "failed", "cancelled"]}, + "startedByName": {"type": "string", "description": "Starter display name, or empty before the run starts or when unknown."}, "startedAt": {"type": "integer", "format": "int64", "nullable": true}, "finishedAt": {"type": "integer", "format": "int64", "nullable": true}, "createdAt": {"type": "integer", "format": "int64"}