@tea-agent/loop-agent 0.52.0-next.1 → 0.52.0-next.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +99 -21
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/cli/command-definitions.js +1 -75
  4. package/dist/cli/help.js +1 -1
  5. package/dist/cli/program.js +1 -28
  6. package/dist/commands/init-accepted-merge.js +46 -0
  7. package/dist/commands/init-upgrade.js +115 -2
  8. package/dist/commands/init.js +79 -12
  9. package/dist/executors/pi-sdk-executor.js +3 -3
  10. package/dist/governance/path-guard.js +2 -0
  11. package/dist/records/harvest.js +1 -1
  12. package/dist/shared/git-progress.js +3 -0
  13. package/dist/shared/operator/capabilities.js +0 -122
  14. package/dist/shared/pi-context-pressure/checkpoint.js +94 -24
  15. package/dist/shared/pi-context-pressure/compaction-policy.js +152 -66
  16. package/dist/shared/pi-context-pressure/extension.js +32 -8
  17. package/dist/shared/pi-context-pressure/index.js +1 -1
  18. package/dist/shared/pi-context-pressure/telemetry.js +15 -0
  19. package/dist/shared/update/npm-client.js +14 -3
  20. package/dist/task/config-types.js +5 -10
  21. package/dist/task/delegate.js +1 -1
  22. package/dist/task/read-model.js +0 -4
  23. package/dist/task/runtime.js +0 -1
  24. package/dist/task/worktree.js +1 -1
  25. package/dist/worker/console/chat/api-workbench-core.js +17 -6
  26. package/dist/worker/console/chat/api-workbench.js +2 -0
  27. package/dist/worker/console/chat/assistant-content.js +21 -3
  28. package/dist/worker/console/chat/chat-event-projection.js +6 -0
  29. package/dist/worker/console/chat/chat-event-store.js +32 -2
  30. package/dist/worker/console/chat/chat-references.js +4 -0
  31. package/dist/worker/console/chat/compaction-errors.js +14 -2
  32. package/dist/worker/console/chat/context-insights.js +41 -4
  33. package/dist/worker/console/chat/context-usage.js +4 -1
  34. package/dist/worker/console/chat/pi-runtime/custom-tools/apiworkbench-tools.js +65 -3
  35. package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +2 -2
  36. package/dist/worker/console/chat/pi-runtime/extension-bindings.js +39 -0
  37. package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +4 -0
  38. package/dist/worker/console/chat/pi-runtime.js +389 -191
  39. package/dist/worker/console/chat/repo-browser.js +5 -2
  40. package/dist/worker/console/chat/repo-preview-kind.js +16 -6
  41. package/dist/worker/console/chat/routes.js +299 -25
  42. package/dist/worker/console/chat/scheduled-goal-request.js +1 -1
  43. package/dist/worker/console/chat/subagents/jobs.js +115 -4
  44. package/dist/worker/console/chat/terminal-sessions.js +52 -6
  45. package/dist/worker/console/chat/tool-exposure-catalog.js +1 -1
  46. package/dist/worker/console/chat/tool-presentation.js +17 -10
  47. package/dist/worker/console/chat/tool-preview.js +22 -0
  48. package/dist/worker/console/chat/turn-process.js +49 -0
  49. package/dist/worker/console/chat/vcp-prompt.js +14 -9
  50. package/dist/worker/console/chat/workspace-changes.js +17 -0
  51. package/dist/worker/console/console-update-runtime.js +5 -1
  52. package/dist/worker/console/operator-actions.js +7 -6
  53. package/dist/worker/console/operator-user-error.js +5 -1
  54. package/dist/worker/console/pi-compaction-settings.js +220 -0
  55. package/dist/worker/console/routes.js +1 -1
  56. package/dist/worker/console/server.js +148 -6
  57. package/dist/worker/console/static/assets/FilePreviewDocx-ybM3ZqSl.js +9 -0
  58. package/dist/worker/console/static/assets/abnfDiagram-N423BO3Z-CT26sIgH.js +1 -0
  59. package/dist/worker/console/static/assets/{arc-Bkf_oc0_.js → arc-CPwLqDB0.js} +1 -1
  60. package/dist/worker/console/static/assets/architectureDiagram-T3A2C74G-CzTSMPU_.js +36 -0
  61. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-D62uVvbI.js → blockDiagram-VBNYF7ZC-BfgbtJLH.js} +1 -1
  62. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-Iq0Y8Afx.js → c4Diagram-5PPSVZJV-B9pTjB8U.js} +1 -1
  63. package/dist/worker/console/static/assets/channel-DtYRMDck.js +1 -0
  64. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-D1TxRE3k.js → chunk-2GRJ4B5K-xORV8QsC.js} +1 -1
  65. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BE-DHkAO.js → chunk-2Q5K7J3B-BzpYWAHK.js} +1 -1
  66. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-t0iYO8Cc.js → chunk-5RXB4S5H-D8zcRP6c.js} +1 -1
  67. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-Clo2nExi.js → chunk-5VM5RSS4-DVEXxzQJ.js} +1 -1
  68. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-C7bSpo-3.js → chunk-6Q2QTUOP-CKZOJU2z.js} +1 -1
  69. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DorZaymh.js → chunk-GF5L2VYU-Cgx34Dj8.js} +1 -1
  70. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-Ch_4HvyJ.js → chunk-JWPE2WC7-ehcSKOcx.js} +1 -1
  71. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-yaSoFe-3.js → chunk-KBJHAD2P-CiY9emCG.js} +1 -1
  72. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-QpjaXecS.js → chunk-RYQCIY6F-Bk9X-ksQ.js} +1 -1
  73. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-B3t6cycg.js → chunk-XXDRQBXY-DC0xXfHy.js} +1 -1
  74. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DyesHbs5.js +1 -0
  75. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DyesHbs5.js +1 -0
  76. package/dist/worker/console/static/assets/cose-bilkent-JH36ORCC-C_EVg5l9.js +1 -0
  77. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-CP8LtrOl.js → cynefin-VYW2F7L2-BIFL8KrA.js} +1 -1
  78. package/dist/worker/console/static/assets/cynefinDiagram-MW4NZA55-DjtUYOlE.js +62 -0
  79. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BK0ua9V8.js → dagre-VZM6K2ZE-D2aN2V9t.js} +1 -1
  80. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-t9-HP13j.js → diagram-7IWD3JNH-D_twhmFi.js} +1 -1
  81. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-L5Sg9jMD.js → diagram-B4RE2ZJO-ChzncqLV.js} +1 -1
  82. package/dist/worker/console/static/assets/diagram-LBJQPF4R-B6LO-bF2.js +24 -0
  83. package/dist/worker/console/static/assets/diagram-Q27KOJAE-GrzM7AFc.js +24 -0
  84. package/dist/worker/console/static/assets/diagram-UB23O5K3-Bv-lntaq.js +41 -0
  85. package/dist/worker/console/static/assets/docx-preview-CAbT0VNs.js +23 -0
  86. package/dist/worker/console/static/assets/docxPreview-D_T4B7qe.js +1 -0
  87. package/dist/worker/console/static/assets/ebnfDiagram-BXEA7PRR-BvD2jkO_.js +1 -0
  88. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CNOuj3BO.js → erDiagram-JOGREHBK-BirPCcmA.js} +1 -1
  89. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-h_Cyayai.js → flowDiagram-UKHOOZJN-Chu1YnGQ.js} +1 -1
  90. package/dist/worker/console/static/assets/ganttDiagram-PKOTCBZU-Djn17xhB.js +292 -0
  91. package/dist/worker/console/static/assets/gitGraphDiagram-DS77QQ5N-Bx1qbGHx.js +106 -0
  92. package/dist/worker/console/static/assets/infoDiagram-6WML65LV-D-TLMqmb.js +2 -0
  93. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-DAdf5lHp.js → ishikawaDiagram-WSZJBQD7-DbJoh-6T.js} +1 -1
  94. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BQbGtg66.js → journeyDiagram-NVQOT4AX-DsyokZ6e.js} +1 -1
  95. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CetLubYc.js → kanban-definition-27J2QSJJ-DlzXTxic.js} +1 -1
  96. package/dist/worker/console/static/assets/{linear-DLZOjaVz.js → linear-ClnZn3vw.js} +1 -1
  97. package/dist/worker/console/static/assets/main-D-ZQ4gLb.css +1 -0
  98. package/dist/worker/console/static/assets/main-fc3P1HID.js +645 -0
  99. package/dist/worker/console/static/assets/{mermaid.core-B_xZl_gM.js → mermaid.core-DqSlcvbf.js} +5 -5
  100. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-Dzo3dzp0.js → mindmap-definition-FAOFIHXS-CSFbzpiX.js} +1 -1
  101. package/dist/worker/console/static/assets/pegDiagram-VL7TDLO6-DK80yQqe.js +1 -0
  102. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-Cp3YrVzQ.js → pieDiagram-7S7Q4E2Y-DWX7SFGb.js} +1 -1
  103. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-4tI5mUgW.js → quadrantDiagram-CIZ2JOQS-BEPPhtXs.js} +1 -1
  104. package/dist/worker/console/static/assets/railroadDiagram-AXF67PYL-Ck_s6fQn.js +1 -0
  105. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DY-0JqdT.js → requirementDiagram-LRYGKXZP-CYig27Rj.js} +1 -1
  106. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-DuJIzRKC.js → sankeyDiagram-W5VNT64P-u-0aSx5s.js} +1 -1
  107. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BTbVJ85l.js → sequenceDiagram-SI44F4Z6-NsEJI9sM.js} +1 -1
  108. package/dist/worker/console/static/assets/{sheet-workbook-BPPh1uLw.js → sheet-workbook-kZ_HK4Sg.js} +2 -2
  109. package/dist/worker/console/static/assets/sizeCapture-X5ZJPWSS-8vneVM5U.js +1 -0
  110. package/dist/worker/console/static/assets/stateDiagram-OKZ733FA-CMIobUBh.js +1 -0
  111. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Bd0pHHKP.js +1 -0
  112. package/dist/worker/console/static/assets/swimlanes-SLNWSIFB-D4Qzt6ug.js +2 -0
  113. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BzmSZnl_.js +8 -0
  114. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-GR6lxokn.js → timeline-definition-Z64GVDOM-DMb1LpED.js} +1 -1
  115. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DEkwyzsF.js → vennDiagram-T6HMQDX7-C_9eFOs3.js} +1 -1
  116. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-W5jnvEJ3.js → wardleyDiagram-T6FBY63Y-DJYMe3uT.js} +1 -1
  117. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-cqsloioo.js → xychartDiagram-ELKLHX3M-Cv_1Mi3u.js} +1 -1
  118. package/dist/worker/console/static/docx-preview.html +25 -0
  119. package/dist/worker/console/static/index.html +3 -2
  120. package/dist/worker/console/static/vcp/fonts/README.md +28 -0
  121. package/dist/worker/console/static/vcp/vendor/vcp-engine-v1.js +4 -4
  122. package/dist/worker/console/static-src/operator-chat/StateDot.js +17 -0
  123. package/dist/worker/console/static-src/operator-chat/changed-file-diff.js +15 -0
  124. package/dist/worker/console/static-src/operator-chat/chat-font-size.js +90 -0
  125. package/dist/worker/console/static-src/operator-chat/chat-session-order.js +96 -0
  126. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +8 -1
  127. package/dist/worker/console/static-src/operator-chat/compaction-message.js +4 -0
  128. package/dist/worker/console/static-src/operator-chat/details-rail-surfaces.js +2 -0
  129. package/dist/worker/console/static-src/operator-chat/file-touch.js +107 -0
  130. package/dist/worker/console/static-src/operator-chat/format-file-size.js +26 -0
  131. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +44 -0
  132. package/dist/worker/console/static-src/operator-chat/reference-display.js +7 -1
  133. package/dist/worker/console/static-src/operator-chat/tasks-auto-open.js +100 -0
  134. package/dist/worker/console/static-src/operator-chat/tasks-layout-tween.js +103 -0
  135. package/dist/worker/console/static-src/operator-chat/tasks-model.js +657 -0
  136. package/dist/worker/console/static-src/operator-chat/tasks-view-glide.js +96 -0
  137. package/dist/worker/console/static-src/operator-chat/turn-group-equality.js +1 -0
  138. package/dist/worker/console/static-src/operator-chat/use-auto-animate.js +61 -0
  139. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +194 -47
  140. package/dist/worker/console/static-src/operator-chat/useChatStream.js +4 -0
  141. package/dist/worker/console/static-src/operator-chat/useChatThread.js +18 -0
  142. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +111 -21
  143. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +91 -47
  144. package/dist/worker/console/static-src/operator-chat/useVcpPreferences.js +1 -1
  145. package/dist/worker/console/static-src/operator-chat/user-turn-anchors-merge.js +50 -0
  146. package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +180 -22
  147. package/dist/worker/console/static-src/operator-chat/vcp-frame.js +3 -3
  148. package/dist/worker/console/static-src/shell/console-update-progress.js +16 -0
  149. package/dist/worker/console/static-src/shell/console-update-reload.js +4 -1
  150. package/dist/worker/console/static-src/shell/workspace-route.js +0 -2
  151. package/dist/worker/console/vite.config.js +5 -1
  152. package/dist/worker/console/workspace-registry.js +62 -19
  153. package/dist/worker/observe/static/operator-chrome.js +0 -1
  154. package/dist/worker/scheduler/git-base.js +3 -0
  155. package/dist/worker/scheduler/night-git-finalizer.js +1 -1
  156. package/dist/worker/scheduler/night-harvest.js +1 -1
  157. package/dist/worker/scheduler/prepared-attempt-recovery.js +1 -1
  158. package/dist/worker/scheduler/scheduled-goal-evidence.js +1 -1
  159. package/dist/workflows/dag/backend-test-scenario-param.js +60 -4
  160. package/dist/workflows/dag/dynamic-runtime/reduction.js +7 -2
  161. package/dist/workflows/dag/frontend-test-framework-adapters.js +11 -2
  162. package/dist/workflows/script/windows/guest.js +13 -2
  163. package/dist/workflows/script/windows/native.js +21 -3
  164. package/docs/architecture/dag-execution.md +2 -13
  165. package/docs/architecture/facts-and-state.md +2 -3
  166. package/docs/architecture/runtime-boundaries.md +2 -2
  167. package/package.json +9 -7
  168. package/resource-catalog.v1.json +6 -6
  169. package/scripts/patch-pi-sdk-windows-hide.mjs +3 -3
  170. package/skills/loop-agent/references/command-reference.md +2 -41
  171. package/skills/loop-agent/references/harness-policy.md +3 -30
  172. package/skills/loop-agent/references/long-running-loop.md +6 -54
  173. package/dist/application/loop/run-action.js +0 -19
  174. package/dist/commands/dag-workflow-compile.js +0 -93
  175. package/dist/commands/dag-workflow-plan.js +0 -132
  176. package/dist/commands/dag-workflow-validate.js +0 -68
  177. package/dist/commands/loop-benchmark.js +0 -74
  178. package/dist/commands/loop.js +0 -251
  179. package/dist/commands/workflow.js +0 -259
  180. package/dist/infrastructure/harness/loop-store.js +0 -41
  181. package/dist/worker/console/static/assets/abnfDiagram-N423BO3Z-FQePHM07.js +0 -1
  182. package/dist/worker/console/static/assets/architectureDiagram-T3A2C74G-p_mwm8cd.js +0 -36
  183. package/dist/worker/console/static/assets/channel-CIBAg8WF.js +0 -1
  184. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-B4xQrSmv.js +0 -1
  185. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-B4xQrSmv.js +0 -1
  186. package/dist/worker/console/static/assets/cose-bilkent-JH36ORCC-BPXf8ZYr.js +0 -1
  187. package/dist/worker/console/static/assets/cynefinDiagram-MW4NZA55-CNsL9N2-.js +0 -62
  188. package/dist/worker/console/static/assets/diagram-LBJQPF4R-BipWFRgs.js +0 -24
  189. package/dist/worker/console/static/assets/diagram-Q27KOJAE-T2p4xa38.js +0 -24
  190. package/dist/worker/console/static/assets/diagram-UB23O5K3-CVwz6LVu.js +0 -41
  191. package/dist/worker/console/static/assets/ebnfDiagram-BXEA7PRR-CybQrGSA.js +0 -1
  192. package/dist/worker/console/static/assets/ganttDiagram-PKOTCBZU-D411_55h.js +0 -292
  193. package/dist/worker/console/static/assets/gitGraphDiagram-DS77QQ5N-DpVtzs9z.js +0 -106
  194. package/dist/worker/console/static/assets/index-B7cwOTL9.js +0 -649
  195. package/dist/worker/console/static/assets/index-CATbSkPc.css +0 -1
  196. package/dist/worker/console/static/assets/infoDiagram-6WML65LV-D74Uvx6K.js +0 -2
  197. package/dist/worker/console/static/assets/pegDiagram-VL7TDLO6-CSwoBOpM.js +0 -1
  198. package/dist/worker/console/static/assets/railroadDiagram-AXF67PYL-n0Mt3Yia.js +0 -1
  199. package/dist/worker/console/static/assets/sizeCapture-X5ZJPWSS-Dmf1pC7B.js +0 -1
  200. package/dist/worker/console/static/assets/stateDiagram-OKZ733FA-4-jdPUHD.js +0 -1
  201. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DojWfYnC.js +0 -1
  202. package/dist/worker/console/static/assets/swimlanes-SLNWSIFB-DNhjjaAU.js +0 -2
  203. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CJo4AKWH.js +0 -8
  204. package/dist/worker/console/static/vcp/fonts/Lanxi-/345/217/257/345/256/213.woff2 +0 -0
  205. package/dist/worker/console/static/vcp/fonts/Lanxi-/346/234/227/345/256/213.woff2 +0 -0
  206. package/dist/worker/console/static/vcp/fonts/Lanxi-/350/266/205/347/262/227/351/273/221.woff2 +0 -0
  207. package/dist/workflows/dynamic/compile.js +0 -371
  208. package/dist/workflows/dynamic/compileTypes.js +0 -1
  209. package/dist/workflows/dynamic/errors.js +0 -5
  210. package/dist/workflows/dynamic/profiles.js +0 -156
  211. package/dist/workflows/dynamic/spec.js +0 -115
  212. package/dist/workflows/dynamic/validate.js +0 -275
  213. package/dist/workflows/loop/actions/dag-action.js +0 -129
  214. package/dist/workflows/loop/actions/pi-review.js +0 -267
  215. package/dist/workflows/loop/actions/shared.js +0 -157
  216. package/dist/workflows/loop/actions/shell-verify.js +0 -82
  217. package/dist/workflows/loop/actions/types.js +0 -1
  218. package/dist/workflows/loop/actions/workflow-action.js +0 -255
  219. package/dist/workflows/loop/actions.js +0 -160
  220. package/dist/workflows/loop/benchmark.js +0 -513
  221. package/dist/workflows/loop/closeout.js +0 -135
  222. package/dist/workflows/loop/context.js +0 -47
  223. package/dist/workflows/loop/events.js +0 -26
  224. package/dist/workflows/loop/hash.js +0 -32
  225. package/dist/workflows/loop/index.js +0 -8
  226. package/dist/workflows/loop/paths.js +0 -17
  227. package/dist/workflows/loop/policy/auto-policy.js +0 -112
  228. package/dist/workflows/loop/policy/path-patterns.js +0 -13
  229. package/dist/workflows/loop/rounds.js +0 -81
  230. package/dist/workflows/loop/signals.js +0 -52
  231. package/dist/workflows/loop/state.js +0 -116
  232. package/dist/workflows/loop/templates.js +0 -54
  233. package/dist/workflows/loop/types.js +0 -28
  234. /package/dist/workflows/{dynamic/artifacts.js → dag/dynamic-runtime/reduction-artifacts.js} +0 -0
