Przeglądaj źródła

fix(workflow): close review and snapshot gaps

pku-xht 2 miesięcy temu
rodzic
commit
4eb0a52840

+ 0 - 23
apps/web/tests/snapshots/workflow-run/ui.expected.md

@@ -1,14 +1,3 @@
-- banner:
-  - navigation "Session hierarchy":
-    - button "Use the workflow tool exactly" [disabled]
-  - button "1 subagent":
-    - text: 1 subagent
-    - img
-  - img
-  - text: 标准模式
-  - tablist:
-    - tab "Chat" [selected]
-    - tab "Trajectory"
 - text: "Use the workflow tool exactly once, with args omitted, meta set to { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" }, and this EXACT script body (copy it verbatim): phase('Run') const reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.') return { reply } After the workflow returns, reply with the single word WORKFLOW_DONE and stop. Do not use any other tool. {{clock}}"
 - button "Copy":
   - img
@@ -41,15 +30,3 @@
 - button "Branch into a new conversation":
   - img
 - text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s
-- button "Back to bottom":
-  - img
-- textbox "Message the agent"
-- button "Commands":
-  - img
-- 'button "Access mode, current: Workspace Write"': Workspace Write
-- button "Select model, current DeepSeek-V4-Flash":
-  - text: DeepSeek-V4-Flash
-  - img
-- button "3% of context used"
-- button "Send message" [disabled]
-- text: 1 turns · 2 steps LLM {{duration}} · Tool call {{duration}} TTFT avg {{duration}} · {{throughput}} tok/s Cache hit 47% Input 6.6K tok · Output 227 tok

+ 14 - 3
apps/web/tests/workflow-run.e2e.ts

@@ -93,8 +93,16 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
       const label = element.querySelector('[data-member-label]')
       const labelWrap = element.querySelector('[data-member-label-wrap]')
       const status = element.querySelector('[data-member-status-text]')
-      const runHeader = element.querySelector('[data-run-header]')
-      const phaseHeader = element.querySelector('[data-phase-header]')
+      const disclosures = element.querySelectorAll('[data-disclosure-row]')
+      const runHeader = disclosures[0]
+      const phaseHeader = disclosures[1]
+      const phaseTitle = phaseHeader?.children.item(1) as HTMLElement | null
+      const phaseStatus = element.querySelector('[data-phase-status-text]')
+      const originalPhaseTitle = phaseTitle?.textContent ?? ''
+      if (phaseTitle !== null) phaseTitle.textContent = 'A phase name long enough to require ellipsis in the narrow layout'
+      const phaseTitleRight = phaseTitle?.getBoundingClientRect().right ?? 0
+      const phaseStatusLeft = phaseStatus?.getBoundingClientRect().left ?? 0
+      if (phaseTitle !== null) phaseTitle.textContent = originalPhaseTitle
       return {
         clientWidth: element.clientWidth,
         scrollWidth: element.scrollWidth,
@@ -105,6 +113,8 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
         statusFontSize: status === null ? '' : getComputedStyle(status).fontSize,
         runHeight: runHeader?.getBoundingClientRect().height ?? 0,
         phaseHeight: phaseHeader?.getBoundingClientRect().height ?? 0,
+        phaseTitleRight,
+        phaseStatusLeft,
       }
     })
     expect(darkNarrow.clientWidth).toBe(356)
@@ -116,6 +126,7 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
     expect(darkNarrow.statusFontSize).toBe('13px')
     expect(darkNarrow.runHeight).toBe(32)
     expect(darkNarrow.phaseHeight).toBe(32)
+    expect(darkNarrow.phaseTitleRight).toBeLessThanOrEqual(darkNarrow.phaseStatusLeft)
     await page.locator('[data-workflow-run]').evaluate((element) => {
       (element as HTMLElement).style.removeProperty('width')
       document.body.removeAttribute('data-ds-dark-theme')
@@ -158,7 +169,7 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
     await page.getByText(CHILD_PROMPT, { exact: false }).waitFor()
     expect(await page.getByRole('button', { name: /^Open Reply with exactly the word/ }).count()).toBe(0)
 
-    const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
+    const snapshot = await captureStableAria(page, '[data-chat-flow]', scaffold.workspaceCwd)
     await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
   }, 60_000)
 

+ 2 - 2
docs/config-catalog.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/config-catalog.md
-config-catalog.md: d9b70eb15865b45d0d8251789d6d661cd9747024
-config-catalog.zh.md: 4974a7e53c60507c2dced9a93cb5e2a2ba0ed850
+config-catalog.md: 7ae543267733cbe27541b1fca5599a2a09d6462d
+config-catalog.zh.md: 5ed7b1fc2cf6576496ec144d1fdccf85ce646717

+ 1 - 1
docs/config-catalog.md

@@ -2412,7 +2412,7 @@ export interface Config {
 }
 ```
 
-Source: [`packages/workflow/tool-workflow/src/index.ts:34`](../packages/workflow/tool-workflow/src/index.ts)
+Source: [`packages/workflow/tool-workflow/src/index.ts:33`](../packages/workflow/tool-workflow/src/index.ts)
 
 ## `@deepseek-ai/dsh-tools`
 

+ 1 - 1
docs/config-catalog.zh.md

@@ -2413,7 +2413,7 @@ export interface Config {
 }
 ```
 
-来源:[`packages/workflow/tool-workflow/src/index.ts:34`](../packages/workflow/tool-workflow/src/index.ts)
+来源:[`packages/workflow/tool-workflow/src/index.ts:33`](../packages/workflow/tool-workflow/src/index.ts)
 
 ## `@deepseek-ai/dsh-tools`
 

+ 2 - 2
docs/subsystems/workflow.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/subsystems/workflow.md
-workflow.md: b651a5459d4ff8c71de223ca2b51dca997ab86bf
-workflow.zh.md: 0fd32675c8612dfeee1dbce7cd8e9977bbe330ef
+workflow.md: 3c7cc39feb8493b9ace11ae10c031a34a3942aee
+workflow.zh.md: c945a339c91402004a790ebc1ce7ffd5f8921ef6

+ 1 - 1
docs/subsystems/workflow.md

@@ -125,7 +125,7 @@ The top-level `dsh-tool-workflow` consumer projects display facts into its calli
 
 `dsh-tool-workflow/invariant` validates the same protocol before live commit and when a Session is loaded: one start per run, positive unique member sequences, paired member endings, no run ending with open members, and no updates after the run ending. A missing member ending or run ending at the log tail is valid interruption evidence rather than corruption.
 
-`dsh-client-ui-workflow-run` folds the four events through the Conversation Node engine into one `workflow-run` Chat node anchored at the run-start sequence, after the original workflow tool node. Phase groups come only from actual member starts and preserve exact strings, including the distinction between an omitted phase and `''`. Closed Locations turn missing terminal facts into interrupted presentation. The 32-pixel run row uses module-platform background, persistent chevrons, and inline dot plus status text; 32-pixel phase rows keep title and count in the main area and precise aggregate status in a fixed tail without another dot; members use a 16-pixel dot slot and fixed 64-pixel lifecycle column. Underlined names alone mark navigation while the member and current list both prove a running same-parent local subagent.
+`dsh-client-ui-workflow-run` folds the four events through the Conversation Node engine into one `workflow-run` Chat node anchored at the run-start sequence, after the original workflow tool node. Phase groups come only from actual member starts and preserve exact strings, including the distinction between an omitted phase and `''`. Closed Locations turn missing terminal facts into interrupted presentation. The [UI package README](../../packages/client/ui-workflow-run/README.md) owns disclosure, status, and same-parent local navigation behavior.
 
 <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
 

+ 1 - 1
docs/subsystems/workflow.zh.md