@@ -0,0 +1,657 @@
1
+ /**
2
+ * Unified Tasks Model for Operator Chat (DSH Better Sidebar parity).
3
+ *
4
+ * Consolidates agent subtasks, workflow runs, background jobs and fold aggregates
5
+ * into a single unified tree and graph data model with hierarchical topology.
6
+ */
7
+ export function formatDuration(startedAt, finishedAt, now = Date.now()) {
8
+ if (!startedAt)
9
+ return "—";
10
+ const start = Date.parse(startedAt);
11
+ const end = finishedAt ? Date.parse(finishedAt) : now;
12
+ if (!Number.isFinite(start) || !Number.isFinite(end))
13
+ return "—";
14
+ const seconds = Math.max(0, Math.round((end - start) / 1000));
15
+ if (seconds < 60)
16
+ return `${seconds}s`;
17
+ const mins = Math.floor(seconds / 60);
18
+ const rem = seconds % 60;
19
+ return `${mins}m ${rem}s`;
20
+ }
21
+ export function agentStatusLabel(status) {
22
+ switch (status) {
23
+ case "starting":
24
+ return "准备中";
25
+ case "working":
26
+ return "运行中";
27
+ case "completed":
28
+ return "已完成";
29
+ case "failed":
30
+ return "失败";
31
+ case "aborted":
32
+ return "已停止";
33
+ default:
34
+ return status;
35
+ }
36
+ }
37
+ export function agentDotState(status) {
38
+ if (status === "starting" || status === "working")
39
+ return "ongoing";
40
+ if (status === "completed")
41
+ return "done";
42
+ if (status === "failed")
43
+ return "error";
44
+ return "idle";
45
+ }
46
+ export function isTaskRunning(status) {
47
+ return status === "starting" || status === "working" || status === "running" || status === "in_progress";
48
+ }
49
+ export function isTaskFailed(status) {
50
+ return status === "failed" || status === "error";
51
+ }
52
+ export function isTaskTerminal(status) {
53
+ return (status === "completed" ||
54
+ status === "failed" ||
55
+ status === "aborted" ||
56
+ status === "cancelled" ||
57
+ status === "done");
58
+ }
59
+ export function buildTasksModel(input) {
60
+ const now = input.now ?? Date.now();
61
+ const rootSessionId = input.rootSessionId ?? "";
62
+ const enableFold = input.enableFold ?? true;
63
+ const expandedFoldIds = input.expandedFoldIds ?? new Set();
64
+ const nodesById = new Map();
65
+ const edges = [];
66
+ const diagnostics = [];
67
+ let totalCount = 0;
68
+ let runningCount = 0;
69
+ let failedCount = 0;
70
+ // Session mapping table: childSessionId -> node id
71
+ const sessionToNodeId = new Map();
72
+ // 1. Root Node (the anchor session)
73
+ const rootNodeId = `root:${rootSessionId || "global"}`;
74
+ const rootNode = {
75
+ id: rootNodeId,
76
+ kind: "root",
77
+ title: input.rootTitle?.trim() || "当前会话",
78
+ status: "active",
79
+ statusLabel: "主会话",
80
+ dotState: "idle",
81
+ rootSessionId,
82
+ childrenIds: [],
83
+ depth: 0,
84
+ orphan: false,
85
+ };
86
+ nodesById.set(rootNodeId, rootNode);
87
+ // 2. Pre-process Agent subtasks. The sidebar is rooted at the active session;
88
+ // workspace snapshots may contain siblings from other roots, so exclude them
89
+ // before deriving topology rather than drawing a cross-session graph.
90
+ const allAgentTasks = input.agentTasks ?? [];
91
+ const activeSessionIds = new Set(rootSessionId ? [rootSessionId] : []);
92
+ let changed = true;
93
+ while (changed) {
94
+ changed = false;
95
+ for (const task of allAgentTasks) {
96
+ const belongsToRoot = task.rootSessionId === rootSessionId || activeSessionIds.has(task.parentSessionId);
97
+ if (belongsToRoot && task.childSessionId && !activeSessionIds.has(task.childSessionId)) {
98
+ activeSessionIds.add(task.childSessionId);
99
+ changed = true;
100
+ }
101
+ }
102
+ }
103
+ const hasRootFacts = allAgentTasks.some((task) => typeof task.rootSessionId === "string" && task.rootSessionId.length > 0);
104
+ /*
105
+ * Scope to THIS session.
106
+ *
107
+ * The workspace endpoint answers for the whole workspace, so its list mixes
108
+ * several conversations: selecting conversation A and opening its Tasks panel
109
+ * used to list conversation B's subagents too. Those rows cannot be opened —
110
+ * `openSubagent` guards on (rootSessionId ?? parentSessionId) === current
111
+ * session — so a click looked like it "jumped somewhere else" while the row
112
+ * itself did nothing.
113
+ *
114
+ * The old code fell back to `allAgentTasks` whenever no row matched the active
115
+ * root, which is exactly the case that leaked other conversations in. The
116
+ * fallback now applies only when the payload carries NO root facts at all
117
+ * (older/simpler providers), never as a rescue for a genuine mismatch.
118
+ */
119
+ const rawAgentTasks = rootSessionId && hasRootFacts
120
+ ? allAgentTasks.filter((task) => task.rootSessionId === rootSessionId ||
121
+ task.parentSessionId === rootSessionId ||
122
+ activeSessionIds.has(task.parentSessionId))
123
+ : allAgentTasks;
124
+ for (const task of rawAgentTasks) {
125
+ totalCount += 1;
126
+ const running = isTaskRunning(task.status);
127
+ const failed = isTaskFailed(task.status);
128
+ if (running)
129
+ runningCount += 1;
130
+ if (failed)
131
+ failedCount += 1;
132
+ const id = `agent:${task.parentSessionId}:${task.childSessionId ?? task.parentToolCallId}`;
133
+ if (task.childSessionId) {
134
+ sessionToNodeId.set(task.childSessionId, id);
135
+ }
136
+ nodesById.set(id, {
137
+ id,
138
+ kind: "agent",
139
+ title: task.label || task.agent || "子代理",
140
+ status: task.status,
141
+ statusLabel: agentStatusLabel(task.status),
142
+ dotState: agentDotState(task.status),
143
+ startedAt: task.startedAt,
144
+ finishedAt: task.finishedAt,
145
+ durationText: formatDuration(task.startedAt, task.finishedAt, now),
146
+ activityText: task.lastActivityText,
147
+ rootSessionId: task.rootSessionId ?? task.parentSessionId,
148
+ parentSessionId: task.parentSessionId,
149
+ childrenIds: [],
150
+ depth: 1,
151
+ canStop: task.canStop ?? (running && Boolean(task.childSessionId)),
152
+ agentTask: task,
153
+ orphan: false,
154
+ });
155
+ }
156
+ // 3. Pre-process Workflow runs
157
+ const workflowRunsList = input.workflowRuns
158
+ ? Array.isArray(input.workflowRuns)
159
+ ? input.workflowRuns
160
+ : [...input.workflowRuns.values()]
161
+ : [];
162
+ for (const run of workflowRunsList) {
163
+ totalCount += 1;
164
+ const status = String(run.status ?? "running");
165
+ const running = status === "running";
166
+ const failed = status === "error";
167
+ if (running)
168
+ runningCount += 1;
169
+ if (failed)
170
+ failedCount += 1;
171
+ const id = `workflow:${run.runId}`;
172
+ nodesById.set(id, {
173
+ id,
174
+ kind: "workflow",
175
+ title: run.name || run.runId || "工作流",
176
+ status,
177
+ statusLabel: running ? "执行中" : status === "completed" ? "已完成" : failed ? "失败" : status,
178
+ dotState: running ? "ongoing" : failed ? "error" : "done",
179
+ durationText: "—",
180
+ activityText: run.members ? `${run.members.length} 个成员` : undefined,
181
+ rootSessionId,
182
+ childrenIds: [],
183
+ depth: 1,
184
+ workflowRun: run,
185
+ orphan: false,
186
+ });
187
+ }
188
+ // 4. Background jobs are NOT topology nodes.
189
+ //
190
+ // DSH keeps the drawer a separate list: a job is a command the reader
191
+ // watches, not a participant in the agent/workflow hierarchy. Modelling jobs
192
+ // as root children made every settled shell call draw a dashed orange edge
193
+ // into the graph, which is exactly the tangle the reader reported. They are
194
+ // counted in `counts` (so the header stays honest) and consumed straight
195
+ // from `index.jobs` by the drawer.
196
+ const jobsList = input.jobs ?? [];
197
+ for (const job of jobsList) {
198
+ const status = String(job.status ?? "running");
199
+ if (status === "running" || status === "working")
200
+ runningCount += 1;
201
+ if (status === "failed" || status === "error")
202
+ failedCount += 1;
203
+ }
204
+ // 5. Connect Hierarchy & Edges
205
+ // 5.1 Re-parent workflow members
206
+ for (const run of workflowRunsList) {
207
+ const wfNodeId = `workflow:${run.runId}`;
208
+ const wfNode = nodesById.get(wfNodeId);
209
+ if (!wfNode)
210
+ continue;
211
+ for (const member of run.members ?? []) {
212
+ const memberNodeId = sessionToNodeId.get(member.childId);
213
+ if (memberNodeId && nodesById.has(memberNodeId)) {
214
+ const memberNode = nodesById.get(memberNodeId);
215
+ memberNode.parentId = wfNodeId;
216
+ memberNode.phase = member.phase;
217
+ wfNode.childrenIds.push(memberNodeId);
218
+ edges.push({
219
+ id: `edge:wf:${wfNodeId}->${memberNodeId}`,
220
+ from: wfNodeId,
221
+ to: memberNodeId,
222
+ kind: "workflow",
223
+ });
224
+ }
225
+ }
226
+ // Connect workflow to root
227
+ if (!wfNode.parentId) {
228
+ wfNode.parentId = rootNodeId;
229
+ rootNode.childrenIds.push(wfNodeId);
230
+ edges.push({
231
+ id: `edge:root->${wfNodeId}`,
232
+ from: rootNodeId,
233
+ to: wfNodeId,
234
+ kind: "workflow",
235
+ });
236
+ }
237
+ }
238
+ // 5.2 Connect agent subtasks hierarchy
239
+ for (const task of rawAgentTasks) {
240
+ const id = `agent:${task.parentSessionId}:${task.childSessionId ?? task.parentToolCallId}`;
241
+ const node = nodesById.get(id);
242
+ if (!node || node.parentId)
243
+ continue; // Already parented (e.g. to a workflow)
244
+ let parentNodeId;
245
+ if (task.parentChildSessionId) {
246
+ parentNodeId = sessionToNodeId.get(task.parentChildSessionId);
247
+ }
248
+ else if (task.parentSessionId && task.parentSessionId !== rootSessionId) {
249
+ parentNodeId = sessionToNodeId.get(task.parentSessionId);
250
+ }
251
+ if (parentNodeId && nodesById.has(parentNodeId) && parentNodeId !== id) {
252
+ node.parentId = parentNodeId;
253
+ nodesById.get(parentNodeId).childrenIds.push(id);
254
+ edges.push({
255
+ id: `edge:parent:${parentNodeId}->${id}`,
256
+ from: parentNodeId,
257
+ to: id,
258
+ kind: "parent",
259
+ });
260
+ }
261
+ else {
262
+ // Connect directly to root
263
+ node.parentId = rootNodeId;
264
+ rootNode.childrenIds.push(id);
265
+ edges.push({
266
+ id: `edge:root->${id}`,
267
+ from: rootNodeId,
268
+ to: id,
269
+ kind: "parent",
270
+ });
271
+ }
272
+ }
273
+ // 5.3 Background jobs stay out of the topology (see step 4).
274
+ // 6. Compute Depth recursively from root
275
+ const computeDepth = (nodeId, depth, visited = new Set()) => {
276
+ if (visited.has(nodeId))
277
+ return;
278
+ visited.add(nodeId);
279
+ const node = nodesById.get(nodeId);
280
+ if (!node)
281
+ return;
282
+ node.depth = depth;
283
+ for (const childId of node.childrenIds) {
284
+ computeDepth(childId, depth + 1, visited);
285
+ }
286
+ };
287
+ computeDepth(rootNodeId, 0);
288
+ // 7. Fold Aggregate Nodes (DSH parity: group settled nodes when threshold exceeded)
289
+ if (enableFold) {
290
+ const parentIds = [rootNodeId, ...nodesById.keys()];
291
+ for (const pId of parentIds) {
292
+ const parent = nodesById.get(pId);
293
+ if (!parent || parent.childrenIds.length < 3)
294
+ continue;
295
+ const settledChildren = parent.childrenIds
296
+ .map((cId) => nodesById.get(cId))
297
+ .filter((n) => Boolean(n && isTaskTerminal(n.status) && n.childrenIds.length === 0));
298
+ // If 2 or more settled leaf children exist under this parent, fold them into a summary node
299
+ if (settledChildren.length >= 2) {
300
+ const foldId = `fold:${pId}:settled`;
301
+ const isExpanded = expandedFoldIds.has(foldId);
302
+ if (!isExpanded) {
303
+ const foldCount = settledChildren.length;
304
+ const foldedIds = settledChildren.map((n) => n.id);
305
+ // Exclude folded nodes from parent children list
306
+ parent.childrenIds = parent.childrenIds.filter((cId) => !foldedIds.includes(cId));
307
+ parent.childrenIds.push(foldId);
308
+ /*
309
+ * Mark the folded members as hidden.
310
+ *
311
+ * Dropping them from `childrenIds` alone was not enough: the LAYOUT
312
+ * rebuilds its own parent map from every node's `parentId`, so the
313
+ * members were re-attached to the parent and drawn next to the fold
314
+ * aggregate they had just been folded into. Measured on a nine-child
315
+ * session: one "已完成任务 (9)" card AND all nine member cards, with
316
+ * eight connectors threading the gutter — exactly the tangle the
317
+ * reader reported. The node objects stay in the model (the expand
318
+ * path needs them); this flag is what keeps them off the canvas.
319
+ */
320
+ for (const memberId of foldedIds) {
321
+ const member = nodesById.get(memberId);
322
+ if (member)
323
+ member.foldedAway = true;
324
+ }
325
+ const foldNode = {
326
+ id: foldId,
327
+ kind: "fold",
328
+ title: `已完成任务 (${foldCount})`,
329
+ status: "completed",
330
+ statusLabel: `${foldCount} 个任务已收起`,
331
+ dotState: "done",
332
+ foldKind: "done",
333
+ parentId: pId,
334
+ childrenIds: [],
335
+ depth: parent.depth + 1,
336
+ foldCount,
337
+ foldNodeIds: foldedIds,
338
+ orphan: false,
339
+ };
340
+ nodesById.set(foldId, foldNode);
341
+ // Replace individual edges with fold edge
342
+ edges.push({
343
+ id: `edge:fold:${pId}->${foldId}`,
344
+ from: pId,
345
+ to: foldId,
346
+ kind: "fold",
347
+ });
348
+ }
349
+ }
350
+ }
351
+ }
352
+ return {
353
+ rootSessionId,
354
+ rootNode,
355
+ nodes: [...nodesById.values()],
356
+ edges,
357
+ counts: {
358
+ total: totalCount,
359
+ running: runningCount,
360
+ failed: failedCount,
361
+ },
362
+ diagnostics,
363
+ };
364
+ }
365
+ /* ==========================================================================
366
+ Graph Hierarchical Layout Algorithm (T4 Parity)
367
+ ========================================================================== */
368
+ export const TASK_GRAPH_CARD_WIDTH_SIDEBAR = 190;
369
+ export const TASK_GRAPH_CARD_WIDTH_PAGE = 190;
370
+ /* ── Card heights, derived the way DSH derives them ───────────────────────
371
+ *
372
+ * These are the SUM OF THE ROWS THE CARD RENDERS, in the real metrics of the
373
+ * page's type scale — the same numbers the rules in `tasks-dsh-parity.css` are
374
+ * written with (DSH `tasks-graph-layout.ts` does the identical derivation).
375
+ *
376
+ * They are derived rather than hand-picked because the card is a fixed-geometry
377
+ * box: its height is `auto` with a reserved `min-height`, so an under-reserved
378
+ * card does NOT stay inside the box the layout handed it — it renders taller,
379
+ * and everything the layout derives from that height (the row pitch, the phase
380
+ * frames, the canvas extent) then disagrees with the pixels on screen.
381
+ */
382
+ /** The card's own border. */
383
+ const NODE_EDGE_H = 1;
384
+ const NODE_CHROME_H = 2 * NODE_EDGE_H;
385
+ /** `.oc-tasks-graph-card__top` vertical padding (6px top / 5px bottom). */
386
+ const NODE_PAD_TOP = 6;
387
+ const NODE_PAD_BOTTOM = 5;
388
+ /** One badge row — 11px/14px type plus its 2px lead. */
389
+ const NODE_BADGE_H = 14 + 2;
390
+ /** One title line — 12px/18px. */
391
+ const NODE_TITLE_LINE_H = 18;
392
+ /** Title lines the card reserves: the `-webkit-line-clamp` in the stylesheet. */
393
+ const NODE_TITLE_LINES = 2;
394
+ /** The mono meta line — 11px/14px plus its 2px lead. */
395
+ const NODE_META_H = 14 + 2;
396
+ /** The state bar — `.oc-tasks-graph-card__bottom`'s fixed height. */
397
+ const NODE_BAR_H = 22;
398
+ /** One line of the card's text tail — 10px/1.3. */
399
+ const NODE_TEXT_LINE_H = 13;
400
+ /** The text tail's lead above its first line. */
401
+ const NODE_TEXT_LEAD_H = 2;
402
+ /** Lines the text tail may show at most. */
403
+ export const NODE_TEXT_MAX_LINES = 1;
404
+ /** An AGENT card: badge row + two title lines + state bar. The mode word lives
405
+ * in the badge row, so an agent card reserves no mono meta line. */
406
+ export const GRAPH_AGENT_NODE_H = NODE_CHROME_H + NODE_PAD_TOP + NODE_BADGE_H + NODE_TITLE_LINES * NODE_TITLE_LINE_H + NODE_PAD_BOTTOM + NODE_BAR_H;
407
+ /** A WORKFLOW run keeps its mono meta line (status · member tally). */
408
+ export const GRAPH_NODE_H = GRAPH_AGENT_NODE_H + NODE_META_H;
409
+ /** The base card reserve (the agent card). Kept for callers that need a floor. */
410
+ export const TASK_GRAPH_CARD_HEIGHT = GRAPH_AGENT_NODE_H;
411
+ export function taskNodeHeight(node) {
412
+ // A run carries the mono meta line; an agent may add a clamped text tail for
413
+ // its newest output. Everything else is the agent card's own reserve.
414
+ let height = node.kind === "workflow" && node.activityText ? GRAPH_NODE_H : GRAPH_AGENT_NODE_H;
415
+ if (node.kind === "agent" && node.agentTask?.outputPreview && node.agentTask.outputPreview.trim()) {
416
+ height += NODE_TEXT_LINE_H * NODE_TEXT_MAX_LINES + NODE_TEXT_LEAD_H;
417
+ }
418
+ return height;
419
+ }
420
+ const GRAPH_GAP_X = 28;
421
+ const GRAPH_GAP_Y = 53;
422
+ const GRAPH_PAD = 16;
423
+ const GRAPH_MAX_BAND_COLS_SIDEBAR = 2;
424
+ const GRAPH_MAX_BAND_COLS_PAGE = 4;
425
+ /** The readability floor the fit honours: the canvas may shrink to this scale
426
+ * before the layout starts wrapping. Fit and column budget must agree on it. */
427
+ export const GRAPH_FIT_MIN_SCALE = 0.78;
428
+ /** The perpendicular stub each connector leaves/enters a card with (px,
429
+ * pre-scale). DSH's `EDGE_STUB`; see the edge-path comment below for why the
430
+ * stubs exist at all. */
431
+ const EDGE_STUB = 8;
432
+ /**
433
+ * The shape of ONE connector.
434
+ *
435
+ * Exported because the layout tween rebuilds every path once per animation
436
+ * frame (`tasks-layout-tween.ts`); while it carried its OWN copy of the old
437
+ * single-cubic formula, the tween silently overwrote whatever this function
438
+ * produced — the model's path never reached the screen, and a fix here looked
439
+ * like a no-op in the browser while the unit test passed.
440
+ *
441
+ * The shape IS DSH's `TasksGraph.edgePath`, verbatim:
442
+ *
443
+ * M start → L stub → C (the turn) → L stub → end
444
+ *
445
+ * The stubs make the wire leave and enter VERTICALLY. A pure bottom-centre to
446
+ * top-centre bezier would leave at an angle, so a ranked tree reads as a fan of
447
+ * diagonals over the cards between the rows.
448
+ *
449
+ * WHY THERE IS NO DETOUR FOR DEEP CHILDREN (this used to have one — read this
450
+ * before adding it back): the SVG is the FIRST child of the canvas and the cards
451
+ * are painted after it, so a connector that crosses a card is simply COVERED by
452
+ * that card's opaque `var(--surface)` fill. The wire is clipped into the gaps
453
+ * for free, exactly where a reader wants to see it.
454
+ *
455
+ * A detour defeats that: routing around the cards puts the line in the gutters
456
+ * where nothing hides it, so six deep children of one parent became six parallel
457
+ * "conduits" threading the column gap. Measured on the nine-child session: 6 of
458
+ * 9 edges were detouring, and the tangle the reader complained about was those
459
+ * exposed lines, not the crossings. Straight stubs plus an opaque card layer is
460
+ * both simpler and quieter.
461
+ */
462
+ export function taskEdgePath(from, to, _allNodes) {
463
+ const x1 = from.x + from.width / 2;
464
+ const y1 = from.y + from.height;
465
+ const x2 = to.x + to.width / 2;
466
+ const y2 = to.y;
467
+ const span = Math.max(0, y2 - y1);
468
+ const stub = Math.min(EDGE_STUB, span / 3);
469
+ const dy = Math.max(16, (y2 - y1 - stub * 2) / 2);
470
+ if (span <= 0) {
471
+ /* A child ABOVE its parent (a re-parented workflow member): no downward
472
+ span, so a straight line rather than a curve with negative control
473
+ points. */
474
+ return `M ${x1} ${y1} L ${x2} ${y2}`;
475
+ }
476
+ return `M ${x1} ${y1} L ${x1} ${y1 + stub} `
477
+ + `C ${x1} ${y1 + stub + dy} ${x2} ${y2 - stub - dy} ${x2} ${y2 - stub} `
478
+ + `L ${x2} ${y2}`;
479
+ }
480
+ /** DSH-style top-down tidy-tree layout with narrow-sidebar sibling wrapping. */
481
+ export function layoutTasksGraph(model, surface = "sidebar", containerWidth) {
482
+ return layoutTasksGraphWithCols(model, surface, containerWidth, surface === "sidebar"
483
+ ? containerWidth !== undefined && containerWidth < 300 ? 1 : GRAPH_MAX_BAND_COLS_SIDEBAR
484
+ : GRAPH_MAX_BAND_COLS_PAGE);
485
+ }
486
+ /**
487
+ * How many sibling columns fit the container at ~1:1 scale. Columns are
488
+ * budgeted at the readability floor rather than 1:1: the fit may scale the
489
+ * canvas down to `minScale` and still be readable, so a narrow panel keeps two
490
+ * columns instead of degenerating into a one-card-per-row ladder.
491
+ */
492
+ export function bandColsFor(containerWidth, minScale = GRAPH_FIT_MIN_SCALE) {
493
+ const usable = (containerWidth <= 0 ? 360 : containerWidth) / minScale - GRAPH_PAD * 2;
494
+ const cols = Math.floor((usable + GRAPH_GAP_X) / (TASK_GRAPH_CARD_WIDTH_SIDEBAR + GRAPH_GAP_X));
495
+ return Math.min(4, Math.max(1, cols));
496
+ }
497
+ /**
498
+ * The layout for one container width: the WIDEST sibling arrangement whose
499
+ * canvas still fits the readability budget — i.e. the least-tall layout the
500
+ * reader can see without zooming below the floor. Wrapping more than needed
501
+ * turns the graph into a ladder; wrapping too little forces an unreadable
502
+ * scale, so the widest option is tried first and narrowed.
503
+ */
504
+ export function layoutTasksGraphForWidth(model, containerWidth, surface = "sidebar", minScale = GRAPH_FIT_MIN_SCALE) {
505
+ const cols = Math.min(bandColsFor(containerWidth <= 0 ? 360 : containerWidth, minScale), surface === "sidebar" ? GRAPH_MAX_BAND_COLS_SIDEBAR : GRAPH_MAX_BAND_COLS_PAGE);
506
+ const budget = containerWidth <= 0 ? Number.POSITIVE_INFINITY : (containerWidth - 24) / minScale;
507
+ // Pass 1: the least-tall arrangement that FITS at two or more columns.
508
+ for (let attempt = cols; attempt >= 2; attempt -= 1) {
509
+ const layout = layoutTasksGraphWithCols(model, surface, containerWidth, attempt);
510
+ if (layout.width <= budget)
511
+ return layout;
512
+ }
513
+ // Pass 2: nothing flat fits — accept a slight horizontal overflow (the
514
+ // reader pans a little) rather than stacking every child vertically.
515
+ const tolerant = budget * 1.2;
516
+ for (let attempt = cols; attempt >= 2; attempt -= 1) {
517
+ const layout = layoutTasksGraphWithCols(model, surface, containerWidth, attempt);
518
+ if (layout.width <= tolerant)
519
+ return layout;
520
+ }
521
+ return layoutTasksGraphWithCols(model, surface, containerWidth, 1);
522
+ }
523
+ function layoutTasksGraphWithCols(model, surface, _containerWidth, maxBandCols) {
524
+ const cardWidth = surface === "sidebar" ? TASK_GRAPH_CARD_WIDTH_SIDEBAR : TASK_GRAPH_CARD_WIDTH_PAGE;
525
+ const byId = new Map(model.nodes.filter((node) => !node.foldedAway).map((node) => [node.id, node]));
526
+ const childrenById = new Map();
527
+ for (const node of model.nodes) {
528
+ // A folded member is OFF the canvas: attaching it to its parent here is what
529
+ // made the layout draw members beside the aggregate that represents them.
530
+ if (node.foldedAway)
531
+ continue;
532
+ if (!node.parentId || !byId.has(node.parentId))
533
+ continue;
534
+ const children = childrenById.get(node.parentId) ?? [];
535
+ children.push(node);
536
+ childrenById.set(node.parentId, children);
537
+ }
538
+ // The row pitch must clear the TALLEST card this model draws, otherwise a
539
+ // card with a meta/text row overlaps the next row and pokes out of its phase
540
+ // frame (DSH rowStrideFor does the same measurement).
541
+ let tallestCard = TASK_GRAPH_CARD_HEIGHT;
542
+ for (const node of model.nodes) {
543
+ tallestCard = Math.max(tallestCard, taskNodeHeight(node));
544
+ }
545
+ const rowHeight = tallestCard + GRAPH_GAP_Y;
546
+ const boxes = new Map();
547
+ const visited = new Set();
548
+ let cursorRow = 0;
549
+ const bands = (items) => {
550
+ const result = [];
551
+ for (let i = 0; i < items.length; i += maxBandCols)
552
+ result.push(items.slice(i, i + maxBandCols));
553
+ return result;
554
+ };
555
+ const subtreeWidth = (node) => {
556
+ const children = childrenById.get(node.id) ?? [];
557
+ if (children.length === 0)
558
+ return cardWidth;
559
+ return Math.max(cardWidth, ...bands(children).map((band) => band.reduce((sum, child) => sum + subtreeWidth(child), 0) + GRAPH_GAP_X * Math.max(0, band.length - 1)));
560
+ };
561
+ const place = (node, centerX, row) => {
562
+ if (visited.has(node.id))
563
+ return row;
564
+ visited.add(node.id);
565
+ boxes.set(node.id, { id: node.id, x: Math.round(centerX - cardWidth / 2), y: GRAPH_PAD + row * rowHeight, width: cardWidth, height: taskNodeHeight(node), node });
566
+ const children = childrenById.get(node.id) ?? [];
567
+ if (children.length === 0) {
568
+ cursorRow = Math.max(cursorRow, row + 1);
569
+ return row;
570
+ }
571
+ let childRow = row + 1;
572
+ let deepest = childRow;
573
+ for (const band of bands(children)) {
574
+ const bandWidth = band.reduce((sum, child) => sum + subtreeWidth(child), 0) + GRAPH_GAP_X * Math.max(0, band.length - 1);
575
+ let x = centerX - bandWidth / 2;
576
+ let bandDeepest = childRow;
577
+ for (const child of band) {
578
+ const width = subtreeWidth(child);
579
+ bandDeepest = Math.max(bandDeepest, place(child, x + width / 2, childRow));
580
+ x += width + GRAPH_GAP_X;
581
+ }
582
+ deepest = Math.max(deepest, bandDeepest);
583
+ childRow = bandDeepest + 1;
584
+ }
585
+ cursorRow = Math.max(cursorRow, deepest + 1);
586
+ return deepest;
587
+ };
588
+ const roots = model.nodes.filter((node) => !node.foldedAway && (!node.parentId || !byId.has(node.parentId)));
589
+ let rootOffset = GRAPH_PAD;
590
+ for (const root of roots) {
591
+ const width = subtreeWidth(root);
592
+ place(root, rootOffset + width / 2, 0);
593
+ rootOffset += width + GRAPH_GAP_X;
594
+ }
595
+ const layoutNodes = [...boxes.values()];
596
+ const layoutNodeMap = new Map(layoutNodes.map((node) => [node.id, node]));
597
+ const layoutEdges = [];
598
+ for (const edge of model.edges) {
599
+ const from = layoutNodeMap.get(edge.from);
600
+ const to = layoutNodeMap.get(edge.to);
601
+ if (!from || !to)
602
+ continue;
603
+ /*
604
+ * DSH's connector shape (`TasksGraph.edgePath`), extended with a detour
605
+ * for the one case DSH's version gets wrong:
606
+ *
607
+ * M start → L stub → C (the turn) → L stub → end
608
+ *
609
+ * The stubs make the wire leave and enter VERTICALLY, so an edge between
610
+ * ADJACENT rows turns entirely inside the gutter — the only empty band on
611
+ * the canvas. That is exactly right for the usual one- or two-child tree.
612
+ *
613
+ * A child more than one row down breaks it: the parent's curve has to
614
+ * travel past the rows in between, and it cuts straight through whatever
615
+ * card sits on the line. Measured on a four-child tree (two bands, so two
616
+ * child rows): `root → c2` passed through `c0` and `root → c3` through
617
+ * `c1`. The parents' own vertical stubs are what visually read as
618
+ * "connections tangled in the cards".
619
+ *
620
+ * So when the child is deeper than one row, the wire routes through the
621
+ * FREE VERTICAL CORRIDOR between the two columns (or down the parent's own
622
+ * column edge when there is only one column), then turns at the child's
623
+ * row. The detour is a plain polyline with rounded corners; it never needs
624
+ * to cross a card because the corridor is gutter all the way down.
625
+ */
626
+ const path = taskEdgePath(from, to, layoutNodes);
627
+ layoutEdges.push({ id: edge.id, from: edge.from, to: edge.to, kind: edge.kind, path });
628
+ }
629
+ const phaseFrames = [];
630
+ const byPhase = new Map();
631
+ for (const node of layoutNodes) {
632
+ if (!node.node.phase || !node.node.parentId?.startsWith("workflow:"))
633
+ continue;
634
+ const key = `${node.node.parentId}:${node.node.phase}`;
635
+ byPhase.set(key, [...(byPhase.get(key) ?? []), node]);
636
+ }
637
+ for (const [key, phaseNodes] of byPhase) {
638
+ const minX = Math.min(...phaseNodes.map((node) => node.x)) - 8;
639
+ const minY = Math.min(...phaseNodes.map((node) => node.y)) - 22;
640
+ const maxX = Math.max(...phaseNodes.map((node) => node.x + node.width)) + 8;
641
+ const maxY = Math.max(...phaseNodes.map((node) => node.y + node.height)) + 8;
642
+ phaseFrames.push({ id: `frame:${key}`, title: `Phase: ${phaseNodes[0]?.node.phase ?? "Phase"}`, x: minX, y: minY, width: maxX - minX, height: maxY - minY });
643
+ }
644
+ // The canvas extent is measured from the boxes actually drawn, not from the
645
+ // root-cursor offset: `rootOffset` already carries a trailing gap that no
646
+ // box occupies, and counting it made a two-column layout 60px wider than its
647
+ // content — enough to break the fit on a 360px rail.
648
+ const contentRight = Math.max(GRAPH_PAD + cardWidth, ...layoutNodes.map((node) => node.x + node.width), ...phaseFrames.map((frame) => frame.x + frame.width));
649
+ const contentBottom = Math.max(GRAPH_PAD + TASK_GRAPH_CARD_HEIGHT, ...layoutNodes.map((node) => node.y + node.height), ...phaseFrames.map((frame) => frame.y + frame.height));
650
+ return {
651
+ nodes: layoutNodes,
652
+ edges: layoutEdges,
653
+ phaseFrames,
654
+ width: contentRight + GRAPH_PAD,
655
+ height: contentBottom + GRAPH_PAD,
656
+ };
657
+ }