@@ -125,7 +125,7 @@ interface WorkflowRun {
 
 `dsh-tool-workflow/invariant` 会在实时提交前和 Session 加载时校验同一协议:每个运行只有一个 start,成员序号为正且唯一,成员 end 必须配对,仍有开放成员时不能结束运行,运行结束后不能继续更新。日志尾部缺少成员 end 或 run end 是有效的中断证据,不是损坏。
 
-`dsh-client-ui-workflow-run` 通过 Conversation Node 引擎把四类事件折叠为一个 `workflow-run` Chat 节点,以 run-start 序号锚定在原工作流工具节点之后。阶段组只来自真正开始过的成员,并保留精确字符串,包括字段缺省与 `''` 的区别。Location 关闭时,缺失终点会显示为已中断。32 像素运行行使用 module-platform 背景、常驻 chevron 与内联状态点加文字;32 像素阶段行在主区显示标题和计数,在固定尾部精确显示聚合状态且不重复状态点;成员使用 16 像素状态点槽和固定 64 像素生命周期列。只有成员状态与当前列表同时证明它是同父级、仍运行的本地 subagent 时,带下划线名称才标记普通 Session 导航。
+`dsh-client-ui-workflow-run` 通过 Conversation Node 引擎把四类事件折叠为一个 `workflow-run` Chat 节点,以 run-start 序号锚定在原工作流工具节点之后。阶段组只来自真正开始过的成员,并保留精确字符串,包括字段缺省与 `''` 的区别。Location 关闭时,缺失终点会显示为已中断。[界面包 README](../../packages/client/ui-workflow-run/README.md)负责定义 disclosure、状态与同父本地导航行为。
 
 <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
 

+ 26 - 22
examples/acp-agent/tests/snapshots/advanced-toolchain/session.jsonl

@@ -4,7 +4,7 @@
 {"type":"agent/inbox/spliced","seq":2,"time":1785821417919,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
 {"type":"step/start","seq":3,"time":1783957884486,"data":{"turn":1,"step":1}}
 {"type":"user/message","seq":4,"time":1785498801761,"data":{"content":[{"type":"text","text":"Run this advanced flow exactly once: try a no-op temporary Cordis Plugin named snapshot-marker; use run_code to inspect the live temporary Plugins through tools.cordis_inspect; delegate once to a direct spawn child; run one workflow that delegates to another spawn child; stop dyn-1; then reply with exactly ADVANCED_ACP_OK."}],"source":{"kind":"user"},"role":"user","id":"6e45782a-31be-4ba7-8c4a-7411a2027e36"},"surfaceOp":"append"}
-{"type":"user/message","seq":5,"time":1785730458430,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"9f38e2b8-1d4e-4c90-8896-00aa42307ea7"},"surfaceOp":"append"}
+{"type":"user/message","seq":5,"time":1785730458430,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"f66cc92b-b90c-4aeb-9568-7463d5eeede9"},"surfaceOp":"append"}
 {"type":"session/title","seq":6,"time":1785730458430,"data":{"title":"Run this advanced flow exactly","messageSeqs":[4],"source":{"kind":"fallback"}}}
 {"type":"request/header","seq":7,"time":1785498801765,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}}
 {"type":"request/context","seq":8,"time":1785730458431,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
@@ -47,24 +47,28 @@
 {"type":"assistant/chunk","seq":45,"time":1785730458577,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
 {"type":"assistant/message","seq":46,"time":1785730458577,"data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\":\"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\",\"meta\":{\"name\":\"advanced-acp-snapshot\",\"description\":\"exercise one workflow child through ACP\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"ebeca5c6-68ae-43b3-87c3-c48fdfe416c8"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[41,42,43,44,45],"surfaceOp":"append"}
 {"type":"tool/call","seq":47,"time":1785730458577,"data":{"turn":1,"step":4,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\":\"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\",\"meta\":{\"name\":\"advanced-acp-snapshot\",\"description\":\"exercise one workflow child through ACP\"}}"}}
-{"type":"tool/result","seq":48,"time":1785730458711,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-acp-snapshot\" completed (1 agent).\nReturn value:\n{\n  \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"f892f17e-1e93-4f4b-9e9e-15116593b6fc"}},"sourceEventSeqs":[47],"surfaceOp":"append"}
-{"type":"step/end","seq":49,"time":1785730458711,"data":{"turn":1,"step":4}}
-{"type":"step/start","seq":50,"time":1785730458723,"data":{"turn":1,"step":5}}
-{"type":"assistant/chunk","seq":51,"time":1783957884719,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
-{"type":"assistant/chunk","seq":52,"time":1783957884719,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-unmount","name":"cordis_unmount","argumentsDelta":"{\"id\":\"dyn-1\"}"}}}
-{"type":"assistant/chunk","seq":53,"time":1785036891795,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}}}
-{"type":"assistant/chunk","seq":54,"time":1785498802087,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
-{"type":"assistant/chunk","seq":55,"time":1785730458728,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
-{"type":"assistant/message","seq":56,"time":1785730458728,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"1291ce3c-e568-4f0d-a95a-5157b8b2cc75"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[51,52,53,54,55],"surfaceOp":"append"}
-{"type":"tool/call","seq":57,"time":1785730458728,"data":{"turn":1,"step":5,"callId":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}
-{"type":"tool/result","seq":58,"time":1785730458735,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-unmount"},"content":[{"type":"tool-result","toolCallId":"advanced-unmount","content":[{"type":"text","text":"Temporary Plugin dyn-1 was unmounted and removed."}],"isError":false}],"role":"user","id":"b3634221-2358-4e82-aac5-e37f0a115023"}},"sourceEventSeqs":[57],"surfaceOp":"append"}
-{"type":"step/end","seq":59,"time":1785730458735,"data":{"turn":1,"step":5}}
-{"type":"step/start","seq":60,"time":1785730458747,"data":{"turn":1,"step":6}}
-{"type":"assistant/chunk","seq":61,"time":1783957884720,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
-{"type":"assistant/chunk","seq":62,"time":1783957884720,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_ACP_OK"}}}
-{"type":"assistant/chunk","seq":63,"time":1785036891804,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_ACP_OK"}}}}
-{"type":"assistant/chunk","seq":64,"time":1785498802107,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
-{"type":"assistant/chunk","seq":65,"time":1785730458751,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
-{"type":"assistant/message","seq":66,"time":1785730458751,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_ACP_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"a32b89ce-13ed-48ba-a7f9-24144b94ec56"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[61,62,63,64,65],"surfaceOp":"append"}
-{"type":"step/end","seq":67,"time":1785730458751,"data":{"turn":1,"step":6}}
-{"type":"turn/end","seq":68,"time":1785730458751,"data":{"turn":1,"reason":{"kind":"completed"}}}
+{"type":"tool-workflow/run-start","seq":48,"time":1786359248404,"data":{"runId":"2f6d6a6e-6d76-4a8a-8677-6671366645dc","name":"advanced-acp-snapshot"}}
+{"type":"tool-workflow/agent-start","seq":49,"time":1786359248518,"data":{"runId":"2f6d6a6e-6d76-4a8a-8677-6671366645dc","seq":1,"label":"workflow-child","phase":"Delegate","childId":"33333333-3333-4333-8333-333333333333"}}
+{"type":"tool-workflow/agent-end","seq":50,"time":1786359248542,"data":{"runId":"2f6d6a6e-6d76-4a8a-8677-6671366645dc","seq":1,"outcome":"completed"}}
+{"type":"tool-workflow/run-end","seq":51,"time":1786359248543,"data":{"runId":"2f6d6a6e-6d76-4a8a-8677-6671366645dc","stopReason":"completed"}}
+{"type":"tool/result","seq":52,"time":1786359248543,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-acp-snapshot\" completed (1 agent).\nReturn value:\n{\n  \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"f892f17e-1e93-4f4b-9e9e-15116593b6fc"}},"sourceEventSeqs":[47],"surfaceOp":"append"}
+{"type":"step/end","seq":53,"time":1786359248543,"data":{"turn":1,"step":4}}
+{"type":"step/start","seq":54,"time":1786359248550,"data":{"turn":1,"step":5}}
+{"type":"assistant/chunk","seq":55,"time":1785730458728,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
+{"type":"assistant/chunk","seq":56,"time":1786359248554,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-unmount","name":"cordis_unmount","argumentsDelta":"{\"id\":\"dyn-1\"}"}}}
+{"type":"assistant/chunk","seq":57,"time":1786359248554,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}}}
+{"type":"assistant/chunk","seq":58,"time":1786359248554,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
+{"type":"assistant/chunk","seq":59,"time":1786359248554,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
+{"type":"assistant/message","seq":60,"time":1786359248554,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"1291ce3c-e568-4f0d-a95a-5157b8b2cc75"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[55,56,57,58,59],"surfaceOp":"append"}
+{"type":"tool/call","seq":61,"time":1786359248554,"data":{"turn":1,"step":5,"callId":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}
+{"type":"tool/result","seq":62,"time":1786359248558,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-unmount"},"content":[{"type":"tool-result","toolCallId":"advanced-unmount","content":[{"type":"text","text":"Temporary Plugin dyn-1 was unmounted and removed."}],"isError":false}],"role":"user","id":"b3634221-2358-4e82-aac5-e37f0a115023"}},"sourceEventSeqs":[61],"surfaceOp":"append"}
+{"type":"step/end","seq":63,"time":1786359248558,"data":{"turn":1,"step":5}}
+{"type":"step/start","seq":64,"time":1786359248564,"data":{"turn":1,"step":6}}
+{"type":"assistant/chunk","seq":65,"time":1785730458751,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
+{"type":"assistant/chunk","seq":66,"time":1786359248568,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_ACP_OK"}}}
+{"type":"assistant/chunk","seq":67,"time":1786359248568,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_ACP_OK"}}}}
+{"type":"assistant/chunk","seq":68,"time":1786359248568,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
+{"type":"assistant/chunk","seq":69,"time":1786359248568,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
+{"type":"assistant/message","seq":70,"time":1786359248568,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_ACP_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"a32b89ce-13ed-48ba-a7f9-24144b94ec56"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[65,66,67,68,69],"surfaceOp":"append"}
+{"type":"step/end","seq":71,"time":1786359248568,"data":{"turn":1,"step":6}}
+{"type":"turn/end","seq":72,"time":1786359248568,"data":{"turn":1,"reason":{"kind":"completed"}}}

+ 19 - 15
examples/acp-agent/tests/snapshots/workflow-run/session.jsonl

@@ -4,7 +4,7 @@
 {"type":"agent/inbox/spliced","seq":2,"time":1785821416248,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
 {"type":"step/start","seq":3,"time":1783600631839,"data":{"turn":1,"step":1}}
 {"type":"user/message","seq":4,"time":1785498800152,"data":{"content":[{"type":"text","text":"Use the workflow tool exactly once, with args omitted, meta set to { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" }, and this EXACT script body (copy it verbatim):\nphase('Run')\nconst reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.')\nreturn { reply }\nAfter the workflow returns, reply with the single word WORKFLOW_DONE and stop. Do not use any other tool."}],"source":{"kind":"user"},"role":"user","id":"5188a9c7-d3ca-4679-b8df-1443e0a0a4df"},"surfaceOp":"append"}
-{"type":"user/message","seq":5,"time":1785730457160,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"1c92c213-1d4f-45ad-be50-161f26a23e65"},"surfaceOp":"append"}
+{"type":"user/message","seq":5,"time":1785730457160,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"7b864c39-41fc-4bfb-809a-0dd9f1dc4383"},"surfaceOp":"append"}
 {"type":"session/title","seq":6,"time":1785730457160,"data":{"title":"Use the workflow tool exactly","messageSeqs":[4],"source":{"kind":"fallback"}}}
 {"type":"request/header","seq":7,"time":1785498800153,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}}
 {"type":"request/context","seq":8,"time":1785730457161,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
@@ -18,17 +18,21 @@
 {"type":"assistant/chunk","seq":163,"time":1785730457174,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
 {"type":"assistant/message","seq":164,"time":1785730457174,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to use the workflow tool exactly once with specific parameters. Let me carefully follow the instructions:\n\n1. args omitted (so I don't include it)\n2. meta = { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" }\n3. script = as given verbatim\n4. After it returns, reply with \"WORKFLOW_DONE\"\n\nLet me do exactly that."},{"type":"tool-call","id":"call_00_dD2BLuNeJCTh2iiYC1QR3449","name":"workflow","arguments":"{\"meta\": {\"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\"}, \"script\": \"\\nphase('Run')\\nconst reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.')\\nreturn { reply }\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"9a15ecb9-11ce-4d1b-9a0a-07cc388dc0e0"},"usage":{"inputTokens":3174,"outputTokens":191,"cacheReadTokens":0,"reasoningTokens":88}},"sourceEventSeqs":[9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163],"surfaceOp":"append"}
 {"type":"tool/call","seq":165,"time":1785730457174,"data":{"turn":1,"step":1,"callId":"call_00_dD2BLuNeJCTh2iiYC1QR3449","name":"workflow","arguments":"{\"meta\": {\"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\"}, \"script\": \"\\nphase('Run')\\nconst reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.')\\nreturn { reply }\\n\"}"}}
-{"type":"tool/result","seq":166,"time":1785730457320,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_dD2BLuNeJCTh2iiYC1QR3449"},"content":[{"type":"tool-result","toolCallId":"call_00_dD2BLuNeJCTh2iiYC1QR3449","content":[{"type":"text","text":"workflow \"snapshot-flow\" completed (1 agent).\nReturn value:\n{\n  \"reply\": \"WF_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"a3ca6fd6-3d4c-4ad2-a67c-fc9479ef4f15"}},"sourceEventSeqs":[165],"surfaceOp":"append"}
-{"type":"step/end","seq":167,"time":1785730457320,"data":{"turn":1,"step":1}}
-{"type":"step/start","seq":168,"time":1785730457334,"data":{"turn":1,"step":2}}
-{"type":"assistant/chunk","seq":169,"time":1783600640134,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}}
-{"type":"reasoning-chunks","seq0":170,"time0":1783600640162,"data":{"turn":1,"step":2,"index":0,"dt":[33,667,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," workflow"," returned"," successfully"," with"," the"," reply"," \"","WF","_CH","ILD","_OK","\"."," Now"," I"," need"," to"," reply"," with"," exactly"," \"","WORK","FL","OW","_D","ONE","\""," and"," stop","."]}}
-{"type":"assistant/chunk","seq":200,"time":1783600640865,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}}
-{"type":"text-chunks","seq0":201,"time0":1783600640865,"data":{"turn":1,"step":2,"index":1,"dt":[0,0,0,0],"texts":["WORK","FL","OW","_D","ONE"]}}
-{"type":"assistant/chunk","seq":206,"time":1783600640865,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly \"WORKFLOW_DONE\" and stop."}}}}
-{"type":"assistant/chunk","seq":207,"time":1783600640865,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"WORKFLOW_DONE"}}}}
-{"type":"assistant/chunk","seq":208,"time":1785498800365,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":328,"outputTokens":36,"cacheReadTokens":3072,"reasoningTokens":30}}}}
-{"type":"assistant/chunk","seq":209,"time":1785730457339,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
-{"type":"assistant/message","seq":210,"time":1785730457339,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly \"WORKFLOW_DONE\" and stop."},{"type":"text","text":"WORKFLOW_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"265fc6fa-19e0-4df9-b4ea-f38141ba4efa"},"usage":{"inputTokens":328,"outputTokens":36,"cacheReadTokens":3072,"reasoningTokens":30}},"sourceEventSeqs":[169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209],"surfaceOp":"append"}
-{"type":"step/end","seq":211,"time":1785730457339,"data":{"turn":1,"step":2}}
-{"type":"turn/end","seq":212,"time":1785730457339,"data":{"turn":1,"reason":{"kind":"completed"}}}
+{"type":"tool-workflow/run-start","seq":166,"time":1786359246611,"data":{"runId":"632cc7d7-38d4-45ba-b6c5-55e5784b2501","name":"snapshot-flow"}}
+{"type":"tool-workflow/agent-start","seq":167,"time":1786359246721,"data":{"runId":"632cc7d7-38d4-45ba-b6c5-55e5784b2501","seq":1,"label":"Reply with exactly the word WF_CHILD_OK and not…","phase":"Run","childId":"583a4db2-3350-436c-b4a5-5615fd159052"}}
+{"type":"tool-workflow/agent-end","seq":168,"time":1786359246743,"data":{"runId":"632cc7d7-38d4-45ba-b6c5-55e5784b2501","seq":1,"outcome":"completed"}}
+{"type":"tool-workflow/run-end","seq":169,"time":1786359246745,"data":{"runId":"632cc7d7-38d4-45ba-b6c5-55e5784b2501","stopReason":"completed"}}
+{"type":"tool/result","seq":170,"time":1786359246745,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_dD2BLuNeJCTh2iiYC1QR3449"},"content":[{"type":"tool-result","toolCallId":"call_00_dD2BLuNeJCTh2iiYC1QR3449","content":[{"type":"text","text":"workflow \"snapshot-flow\" completed (1 agent).\nReturn value:\n{\n  \"reply\": \"WF_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"a3ca6fd6-3d4c-4ad2-a67c-fc9479ef4f15"}},"sourceEventSeqs":[165],"surfaceOp":"append"}
+{"type":"step/end","seq":171,"time":1786359246746,"data":{"turn":1,"step":1}}
+{"type":"step/start","seq":172,"time":1786359246751,"data":{"turn":1,"step":2}}
+{"type":"assistant/chunk","seq":173,"time":1783600640862,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}}
+{"type":"reasoning-chunks","seq0":174,"time0":1783600640862,"data":{"turn":1,"step":2,"index":0,"dt":[0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," workflow"," returned"," successfully"," with"," the"," reply"," \"","WF","_CH","ILD","_OK","\"."," Now"," I"," need"," to"," reply"," with"," exactly"," \"","WORK","FL","OW","_D","ONE","\""," and"," stop","."]}}
+{"type":"assistant/chunk","seq":204,"time":1783600640865,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}}
+{"type":"text-chunks","seq0":205,"time0":1783600640865,"data":{"turn":1,"step":2,"index":1,"dt":[0,0,1898159500,231656974],"texts":["WORK","FL","OW","_D","ONE"]}}
+{"type":"assistant/chunk","seq":210,"time":1786359246756,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly \"WORKFLOW_DONE\" and stop."}}}}
+{"type":"assistant/chunk","seq":211,"time":1786359246756,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"WORKFLOW_DONE"}}}}
+{"type":"assistant/chunk","seq":212,"time":1786359246756,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":328,"outputTokens":36,"cacheReadTokens":3072,"reasoningTokens":30}}}}
+{"type":"assistant/chunk","seq":213,"time":1786359246756,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
+{"type":"assistant/message","seq":214,"time":1786359246756,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly \"WORKFLOW_DONE\" and stop."},{"type":"text","text":"WORKFLOW_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"265fc6fa-19e0-4df9-b4ea-f38141ba4efa"},"usage":{"inputTokens":328,"outputTokens":36,"cacheReadTokens":3072,"reasoningTokens":30}},"sourceEventSeqs":[173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213],"surfaceOp":"append"}
+{"type":"step/end","seq":215,"time":1786359246757,"data":{"turn":1,"step":2}}
+{"type":"turn/end","seq":216,"time":1786359246757,"data":{"turn":1,"reason":{"kind":"completed"}}}

Plik diff jest za duży
+ 2 - 2
examples/headless-agent/tests/snapshots/advanced-toolchain/session.jsonl


+ 25 - 21
examples/headless-agent/tests/snapshots/advanced-toolchain/stream-json.expected.jsonl

@@ -45,25 +45,29 @@
 {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":44,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}
 {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":45,"time":0,"data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\":\"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\",\"meta\":{\"name\":\"advanced-headless-snapshot\",\"description\":\"exercise one workflow child through the headless agent\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[40,41,42,43,44],"surfaceOp":"append"}}
 {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":46,"time":0,"data":{"turn":1,"step":4,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\":\"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\",\"meta\":{\"name\":\"advanced-headless-snapshot\",\"description\":\"exercise one workflow child through the headless agent\"}}"}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":47,"time":0,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-headless-snapshot\" completed (1 agent).\nReturn value:\n{\n  \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[46],"surfaceOp":"append"}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":48,"time":0,"data":{"turn":1,"step":4}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":49,"time":0,"data":{"turn":1,"step":5}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":50,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":51,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-unmount","name":"cordis_unmount","argumentsDelta":"{\"id\":\"dyn-1\"}"}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":52,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":53,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":54,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":55,"time":0,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[50,51,52,53,54],"surfaceOp":"append"}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":56,"time":0,"data":{"turn":1,"step":5,"callId":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":57,"time":0,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-unmount"},"content":[{"type":"tool-result","toolCallId":"advanced-unmount","content":[{"type":"text","text":"Temporary Plugin dyn-1 was unmounted and removed."}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[56],"surfaceOp":"append"}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":58,"time":0,"data":{"turn":1,"step":5}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":59,"time":0,"data":{"turn":1,"step":6}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":60,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":61,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_HEADLESS_OK"}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":62,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_HEADLESS_OK"}}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":63,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":64,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":65,"time":0,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_HEADLESS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[60,61,62,63,64],"surfaceOp":"append"}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":66,"time":0,"data":{"turn":1,"step":6}}}
-{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":67,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool-workflow/run-start","seq":47,"time":0,"data":{"runId":"{{sessionId}}","name":"advanced-headless-snapshot"}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool-workflow/agent-start","seq":48,"time":0,"data":{"runId":"{{sessionId}}","seq":1,"label":"workflow-child","phase":"Delegate","childId":"{{sessionId}}"}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool-workflow/agent-end","seq":49,"time":0,"data":{"runId":"{{sessionId}}","seq":1,"outcome":"completed"}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool-workflow/run-end","seq":50,"time":0,"data":{"runId":"{{sessionId}}","stopReason":"completed"}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":51,"time":0,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-headless-snapshot\" completed (1 agent).\nReturn value:\n{\n  \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[46],"surfaceOp":"append"}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":52,"time":0,"data":{"turn":1,"step":4}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":53,"time":0,"data":{"turn":1,"step":5}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":54,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":55,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-unmount","name":"cordis_unmount","argumentsDelta":"{\"id\":\"dyn-1\"}"}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":56,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":57,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":58,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":59,"time":0,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[54,55,56,57,58],"surfaceOp":"append"}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":60,"time":0,"data":{"turn":1,"step":5,"callId":"advanced-unmount","name":"cordis_unmount","arguments":"{\"id\":\"dyn-1\"}"}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":61,"time":0,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-unmount"},"content":[{"type":"tool-result","toolCallId":"advanced-unmount","content":[{"type":"text","text":"Temporary Plugin dyn-1 was unmounted and removed."}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[60],"surfaceOp":"append"}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":62,"time":0,"data":{"turn":1,"step":5}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":63,"time":0,"data":{"turn":1,"step":6}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":64,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":65,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_HEADLESS_OK"}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":66,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_HEADLESS_OK"}}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":67,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":68,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":69,"time":0,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_HEADLESS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[64,65,66,67,68],"surfaceOp":"append"}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":70,"time":0,"data":{"turn":1,"step":6}}}
+{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":71,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}
 {"type":"result","sessionId":"{{sessionId}}","output":"ADVANCED_HEADLESS_OK","usage":{"inputTokens":18,"outputTokens":18}}

+ 7 - 1
packages/client/ui-workflow-run/src/client/WorkflowRunPanel.module.css

@@ -29,6 +29,7 @@
   height: 16px;
   align-items: center;
   justify-content: center;
+  margin-right: 0;
   color: var(--dsw-alias-label-tertiary);
 }
 
@@ -93,14 +94,19 @@
   height: 16px;
   align-items: center;
   justify-content: center;
+  margin-right: 0;
   color: var(--dsw-alias-label-tertiary);
 }
 
 .phaseTitle {
-  flex: none;
+  overflow: hidden;
+  flex: 0 1 auto;
+  min-width: 0;
+  max-width: 42%;
   color: var(--dsw-alias-label-secondary);
   font-size: 14px;
   line-height: 24px;
+  text-overflow: ellipsis;
   white-space: nowrap;
 }
 

+ 59 - 61
packages/client/ui-workflow-run/src/client/WorkflowRunPanel.tsx

@@ -1,6 +1,6 @@
-import { useMemo, useState, type KeyboardEvent } from 'react'
+import { useMemo, useState } from 'react'
 import {
-  IconChevronDownOutline14, IconChevronRightOutline14, StateDot, type StateDotState,
+  DisclosureRow, IconChevronRightOutline14, StateDot, type StateDotState,
 } from '@deepseek-ai/dsh-client-ui-primitives'
 import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
 import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
@@ -71,12 +71,6 @@ function phaseStatusSummary(members: readonly WorkflowRunMemberData[], t: Workfl
   return visible.map(status => statusCount(status, count(status), t)).join(' · ')
 }
 
-function handleDisclosureKey(event: KeyboardEvent<HTMLDivElement>, onToggle: () => void): void {
-  if (event.key !== 'Enter' && event.key !== ' ') return
-  event.preventDefault()
-  onToggle()
-}
-
 function RunHeader({ count, name, onToggle, open, status, t }: {
   readonly count: number
   readonly name: string
@@ -86,27 +80,29 @@ function RunHeader({ count, name, onToggle, open, status, t }: {
   readonly t: WorkflowRunPanelProps['t']
 }) {
   return (
-    <div
-      className={css.runHeader}
-      data-run-header
-      data-status={status}
-      role="button"
-      tabIndex={0}
-      aria-expanded={open}
-      onClick={onToggle}
-      onKeyDown={(event) => { handleDisclosureKey(event, onToggle) }}
-    >
-      <span className={css.runLeading}>
-        {open ? <IconChevronDownOutline14 /> : <IconChevronRightOutline14 />}
-      </span>
-      <span className={css.runTitle}>{t('run.title', { name })}</span>
-      <span className={css.separator} aria-hidden />
-      <span className={css.runSummary}>{t('run.members', { count })}</span>
-      <span className={css.statusTail} data-run-status-tail data-status={status}>
-        <StateDot state={dotState(status)} />
-        <span>{t(STATUS_KEYS[status])}</span>
-      </span>
-    </div>
+    <DisclosureRow
+      icon={<IconChevronRightOutline14 />}
+      title={t('run.title', { name })}
+      open={open}
+      expandable
+      onToggle={onToggle}
+      expandOnRowClick
+      previewChevron={false}
+      keepContentWhenOpen
+      rowClassName={css.runHeader}
+      leadingClassName={css.runLeading}
+      titleClassName={css.runTitle}
+      collapsedContent={(
+        <>
+          <span className={css.separator} aria-hidden />
+          <span className={css.runSummary}>{t('run.members', { count })}</span>
+          <span className={css.statusTail} data-status={status}>
+            <StateDot state={dotState(status)} />
+            <span>{t(STATUS_KEYS[status])}</span>
+          </span>
+        </>
+      )}
+    />
   )
 }
 
@@ -149,38 +145,39 @@ function PhaseSection({ phase, navigable, openSession, t }: {
   const [open, setOpen] = useState(false)
   const toggle = (): void => { setOpen(value => !value) }
   return (
-    <div className={css.phase} data-phase-key={phase.key} data-phase-status={phase.status}>
-      <div
-        className={css.phaseHeader}
-        data-phase-header
-        role="button"
-        tabIndex={0}
-        aria-expanded={open}
-        onClick={toggle}
-        onKeyDown={(event) => { handleDisclosureKey(event, toggle) }}
-      >
-        <span className={css.phaseLeading}>
-          {open ? <IconChevronDownOutline14 /> : <IconChevronRightOutline14 />}
-        </span>
-        <span className={css.phaseTitle}>{readablePhase(phase.phase, t)}</span>
-        <span className={css.separator} aria-hidden />
-        <span className={css.phaseCount} data-phase-count>{t('run.members', { count: phase.members.length })}</span>
-        <span className={css.phaseStatus} data-phase-status-text>{phaseStatusSummary(phase.members, t)}</span>
-      </div>
-      {open && (
-        <div className={css.members}>
-          {phase.members.map(member => (
-            <MemberRow
-              key={member.seq}
-              member={member}
-              navigable={navigable.has(member.childId)}
-              openSession={openSession}
-              t={t}
-            />
-          ))}
-        </div>
+    <DisclosureRow
+      icon={<IconChevronRightOutline14 />}
+      title={readablePhase(phase.phase, t)}
+      open={open}
+      expandable
+      onToggle={toggle}
+      expandOnRowClick
+      previewChevron={false}
+      keepContentWhenOpen
+      className={css.phase}
+      rowClassName={css.phaseHeader}
+      leadingClassName={css.phaseLeading}
+      titleClassName={css.phaseTitle}
+      collapsedContent={(
+        <>
+          <span className={css.separator} aria-hidden />
+          <span className={css.phaseCount} data-phase-count>{t('run.members', { count: phase.members.length })}</span>
+          <span className={css.phaseStatus} data-phase-status-text>{phaseStatusSummary(phase.members, t)}</span>
+        </>
       )}
-    </div>
+    >
+      <div className={css.members}>
+        {phase.members.map(member => (
+          <MemberRow
+            key={member.seq}
+            member={member}
+            navigable={navigable.has(member.childId)}
+            openSession={openSession}
+            t={t}
+          />
+        ))}
+      </div>
+    </DisclosureRow>
   )
 }
 
@@ -188,6 +185,7 @@ function PhaseSection({ phase, navigable, openSession, t }: {
 export function WorkflowRunPanel({ node, sessionId, useSessions, openSession, t }: WorkflowRunPanelProps) {
   const [open, setOpen] = useState(() => node.data.status === 'running')
   const sessions = useSessions(value => value)
+  const memberCount = node.data.phases.reduce((count, phase) => count + phase.members.length, 0)
   const navigable = useMemo(() => {
     const ordinary = new Set(sessions.ids)
     const result = new Set<SessionId>()
@@ -208,7 +206,7 @@ export function WorkflowRunPanel({ node, sessionId, useSessions, openSession, t
   return (
     <section className={css.root} data-workflow-run data-run-status={node.data.status}>
       <RunHeader
-        count={node.data.memberCount}
+        count={memberCount}
         name={node.data.name}
         open={open}
         status={node.data.status}

+ 0 - 6
packages/client/ui-workflow-run/src/client/index.ts

@@ -7,12 +7,6 @@ import { WorkflowRunPanel, type WorkflowRunInjected } from './WorkflowRunPanel.t
 import { en, NS, type WorkflowRunKey, zh } from './locales.ts'
 import { workflowRunDefinition } from './workflow-definition.ts'
 
-export type { WorkflowRunInjected, WorkflowRunPanelProps } from './WorkflowRunPanel.tsx'
-export type {
-  WorkflowRunChatData, WorkflowRunMemberData, WorkflowRunPhaseData, WorkflowRunStatus,
-} from './workflow-definition.ts'
-export type { WorkflowRunKey } from './locales.ts'
-
 declare module '@deepseek-ai/dsh-client-ui-slots' {
   interface LocaleNamespaceMap {
     /** Durable workflow-run node copy. */

+ 8 - 14
packages/client/ui-workflow-run/src/client/workflow-definition.ts

@@ -24,7 +24,6 @@ export interface WorkflowRunPhaseData {
   readonly key: string
   /** `null` is the absent field; the empty string remains a distinct identity. */
   readonly phase: string | null
-  readonly status: WorkflowRunStatus
   readonly members: readonly WorkflowRunMemberData[]
 }
 
@@ -32,7 +31,6 @@ export interface WorkflowRunPhaseData {
 export interface WorkflowRunChatData {
   readonly name: string
   readonly status: WorkflowRunStatus
-  readonly memberCount: number
   readonly phases: readonly WorkflowRunPhaseData[]
 }
 
@@ -43,7 +41,7 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
   }
 }
 
-interface WorkflowMemberState extends ToolWorkflowAgentStartData {
+interface WorkflowMemberState extends Omit<ToolWorkflowAgentStartData, 'runId'> {
   readonly outcome?: WorkflowAgentOutcome
 }
 
@@ -90,14 +88,6 @@ function locationClosed(location: ConversationLocation | undefined): boolean {
   return location.kind === 'turn' && location.turn.status === 'closed'
 }
 
-function aggregateStatus(members: readonly WorkflowRunMemberData[]): WorkflowRunStatus {
-  if (members.some(member => member.status === 'running')) return 'running'
-  if (members.some(member => member.status === 'failed')) return 'failed'
-  if (members.some(member => member.status === 'cancelled')) return 'cancelled'
-  if (members.some(member => member.status === 'interrupted')) return 'interrupted'
-  return 'completed'
-}
-
 function projectWorkflow(
   context: ConversationNodeContext<WorkflowState>,
 ): WorkflowRunChatData | undefined {
@@ -126,7 +116,6 @@ function projectWorkflow(
   const projectedPhases = [...phases].map(([key, phase]) => ({
     key,
     phase: phase.phase,
-    status: aggregateStatus(phase.members),
     members: phase.members,
   }))
   return {
@@ -134,13 +123,18 @@ function projectWorkflow(
     status: state.stopReason === undefined
       ? interrupted ? 'interrupted' : 'running'
       : statusFromStopReason(state.stopReason),
-    memberCount: state.members.length,
     phases: projectedPhases,
   }
 }
 
 function updateAgentStart(state: WorkflowState, data: ToolWorkflowAgentStartData): WorkflowState {
-  return { ...state, members: [...state.members, data] }
+  const member: WorkflowMemberState = {
+    seq: data.seq,
+    label: data.label,
+    ...data.phase === undefined ? {} : { phase: data.phase },
+    childId: data.childId,
+  }
+  return { ...state, members: [...state.members, member] }
 }
 
 function updateAgentEnd(state: WorkflowState, data: ToolWorkflowAgentEndData): WorkflowState {

+ 14 - 20
packages/client/ui-workflow-run/tests/workflow-run.spec.tsx

@@ -107,14 +107,13 @@ describe('workflow-run Conversation Definition', () => {
     expect(data).toEqual({
       name: 'audit',
       status: 'failed',
-      memberCount: 2,
       phases: [
         {
-          key: 'value:0:', phase: '', status: 'completed',
+          key: 'value:0:', phase: '',
           members: [{ seq: 1, label: 'first', childId: 'child-1', status: 'completed' }],
         },
         {
-          key: 'missing', phase: null, status: 'failed',
+          key: 'missing', phase: null,
           members: [{ seq: 2, label: 'second', childId: 'child-2', status: 'failed' }],
         },
       ],
@@ -167,7 +166,7 @@ describe('workflow-run Conversation Definition', () => {
       at(4, 'tool-workflow/run-end', { runId: 'empty', stopReason: 'completed' }),
     ])
     expect(workflowData(value)).toEqual({
-      name: 'empty', status: 'completed', memberCount: 0, phases: [],
+      name: 'empty', status: 'completed', phases: [],
     })
   })
 
@@ -187,7 +186,7 @@ describe('workflow-run Conversation Definition', () => {
     ])
     expect(workflowData(cancelled)).toMatchObject({
       status: 'cancelled',
-      phases: [{ phase: 'Research', status: 'cancelled', members: [{ status: 'cancelled' }, { status: 'completed' }] }],
+      phases: [{ phase: 'Research', members: [{ status: 'cancelled' }, { status: 'completed' }] }],
     })
 
     const interruptedTurn = assembler([
@@ -254,7 +253,6 @@ function node(data: WorkflowRunChatData): WorkflowRunPanelProps['node'] {
 const phase = (overrides: Partial<WorkflowRunChatData['phases'][number]> = {}): WorkflowRunChatData['phases'][number] => ({
   key: 'missing',
   phase: null,
-  status: 'running',
   members: [{ seq: 1, label: 'worker', childId: 'child-1' as SessionId, status: 'running' }],
   ...overrides,
 })
@@ -303,7 +301,7 @@ function panelProps(data: WorkflowRunChatData, sessions = listState(), openSessi
 describe('WorkflowRunPanel', () => {
   it('defaults running runs open, terminal history closed, and keeps the current choice across data updates', () => {
     const running: WorkflowRunChatData = {
-      name: 'audit', status: 'running', memberCount: 1, phases: [phase()],
+      name: 'audit', status: 'running', phases: [phase()],
     }
     const view = render(<WorkflowRunPanel {...panelProps(running)} />)
     expect(screen.getByText('未分阶段')).toBeTruthy()
@@ -321,7 +319,7 @@ describe('WorkflowRunPanel', () => {
 
   it('supports root keyboard disclosure and renders a zero-member running state', () => {
     render(<WorkflowRunPanel {...panelProps({
-      name: 'keyboard', status: 'running', memberCount: 1,
+      name: 'keyboard', status: 'running',
       phases: [phase({ key: 'research', phase: 'Research' })],
     })} />)
     const header = screen.getByRole('button', { name: /^keyboard/ })
@@ -344,14 +342,14 @@ describe('WorkflowRunPanel', () => {
 
     cleanup()
     render(<WorkflowRunPanel {...panelProps({
-      name: 'empty', status: 'running', memberCount: 0, phases: [],
+      name: 'empty', status: 'running', phases: [],
     })} />)
     expect(screen.getByText('没有启动成员')).toBeTruthy()
   })
 
   it('keeps phase disclosure independent and preserves empty versus absent names', () => {
     render(<WorkflowRunPanel {...panelProps({
-      name: 'audit', status: 'running', memberCount: 2,
+      name: 'audit', status: 'running',
       phases: [
         phase({ key: 'value:0:', phase: '', members: [{
           seq: 1, label: '', childId: 'child-1' as SessionId, status: 'running',
@@ -373,9 +371,8 @@ describe('WorkflowRunPanel', () => {
 
   it('covers the Figma completed, failed/cancelled, and interrupted state boards', () => {
     const completed: WorkflowRunChatData = {
-      name: 'repo-audit', status: 'completed', memberCount: 1,
+      name: 'repo-audit', status: 'completed',
       phases: [phase({
-        status: 'completed',
         members: [{ seq: 1, label: 'done', childId: 'child-1' as SessionId, status: 'completed' }],
       })],
     }
@@ -387,9 +384,8 @@ describe('WorkflowRunPanel', () => {
     completedView.unmount()
 
     const mixed: WorkflowRunChatData = {
-      name: 'repo-audit', status: 'failed', memberCount: 2,
+      name: 'repo-audit', status: 'failed',
       phases: [phase({
-        status: 'failed',
         members: [
           { seq: 1, label: 'failed', childId: 'child-1' as SessionId, status: 'failed' },
           { seq: 2, label: 'cancelled', childId: 'child-2' as SessionId, status: 'cancelled' },
@@ -407,17 +403,16 @@ describe('WorkflowRunPanel', () => {
     mixedView.unmount()
 
     const interrupted: WorkflowRunChatData = {
-      name: 'repo-audit', status: 'interrupted', memberCount: 2,
+      name: 'repo-audit', status: 'interrupted',
       phases: [
         phase({
-          status: 'interrupted',
           members: [
             { seq: 1, label: 'done', childId: 'child-1' as SessionId, status: 'completed' },
             { seq: 2, label: 'interrupted', childId: 'child-2' as SessionId, status: 'interrupted' },
           ],
         }),
         phase({
-          key: 'interrupted-only', phase: 'Interrupted only', status: 'interrupted',
+          key: 'interrupted-only', phase: 'Interrupted only',
           members: [{
             seq: 3, label: 'interrupted', childId: 'child-3' as SessionId, status: 'interrupted',
           }],
@@ -433,7 +428,7 @@ describe('WorkflowRunPanel', () => {
 
   it('opens only a running ordinary-list subagent proven to have this parent', () => {
     const data: WorkflowRunChatData = {
-      name: 'audit', status: 'running', memberCount: 1, phases: [phase()],
+      name: 'audit', status: 'running', phases: [phase()],
     }
     const openSession = vi.fn()
     render(<WorkflowRunPanel {...panelProps(data, listState(), openSession)} />)
@@ -459,9 +454,8 @@ describe('WorkflowRunPanel', () => {
     ['member terminal', listState(), 'completed'],
   ] as const)('does not navigate when %s', (_name, sessions, memberStatus) => {
     const data: WorkflowRunChatData = {
-      name: 'audit', status: 'running', memberCount: 1,
+      name: 'audit', status: 'running',
       phases: [phase({
-        status: memberStatus === 'running' ? 'running' : 'completed',
         members: [{
           seq: 1, label: 'worker', childId: 'child-1' as SessionId, status: memberStatus,
         }],

+ 57 - 87
packages/workflow/tool-workflow/src/index.ts

@@ -17,8 +17,7 @@ import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
 import type { ContentBlock } from '@deepseek-ai/dsh-llm'
 import type { JsonValue, Session, SessionEventMap } from '@deepseek-ai/dsh-session'
 import type {
-  WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowResult, WorkflowRun,
-  WorkflowRunId, WorkflowRunInfo, WorkflowStopReason,
+  WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason,
 } from '@deepseek-ai/dsh-workflow'
 import type {
   ToolWorkflowAgentEndData, ToolWorkflowAgentStartData,
@@ -45,14 +44,10 @@ export const Config: z<Config> = z.object({
 
 type ResolvedConfig = Required<Config>
 
-type BufferedWorkflowEvent =
-  | { readonly kind: 'agent-start'; readonly info: WorkflowRunInfo; readonly agent: WorkflowAgentInfo }
-  | { readonly kind: 'agent-end'; readonly info: WorkflowRunInfo; readonly agent: WorkflowAgentEndInfo }
-
 interface WorkflowRecorder {
-  bind(run: WorkflowRun): void
-  finish(stopReason: WorkflowStopReason): void
-  dispose(): void
+  start(session: Session, run: WorkflowRun): void
+  finish(runId: WorkflowRunId, stopReason: WorkflowStopReason): void
+  abandon(runId: WorkflowRunId): void
 }
 
 interface ToolWorkflowRecordEventMap {
@@ -72,84 +67,66 @@ function renderRecordingError(error: unknown): string {
 }
 
 /**
- * Project one top-level workflow run into its parent Session without letting
- * recording failure affect tool execution. Listeners are installed before
- * `start()` so even a synchronous provider cannot outrun the recorder.
+ * Project active top-level workflow runs into their parent Sessions without
+ * letting recording failure affect tool execution.
  */
-function createWorkflowRecorder(ctx: Context, session: Session): WorkflowRecorder {
-  let runId: WorkflowRunId | undefined
-  let enabled = true
-  const buffered: BufferedWorkflowEvent[] = []
-  // These four package-owned events are all log-only. Narrowing the generic
-  // append face here lets TypeScript discharge Session.append's conditional
-  // surface-options tuple once for the complete closed event set.
-  const appendRecord = session.append.bind(session) as <Type extends keyof ToolWorkflowRecordEventMap>(
-    type: Type,
-    data: SessionEventMap[Type],
-  ) => void
-
+function createWorkflowRecorder(ctx: Context): WorkflowRecorder {
+  const active = new Map<WorkflowRunId, Session>()
   const append = <Type extends keyof ToolWorkflowRecordEventMap>(
+    session: Session,
     type: Type,
     data: SessionEventMap[Type],
-  ): void => {
-    if (!enabled) return
+  ): boolean => {
+    // These four package-owned events are all log-only. Narrowing the generic
+    // append face here discharges Session.append's conditional options tuple.
+    const appendRecord = session.append.bind(session) as <Event extends keyof ToolWorkflowRecordEventMap>(
+      event: Event,
+      value: SessionEventMap[Event],
+    ) => void
     try {
       appendRecord(type, data)
+      return true
     } catch (error: unknown) {
-      enabled = false
       ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`)
+      return false
     }
   }
 
-  const record = (event: BufferedWorkflowEvent): void => {
-    if (runId === undefined) {
-      buffered.push(event)
-      return
-    }
-    if (event.info.id !== runId) return
-    if (event.kind === 'agent-start') {
-      const data: ToolWorkflowAgentStartData = {
-        runId,
-        seq: event.agent.seq,
-        label: event.agent.label,
-        ...event.agent.phase === undefined ? {} : { phase: event.agent.phase },
-        childId: event.agent.childId,
-      }
-      append('tool-workflow/agent-start', data)
-      return
+  ctx.on('workflow/agent-start', (info, agent) => {
+    const session = active.get(info.id)
+    if (session === undefined) return
+    const data: ToolWorkflowAgentStartData = {
+      runId: info.id,
+      seq: agent.seq,
+      label: agent.label,
+      ...agent.phase === undefined ? {} : { phase: agent.phase },
+      childId: agent.childId,
     }
+    if (!append(session, 'tool-workflow/agent-start', data)) active.delete(info.id)
+  })
+  ctx.on('workflow/agent-end', (info, agent) => {
+    const session = active.get(info.id)
+    if (session === undefined) return
     const data: ToolWorkflowAgentEndData = {
-      runId,
-      seq: event.agent.seq,
-      outcome: event.agent.outcome,
+      runId: info.id,
+      seq: agent.seq,
+      outcome: agent.outcome,
     }
-    append('tool-workflow/agent-end', data)
-  }
-
-  const disposeStart = ctx.on('workflow/agent-start', (info, agent) => {
-    record({ kind: 'agent-start', info, agent })
-  })
-  const disposeEnd = ctx.on('workflow/agent-end', (info, agent) => {
-    record({ kind: 'agent-end', info, agent })
+    if (!append(session, 'tool-workflow/agent-end', data)) active.delete(info.id)
   })
 
   return {
-    bind(run) {
-      runId = run.id
-      append('tool-workflow/run-start', { runId, name: run.meta.name })
-      for (const event of buffered) record(event)
-      buffered.length = 0
-    },
-    finish(stopReason) {
-      /* v8 ignore next -- execute binds every returned run before result settlement can call finish. */
-      if (runId === undefined) return
-      append('tool-workflow/run-end', { runId, stopReason })
+    start(session, run) {
+      if (append(session, 'tool-workflow/run-start', { runId: run.id, name: run.meta.name })) {
+        active.set(run.id, session)
+      }
     },
-    dispose() {
-      disposeStart()
-      disposeEnd()
-      buffered.length = 0
+    finish(runId, stopReason) {
+      const session = active.get(runId)
+      if (session !== undefined) append(session, 'tool-workflow/run-end', { runId, stopReason })
+      active.delete(runId)
     },
+    abandon: (runId) => { active.delete(runId) },
   }
 }
 
@@ -229,6 +206,7 @@ export function apply(ctx: Context, config: Config): void {
   // schemastery (the exported Config schema) has already filled the defaulted
   // fields; the assertion records that resolution, not a hidden fallback.
   const { toolName, maxResultChars } = config as ResolvedConfig
+  const recorder = createWorkflowRecorder(ctx)
   // Usage policy ships with the tool (the master convention: tool guidance
   // lives in tool plugins as prompt sections, not in the deployment persona).
   ctx.systemPrompt.section({
@@ -303,23 +281,15 @@ export function apply(ctx: Context, config: Config): void {
       // Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
       // synchronously here and become isError results via the registry — the
       // model sees the violation list and can correct the call.
-      const recorder = exec.parent === undefined
-        ? createWorkflowRecorder(ctx, parent.session)
-        : undefined
-      let run: WorkflowRun
-      try {
-        run = ctx.workflows.start({
-          script: args.script,
-          meta: args.meta,
-          ...args.args !== undefined ? { args: args.args } : {},
-          parent,
-          signal: exec.signal,
-        })
-      } catch (error: unknown) {
-        recorder?.dispose()
-        throw error
-      }
-      recorder?.bind(run)
+      const run = ctx.workflows.start({
+        script: args.script,
+        meta: args.meta,
+        ...args.args !== undefined ? { args: args.args } : {},
+        parent,
+        signal: exec.signal,
+      })
+      const recordsRun = exec.parent === undefined
+      if (recordsRun) recorder.start(parent.session, run)
 
       // Bridge the tool's abort signal to the run: if the parent step is aborted while the
       // script is in flight, cancel the whole run. The signal also enters the engine directly, but
@@ -348,9 +318,9 @@ export function apply(ctx: Context, config: Config): void {
           // synthesize cancelled member endings while reaching quiescence.
           await run.dispose()
           /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
-          if (result !== undefined) recorder?.finish(result.stopReason)
+          if (recordsRun && result !== undefined) recorder.finish(run.id, result.stopReason)
         } finally {
-          recorder?.dispose()
+          if (recordsRun) recorder.abandon(run.id)
         }
       }
     },

+ 27 - 13
packages/workflow/tool-workflow/src/invariant.ts

@@ -19,12 +19,9 @@ interface RunTrace {
 
 type WorkflowTrace = Map<string, RunTrace>
 
-/** Clone the independent fold before validating one candidate append. */
-function cloneTrace(source: WorkflowTrace): WorkflowTrace {
-  return new Map([...source].map(([runId, run]) => [runId, {
-    ended: run.ended,
-    members: new Map(run.members),
-  }]))
+/** Whether this package owns the candidate Session event. */
+function isWorkflowRecordEvent(event: SessionEvent): boolean {
+  return event.type.startsWith('tool-workflow/')
 }
 
 /** Require a durable opaque identity to be a non-empty string. */
@@ -50,6 +47,23 @@ function recordOf(event: SessionEvent, fail: InvariantFailure): Record<string, u
   return data as Record<string, unknown>
 }
 
+/** Copy only the run one candidate can mutate; other committed states stay shared. */
+function cloneTraceForEvent(
+  source: WorkflowTrace,
+  event: SessionEvent,
+  fail: InvariantFailure,
+): WorkflowTrace {
+  const trace = new Map(source)
+  if (event.type === 'tool-workflow/run-start') return trace
+  const data = recordOf(event, fail)
+  const runId = stringId(data.runId, `${event.type} runId`, fail)
+  const run = source.get(runId)
+  if (run !== undefined) {
+    trace.set(runId, { ended: run.ended, members: new Map(run.members) })
+  }
+  return trace
+}
+
 /** Require the named run to exist and remain open. */
 function openRun(trace: WorkflowTrace, runId: string, eventType: string, fail: InvariantFailure): RunTrace {
   const run = trace.get(runId)
@@ -60,7 +74,6 @@ function openRun(trace: WorkflowTrace, runId: string, eventType: string, fail: I
 
 /** Advance the workflow-record fold with one relevant Session event. */
 function applyEvent(trace: WorkflowTrace, event: SessionEvent, fail: InvariantFailure): void {
-  if (!event.type.startsWith('tool-workflow/')) return
   const data = recordOf(event, fail)
   const runId = stringId(data.runId, `${event.type} runId`, fail)
 
@@ -107,6 +120,7 @@ function applyEvent(trace: WorkflowTrace, event: SessionEvent, fail: InvariantFa
         fail(`tool-workflow/run-end leaves member seq ${openMembers.join(', ')} open in run ${runId}`)
       }
       run.ended = true
+      run.members.clear()
       return
     }
     default:
@@ -126,23 +140,23 @@ const install: InvariantInstaller = Object.assign((ctx: Context, fail: Invariant
 
   const seed = (session: Session): WorkflowTrace => {
     const trace: WorkflowTrace = new Map()
-    for (const event of session.events) applyChecked(trace, event, fail)
+    for (const event of session.events.filter(isWorkflowRecordEvent)) applyChecked(trace, event, fail)
     traces.set(session, trace)
     return trace
   }
-  /* v8 ignore next -- session/event always follows list() or session/created seeding. */
-  const traceFor = (session: Session): WorkflowTrace => traces.get(session) ?? seed(session)
-
-  for (const session of ctx.sessions.list()) seed(session)
+  ctx.sessions.list().forEach(seed)
   ctx.on('session/created', (session) => { seed(session) }, { global: true })
   ctx.on('internal/dispatch', (_mode, eventName, args) => {
     if (eventName !== 'session/event') return
     const [session, event] = args as [Session, SessionEvent]
-    const trace = cloneTrace(traceFor(session))
+    if (!isWorkflowRecordEvent(event)) return
+    // session/event dispatch follows list() or session/created seeding.
+    const trace = cloneTraceForEvent(traces.get(session) as WorkflowTrace, event, fail)
     applyChecked(trace, event, fail)
     staged.set(event, { session, trace })
   }, { global: true })
   ctx.on('session/event', (session, event) => {
+    if (!isWorkflowRecordEvent(event)) return
     const candidate = staged.get(event)
     /* v8 ignore next 2 -- internal/dispatch stages the exact session/event callback arguments. */
     if (candidate === undefined || candidate.session !== session) {

+ 0 - 24
packages/workflow/tool-workflow/tests/tool-workflow.spec.ts

@@ -27,7 +27,6 @@ class StubEngine extends WorkflowService {
   settle!: (result: WorkflowResult) => void
   readonly settlements = new Map<WorkflowRunIdType, (result: WorkflowResult) => void>()
   startError: Error | undefined
-  emitMemberDuringStart = false
 
   start(request: WorkflowStartRequest): WorkflowRun {
     if (this.startError) throw this.startError
@@ -35,12 +34,6 @@ class StubEngine extends WorkflowService {
     const id = WorkflowRunId(`run-${this.requests.length}`)
     const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
     this.settlements.set(id, this.settle)
-    if (this.emitMemberDuringStart) {
-      const info = { id, meta: request.meta }
-      const member = { seq: 1, label: 'synchronous', childId: SessionId('sync-child') }
-      this.emitWorkflowEvent('workflow/agent-start', info, member)
-      this.emitWorkflowEvent('workflow/agent-end', info, { ...member, outcome: 'completed' })
-    }
     request.signal?.addEventListener('abort', () => {
       this.settle({ value: null, stopReason: 'cancelled', error: 'signal', agentsStarted: 0 })
     }, { once: true })
@@ -205,23 +198,6 @@ describe('dsh-tool-workflow', () => {
       ])
   })
 
-  it('buffers synchronous member events until start returns the run identity', async () => {
-    const { ctx, engine, parent, session } = await setup()
-    engine.emitMemberDuringStart = true
-    const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
-    await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
-    engine.settleRun(WorkflowRunId('run-1'), {
-      value: null, stopReason: 'completed', agentsStarted: 1,
-    })
-    expect((await pending).isError).toBe(false)
-    expect(session.events.map(event => event.type)).toEqual([
-      'tool-workflow/run-start',
-      'tool-workflow/agent-start',
-      'tool-workflow/agent-end',
-      'tool-workflow/run-end',
-    ])
-  })
-
   it('does not record nested transport executions', async () => {
     const { ctx, engine, parent, session } = await setup()
     const pending = execute(ctx, { script: SCRIPT, meta: META }, {

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików