@tea-agent/loop-agent 0.1.0-fe-test.3 → 0.1.0-fe-test.5

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 (485) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +607 -93
  3. package/README.md +11 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  6. package/dist/adapters/context-transfer/pi-session.js +61 -0
  7. package/dist/application/dag/generate-task-dag.js +90 -21
  8. package/dist/application/dag/run-dag.js +41 -0
  9. package/dist/application/task-lifecycle/advance.js +40 -5
  10. package/dist/application/task-lifecycle/observe.js +171 -17
  11. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  12. package/dist/application/task-lifecycle/recommendations.js +13 -2
  13. package/dist/build-stamp.json +3 -3
  14. package/dist/cli/command-definitions.js +44 -10
  15. package/dist/cli/program.js +82 -6
  16. package/dist/cli/update/notifier.js +2 -2
  17. package/dist/cli/update/runtime-activity.js +1 -29
  18. package/dist/cli.js +2 -1
  19. package/dist/commands/client-recovery.js +11 -36
  20. package/dist/commands/dag-artifact.js +284 -0
  21. package/dist/commands/dag-context.js +184 -0
  22. package/dist/commands/dag-follow-up.js +138 -0
  23. package/dist/commands/dag-rerun-task.js +2 -0
  24. package/dist/commands/dag-rerun.js +261 -2
  25. package/dist/commands/init-model-catalog.js +486 -0
  26. package/dist/commands/init-upgrade.js +265 -97
  27. package/dist/commands/init.js +455 -28
  28. package/dist/commands/inspect-next.js +8 -0
  29. package/dist/commands/task-advance.js +73 -1
  30. package/dist/commands/task-source-prepare.js +5 -0
  31. package/dist/commands/task-status.js +1 -0
  32. package/dist/executors/dag-pi-executor.js +4323 -231
  33. package/dist/executors/pi-event-serializer.js +42 -1
  34. package/dist/executors/pi-executor.js +70 -6
  35. package/dist/executors/pi-extension-resolver.js +245 -0
  36. package/dist/executors/pi-playwright-cli-tool.js +74 -28
  37. package/dist/executors/pi-read-budget-policy.js +239 -0
  38. package/dist/executors/pi-sdk-executor.js +263 -59
  39. package/dist/executors/pi-writer-tool-policy.js +57 -1
  40. package/dist/executors/shell-executor.js +1456 -240
  41. package/dist/executors/shell-write-guard.js +14 -0
  42. package/dist/executors/workspace-write-snapshot.js +68 -0
  43. package/dist/governance/checks.js +1 -0
  44. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  45. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  46. package/dist/infrastructure/console/context-export-store.js +160 -0
  47. package/dist/infrastructure/console/dir-lock.js +132 -0
  48. package/dist/infrastructure/console/operation-store.js +417 -0
  49. package/dist/infrastructure/harness/artifact-store.js +10 -1
  50. package/dist/infrastructure/harness/atomic-write.js +35 -2
  51. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  52. package/dist/shared/context-transfer.js +418 -0
  53. package/dist/shared/dag-failure-category.js +150 -0
  54. package/dist/shared/dag-prompt-override.js +27 -0
  55. package/dist/shared/openspec-spec.js +70 -4
  56. package/dist/shared/operator/capabilities.js +65 -4
  57. package/dist/shared/operator/safe-run-summary.js +1 -0
  58. package/dist/shared/path-safety.js +93 -0
  59. package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
  60. package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
  61. package/dist/shared/pi-context-pressure/env.js +58 -0
  62. package/dist/shared/pi-context-pressure/extension.js +100 -0
  63. package/dist/shared/pi-context-pressure/index.js +7 -0
  64. package/dist/shared/pi-context-pressure/overflow.js +252 -0
  65. package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
  66. package/dist/shared/pi-context-pressure/telemetry.js +51 -0
  67. package/dist/shared/playwright-cli-command-policy.js +15 -0
  68. package/dist/shared/preview.js +28 -4
  69. package/dist/shared/update/console-notifier.js +100 -0
  70. package/dist/{cli → shared}/update/npm-client.js +70 -15
  71. package/dist/{cli → shared}/update/state.js +41 -13
  72. package/dist/task/config-types.js +125 -6
  73. package/dist/task/contract/adopt.js +4 -0
  74. package/dist/task/contract/apply.js +11 -1
  75. package/dist/task/contract/constants.js +3 -0
  76. package/dist/task/contract/diff.js +26 -0
  77. package/dist/task/contract/hash.js +3 -0
  78. package/dist/task/contract/import-revision.js +4 -0
  79. package/dist/task/contract/observe.js +25 -4
  80. package/dist/task/contract/paths.js +2 -1
  81. package/dist/task/contract/project.js +23 -1
  82. package/dist/task/contract/schema.js +9 -1
  83. package/dist/task/contract/transaction.js +12 -0
  84. package/dist/task/frontend-project-capability.js +203 -20
  85. package/dist/task/runtime.js +5 -2
  86. package/dist/task/source-prepare/build-draft.js +18 -3
  87. package/dist/task/source-prepare/completeness.js +188 -0
  88. package/dist/task/source-prepare/fragment-inventory.js +513 -0
  89. package/dist/task/source-prepare/index.js +3 -0
  90. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  91. package/dist/task/source-prepare/ledger-review.js +214 -0
  92. package/dist/task/source-prepare/ledger.js +545 -0
  93. package/dist/task/source-prepare/parse-intent.js +24 -4
  94. package/dist/task/source-prepare/prepare.js +368 -2
  95. package/dist/task/source-prepare/semantic-intake.js +25 -5
  96. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  97. package/dist/task/source-prepare/types.js +22 -0
  98. package/dist/task/source-references.js +22 -1
  99. package/dist/task/task-demand-routing.js +3 -0
  100. package/dist/worker/cli.js +18 -2
  101. package/dist/worker/console/chat/assistant-content.js +7 -0
  102. package/dist/worker/console/chat/chat-event-store.js +159 -18
  103. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  104. package/dist/worker/console/chat/context-panel.js +7 -0
  105. package/dist/worker/console/chat/deferred-turn.js +103 -0
  106. package/dist/worker/console/chat/goal-round-driver.js +72 -0
  107. package/dist/worker/console/chat/goals.js +300 -0
  108. package/dist/worker/console/chat/model-resolver.js +7 -4
  109. package/dist/worker/console/chat/operation-card.js +8 -1
  110. package/dist/worker/console/chat/pi-console-config.js +81 -10
  111. package/dist/worker/console/chat/pi-runtime.js +868 -30
  112. package/dist/worker/console/chat/provider-error.js +99 -0
  113. package/dist/worker/console/chat/repo-browser.js +101 -12
  114. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  115. package/dist/worker/console/chat/routes.js +1451 -145
  116. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  117. package/dist/worker/console/chat/semantic-activity.js +25 -24
  118. package/dist/worker/console/chat/session-catalog.js +50 -0
  119. package/dist/worker/console/chat/session-stats.js +275 -0
  120. package/dist/worker/console/chat/session-store.js +348 -76
  121. package/dist/worker/console/chat/shortcuts.js +26 -3
  122. package/dist/worker/console/chat/sift-bridge.js +1 -0
  123. package/dist/worker/console/chat/todos.js +115 -0
  124. package/dist/worker/console/chat/tool-preview.js +42 -0
  125. package/dist/worker/console/chat/turn-process.js +185 -112
  126. package/dist/worker/console/chat/user-questions.js +266 -0
  127. package/dist/worker/console/chat/workspace-landing.js +79 -0
  128. package/dist/worker/console/console-handoff.js +82 -0
  129. package/dist/worker/console/console-update-and-init.js +115 -0
  130. package/dist/worker/console/console-update-runtime.js +84 -0
  131. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  132. package/dist/worker/console/dag-confirmation.js +1 -1
  133. package/dist/worker/console/dag-execution-receipt.js +54 -3
  134. package/dist/worker/console/doctor.js +1 -1
  135. package/dist/worker/console/draft-store.js +50 -1
  136. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  137. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  138. package/dist/worker/console/human-gate-token.js +1 -1
  139. package/dist/worker/console/index.js +6 -3
  140. package/dist/worker/console/inspect-split.js +18 -0
  141. package/dist/worker/console/interview/assessment.js +1 -1
  142. package/dist/worker/console/interview/session.js +1 -1
  143. package/dist/worker/console/native-directory-picker.js +13 -0
  144. package/dist/worker/console/operation-run-facts.js +19 -3
  145. package/dist/worker/console/operation-runner.js +45 -4
  146. package/dist/worker/console/operation-sse.js +1 -1
  147. package/dist/worker/console/operation-wait.js +1 -1
  148. package/dist/worker/console/operator-actions.js +534 -15
  149. package/dist/worker/console/operator-selection.js +6 -2
  150. package/dist/worker/console/operator-surface-health.js +2 -1
  151. package/dist/worker/console/operator-user-error.js +171 -2
  152. package/dist/worker/console/pi-plugins.catalog.json +73658 -0
  153. package/dist/worker/console/pi-plugins.js +238 -0
  154. package/dist/worker/console/pi-readiness.js +7 -6
  155. package/dist/worker/console/prd-intake-bridge.js +13 -0
  156. package/dist/worker/console/recovery-cta.js +4 -4
  157. package/dist/worker/console/recovery-error-copy.js +4 -4
  158. package/dist/worker/console/routes.js +1231 -10
  159. package/dist/worker/console/security.js +102 -13
  160. package/dist/worker/console/server.js +762 -159
  161. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
  162. package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
  163. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
  164. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
  165. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
  166. package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
  167. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
  168. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
  169. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
  170. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
  171. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
  172. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
  173. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
  174. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
  175. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
  176. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
  177. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
  178. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
  179. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
  180. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
  181. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
  182. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
  183. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
  184. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
  185. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
  186. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
  187. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
  188. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
  189. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
  190. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
  191. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
  192. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
  193. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  194. package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
  195. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
  196. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
  197. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
  198. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
  199. package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
  200. package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
  201. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
  202. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
  203. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
  204. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
  205. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
  206. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
  207. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
  208. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
  209. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
  210. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
  211. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
  212. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
  213. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
  214. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
  215. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
  216. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
  217. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
  218. package/dist/worker/console/static/index.html +7 -2
  219. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  220. package/dist/worker/console/static-src/app/console-types.js +68 -4
  221. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  222. package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
  223. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  224. package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
  225. package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
  226. package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
  227. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  228. package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
  229. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
  230. package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
  231. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  232. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  233. package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
  234. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  235. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
  236. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  237. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  238. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  239. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  240. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
  241. package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
  242. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
  243. package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
  244. package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
  245. package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
  246. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
  247. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
  248. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  249. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  250. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  251. package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
  252. package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
  253. package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
  254. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
  255. package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
  256. package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
  257. package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
  258. package/dist/worker/console/workspace-context.js +399 -0
  259. package/dist/worker/console/workspace-registry.js +487 -0
  260. package/dist/worker/continuation/worker-continuation.js +278 -0
  261. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  262. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  263. package/dist/worker/materialize/harness-task-lineage.js +5 -2
  264. package/dist/worker/observability/init-runtime-activity.js +26 -0
  265. package/dist/worker/observability/read-model.js +26 -0
  266. package/dist/worker/observe/health.js +1 -1
  267. package/dist/worker/observe/node-input.js +160 -3
  268. package/dist/worker/observe/node-process.js +377 -0
  269. package/dist/worker/observe/node-transparency.js +572 -0
  270. package/dist/worker/observe/routes.js +278 -3
  271. package/dist/worker/observe/server.js +4 -0
  272. package/dist/worker/observe/shell-handler-keys.js +34 -0
  273. package/dist/worker/observe/static/api.js +154 -4
  274. package/dist/worker/observe/static/app.js +18 -70
  275. package/dist/worker/observe/static/constants.js +26 -19
  276. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  277. package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
  278. package/dist/worker/observe/static/dag-helpers.js +4 -2
  279. package/dist/worker/observe/static/dag-history-labels.js +5 -0
  280. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  281. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  282. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  283. package/dist/worker/observe/static/dag-node-purpose.js +208 -0
  284. package/dist/worker/observe/static/format.js +60 -0
  285. package/dist/worker/observe/static/index.html +10 -5
  286. package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
  287. package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
  288. package/dist/worker/observe/static/inspect-workspace.js +374 -0
  289. package/dist/worker/observe/static/kpi.js +2 -2
  290. package/dist/worker/observe/static/markdown-render.js +20 -1
  291. package/dist/worker/observe/static/operator-chrome.css +168 -24
  292. package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
  293. package/dist/worker/observe/static/operator-chrome.js +354 -101
  294. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  295. package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
  296. package/dist/worker/observe/static/relations.js +7 -7
  297. package/dist/worker/observe/static/router.d.ts +57 -0
  298. package/dist/worker/observe/static/router.js +67 -1
  299. package/dist/worker/observe/static/run-processing.js +4 -2
  300. package/dist/worker/observe/static/shell-chrome.js +2 -2
  301. package/dist/worker/observe/static/state.d.ts +50 -0
  302. package/dist/worker/observe/static/state.js +191 -1
  303. package/dist/worker/observe/static/styles.css +1720 -86
  304. package/dist/worker/observe/static/views/dag-graph.js +5 -3
  305. package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
  306. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  307. package/dist/worker/observe/static/views/dag.js +39 -18
  308. package/dist/worker/observe/static/views/dags.js +10 -6
  309. package/dist/worker/observe/static/views/dashboard.js +18 -8
  310. package/dist/worker/observe/static/views/failures.js +5 -2
  311. package/dist/worker/observe/static/views/night.js +2 -2
  312. package/dist/worker/observe/static/views/pool.js +8 -2
  313. package/dist/worker/observe/static/views/run.js +15 -4
  314. package/dist/worker/observe/static/views/session-timeline.js +386 -25
  315. package/dist/worker/observe/static/views/task.js +63 -3
  316. package/dist/worker/outcomes/adapters.js +19 -0
  317. package/dist/worker/outcomes/types.js +1 -0
  318. package/dist/worker/pool/attempt-lease.js +97 -66
  319. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  320. package/dist/worker/pool/reconcile.js +46 -1
  321. package/dist/worker/pool/run-store.js +2 -0
  322. package/dist/worker/pool/state-projection.js +2 -0
  323. package/dist/worker/task-spec/workflow-routing.js +8 -3
  324. package/dist/workflows/dag/artifact-bindings.js +149 -0
  325. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  326. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
  327. package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
  328. package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
  329. package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
  330. package/dist/workflows/dag/backend-test-result-contract.js +5 -1
  331. package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
  332. package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
  333. package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
  334. package/dist/workflows/dag/budget-enforcement.js +10 -0
  335. package/dist/workflows/dag/context-receipt.js +305 -0
  336. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  337. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  338. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  339. package/dist/workflows/dag/contract-output-registry.js +15 -0
  340. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  341. package/dist/workflows/dag/convergence/controller.js +141 -0
  342. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  343. package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
  344. package/dist/workflows/dag/dynamic-runtime/map.js +17 -3
  345. package/dist/workflows/dag/failure-category.js +7 -116
  346. package/dist/workflows/dag/frontend-closeout.js +221 -0
  347. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  348. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  349. package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
  350. package/dist/workflows/dag/frontend-plan-render.js +26 -1
  351. package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
  352. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  353. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  354. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  355. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  356. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  357. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  358. package/dist/workflows/dag/frontend-repair.js +7 -424
  359. package/dist/workflows/dag/frontend-review-context.js +348 -20
  360. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  361. package/dist/workflows/dag/frontend-risk.js +15 -2
  362. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  363. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  364. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  365. package/dist/workflows/dag/frontend-shape.js +435 -0
  366. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  367. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  368. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  369. package/dist/workflows/dag/frontend-test-case-checklist.js +32 -4
  370. package/dist/workflows/dag/frontend-test-case-generation-assessment.js +69 -0
  371. package/dist/workflows/dag/frontend-test-case-manifest.js +17 -5
  372. package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
  373. package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
  374. package/dist/workflows/dag/frontend-test-html-report.js +3 -1
  375. package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
  376. package/dist/workflows/dag/frontend-test-layout.js +159 -0
  377. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  378. package/dist/workflows/dag/frontend-test-result-contract.js +202 -42
  379. package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
  380. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  381. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  382. package/dist/workflows/dag/frontend-verification-trace.js +281 -29
  383. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  384. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  385. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  386. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  387. package/dist/workflows/dag/init-hybrid.js +1771 -717
  388. package/dist/workflows/dag/interrupt-request.js +10 -3
  389. package/dist/workflows/dag/lifecycle.js +3 -3
  390. package/dist/workflows/dag/node-execution.js +1141 -32
  391. package/dist/workflows/dag/path-safety.js +1 -0
  392. package/dist/workflows/dag/prompt.js +158 -7
  393. package/dist/workflows/dag/recovery-lease.js +170 -0
  394. package/dist/workflows/dag/report.js +37 -1
  395. package/dist/workflows/dag/rerun-feedback.js +526 -0
  396. package/dist/workflows/dag/rerun-plan.js +790 -28
  397. package/dist/workflows/dag/rerun-run.js +700 -21
  398. package/dist/workflows/dag/rerun-task.js +311 -14
  399. package/dist/workflows/dag/retry-policy.js +336 -101
  400. package/dist/workflows/dag/runner.js +596 -121
  401. package/dist/workflows/dag/scheduler.js +133 -20
  402. package/dist/workflows/dag/skill-snapshot.js +17 -0
  403. package/dist/workflows/dag/structured-output-repair.js +712 -0
  404. package/dist/workflows/dag/types.js +600 -31
  405. package/dist/workflows/dag/validate.js +92 -32
  406. package/docs/README.md +2 -0
  407. package/docs/architecture/evolution.md +45 -0
  408. package/docs/architecture/runtime-boundaries.md +8 -7
  409. package/docs/architecture/worker-and-feature.md +1 -1
  410. package/docs/examples/README.md +5 -0
  411. package/docs/init-surface.manifest.json +36 -12
  412. package/docs/operations/README.md +1 -1
  413. package/docs/operations/local-development-environment.md +22 -5
  414. package/docs/skills/vetted-skill-registry.md +16 -0
  415. package/docs/templates/README.md +4 -2
  416. package/docs/templates/agent-dag-report.schema.json +8 -2
  417. package/docs/templates/agent-dag.schema.json +95 -1
  418. package/docs/templates/backend-test-dag.json +278 -244
  419. package/docs/templates/frontend-implementation-contract.schema.json +684 -24
  420. package/docs/templates/frontend-implementation-dag.json +89 -0
  421. package/docs/templates/frontend-test-case-checklist.md +2 -2
  422. package/docs/templates/frontend-test-dag.json +10 -12
  423. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  424. package/docs/templates/init-managed-agents.md +13 -3
  425. package/docs/templates/product-line/task.yaml +1 -1
  426. package/docs/templates/spec-registry.schema.json +45 -0
  427. package/harness.json +2 -2
  428. package/package.json +19 -5
  429. package/scripts/next-info.mjs +356 -0
  430. package/scripts/next-publish-gate.mjs +238 -0
  431. package/scripts/release-source-binding.mjs +251 -0
  432. package/skills/analyze-product-requirements/SKILL.md +8 -5
  433. package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
  434. package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
  435. package/skills/analyze-product-requirements/references/example.md +50 -0
  436. package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
  437. package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
  438. package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
  439. package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
  440. package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
  441. package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
  442. package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
  443. package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
  444. package/skills/codebase-scout/SKILL.md +1 -1
  445. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  446. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  447. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  448. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  449. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  450. package/skills/frontend-contract/SKILL.md +23 -0
  451. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  452. package/skills/frontend-design-review/SKILL.md +22 -41
  453. package/skills/frontend-plan/SKILL.md +26 -0
  454. package/skills/frontend-plan/references/decision-contract.md +37 -0
  455. package/skills/frontend-plan/references/design-decisions.md +17 -0
  456. package/skills/frontend-review/SKILL.md +20 -15
  457. package/skills/frontend-review/references/review-findings.md +6 -7
  458. package/skills/frontend-scout/SKILL.md +25 -0
  459. package/skills/frontend-scout/references/design-evidence.md +16 -0
  460. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  461. package/skills/frontend-verification/SKILL.md +1 -1
  462. package/skills/improve-codebase-architecture/SKILL.md +81 -0
  463. package/skills/improve-codebase-architecture/deepening.md +37 -0
  464. package/skills/improve-codebase-architecture/html-report.md +123 -0
  465. package/skills/improve-codebase-architecture/interface-design.md +44 -0
  466. package/skills/improve-codebase-architecture/language.md +53 -0
  467. package/skills/loop-agent/references/command-reference.md +32 -4
  468. package/skills/loop-agent/references/hybrid-dag.md +9 -2
  469. package/skills/playwright-cli/SKILL.md +23 -1
  470. package/skills/playwright-cli-case-generator/SKILL.md +50 -13
  471. package/dist/worker/console/operation-store.js +0 -169
  472. package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
  473. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
  474. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
  475. package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
  476. package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
  477. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
  478. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
  479. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  480. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
  481. package/skills/frontend-implementation/SKILL.md +0 -52
  482. package/skills/frontend-implementation/references/code-standards.md +0 -33
  483. package/skills/frontend-implementation/references/design-spec.md +0 -56
  484. package/skills/frontend-implementation/references/node-contracts.md +0 -31
  485. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -1,12 +1,100 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
- import { parseAssistantContent } from "../../chat/assistant-content.js";
3
2
  import { runtimeSelectionFromRecord } from "../../chat/runtime-selection.js";
4
3
  import { hydrateSessionThread } from "../../chat/turn-process.js";
5
- import { ACTIVE_CHAT_SESSION_STORAGE_KEY } from "../../chat/workspace-landing.js";
6
- import { CHAT_SESSION_LIST_LIMIT } from "../chat-view-types.js";
4
+ import { forgetActiveChatSession, readActiveChatSessionId, rememberActiveChatSession, } from "../../chat/workspace-landing.js";
7
5
  import { confirmationToken } from "./format.js";
6
+ import { isLostChatSessionError } from "./runtime-snapshot-store.js";
7
+ import { upsertCompactionMessage } from "./compaction-message.js";
8
8
  import { describeMutationGateFailure, isMutationGateFailureCode, isStaleTokenFailure, } from "./mutation-gate.js";
9
9
  import { SessionTitleWatcher } from "./session-title-watcher.js";
10
+ /** Pure list mutations keep optimistic UI deterministic and easy to verify. */
11
+ export function insertOptimisticSession(list, row) {
12
+ return [row, ...list.filter((item) => item.sessionId !== row.sessionId)];
13
+ }
14
+ export function replaceOptimisticSession(list, temporaryId, durable) {
15
+ return [
16
+ durable,
17
+ ...list.filter((item) => item.sessionId !== durable.sessionId &&
18
+ (!temporaryId || item.sessionId !== temporaryId)),
19
+ ];
20
+ }
21
+ export function removeSessionById(list, sessionId) {
22
+ const index = list.findIndex((item) => item.sessionId === sessionId);
23
+ if (index < 0)
24
+ return { next: list, index: -1 };
25
+ return {
26
+ next: list.filter((item) => item.sessionId !== sessionId),
27
+ removed: list[index],
28
+ index,
29
+ };
30
+ }
31
+ export function restoreSessionAt(list, row, index) {
32
+ if (list.some((item) => item.sessionId === row.sessionId))
33
+ return list;
34
+ const next = [...list];
35
+ next.splice(Math.max(0, Math.min(index, next.length)), 0, row);
36
+ return next;
37
+ }
38
+ function sameQueueSummary(a, b) {
39
+ const left = a.deferredTurns ?? (a.deferredTurn ? [a.deferredTurn] : []);
40
+ const right = b.deferredTurns ?? (b.deferredTurn ? [b.deferredTurn] : []);
41
+ if (left.length !== right.length)
42
+ return false;
43
+ return left.every((item, index) => {
44
+ const other = right[index];
45
+ return Boolean(other &&
46
+ item.clientRequestId === other.clientRequestId &&
47
+ item.revision === other.revision &&
48
+ item.state === other.state &&
49
+ item.updatedAt === other.updatedAt &&
50
+ item.textPreview === other.textPreview &&
51
+ item.imageCount === other.imageCount &&
52
+ item.acceptedTurnId === other.acceptedTurnId &&
53
+ item.lastError?.code === other.lastError?.code &&
54
+ item.lastError?.message === other.lastError?.message);
55
+ });
56
+ }
57
+ function sameSessionSummary(a, b) {
58
+ return (a.sessionId === b.sessionId &&
59
+ a.workspaceId === b.workspaceId &&
60
+ a.state === b.state &&
61
+ a.title === b.title &&
62
+ a.displayTitle === b.displayTitle &&
63
+ a.updatedAt === b.updatedAt &&
64
+ a.activeTurnId === b.activeTurnId &&
65
+ a.turnPhase === b.turnPhase &&
66
+ a.model?.provider === b.model?.provider &&
67
+ a.model?.modelId === b.model?.modelId &&
68
+ a.thinkingLevel === b.thinkingLevel &&
69
+ a.isBlank === b.isBlank &&
70
+ a.optimisticState === b.optimisticState &&
71
+ sameQueueSummary(a, b));
72
+ }
73
+ /** Reuse unchanged row and list references across catalog refreshes. */
74
+ export function stabilizeSessionList(previous, next) {
75
+ const previousById = new Map(previous.map((item) => [item.sessionId, item]));
76
+ let changed = previous.length !== next.length;
77
+ const stabilized = next.map((item, index) => {
78
+ const existing = previousById.get(item.sessionId);
79
+ const value = existing && sameSessionSummary(existing, item) ? existing : item;
80
+ if (value !== previous[index])
81
+ changed = true;
82
+ return value;
83
+ });
84
+ return changed ? stabilized : previous;
85
+ }
86
+ /** Select a server-confirmed blank session owned by the requested workspace. */
87
+ export function findReusableBlankSession(list, workspaceId) {
88
+ const scope = workspaceId.trim();
89
+ if (!scope)
90
+ return undefined;
91
+ return list.find((item) => item.workspaceId === scope &&
92
+ item.state === "active" &&
93
+ item.isBlank === true &&
94
+ item.turnPhase === "idle" &&
95
+ !item.activeTurnId &&
96
+ !item.optimisticState);
97
+ }
10
98
  export async function createSessionAndPrimeTitleWatcher(input) {
11
99
  if (input.creatingRef?.current) {
12
100
  throw new Error("CREATE_SESSION_IN_FLIGHT");
@@ -24,30 +112,37 @@ export async function createSessionAndPrimeTitleWatcher(input) {
24
112
  "x-loop-console-confirmation": confirmationToken(),
25
113
  },
26
114
  credentials: "include",
27
- body: JSON.stringify(input.options ?? {}),
115
+ body: JSON.stringify((() => {
116
+ const { optimisticSessionId: _optimisticSessionId, ...body } = input.options ?? {};
117
+ return body;
118
+ })()),
28
119
  });
29
120
  if (!res.ok) {
30
121
  const body = (await res.json().catch(() => ({})));
122
+ if (isMutationGateFailureCode(body.error?.code)) {
123
+ throw new Error(describeMutationGateFailure(body.error.code));
124
+ }
31
125
  throw new Error(body.error?.message ?? `HTTP ${res.status}`);
32
126
  }
33
127
  const body = (await res.json());
34
128
  if (!body.session)
35
129
  throw new Error("创建会话响应缺少 durable session");
36
- const durable = body.session;
130
+ const durable = { ...body.session, isBlank: true };
37
131
  const created = {
38
132
  sessionId: durable.sessionId,
133
+ ...(durable.workspaceId || input.options?.workspaceId
134
+ ? {
135
+ workspaceId: durable.workspaceId ?? input.options?.workspaceId,
136
+ }
137
+ : {}),
39
138
  ...runtimeSelectionFromRecord(durable),
40
139
  };
41
- const nextList = [
42
- durable,
43
- ...input.sessionListRef.current.filter((item) => item.sessionId !== durable.sessionId),
44
- ].slice(0, CHAT_SESSION_LIST_LIMIT);
140
+ const nextList = replaceOptimisticSession(input.sessionListRef.current, input.options?.optimisticSessionId, durable);
45
141
  // Commit ref → state → eligibility → deferred refresh. The ref assignment
46
142
  // makes the durable record observable before React's state commit.
47
143
  input.sessionListRef.current = nextList;
48
144
  input.setSessionList(nextList);
49
145
  input.titleWatcher?.markEligible(durable.sessionId);
50
- void input.refreshSessionList();
51
146
  return created;
52
147
  }
53
148
  finally {
@@ -56,15 +151,38 @@ export async function createSessionAndPrimeTitleWatcher(input) {
56
151
  input.setCreatingSession?.(false);
57
152
  }
58
153
  }
154
+ function mergeCompactionMessages(messages, compactions) {
155
+ return (compactions ?? []).reduce((result, item) => upsertCompactionMessage(result, item), messages);
156
+ }
59
157
  /** Session lifecycle: list / activate / create / delete / rename-archive /
60
158
  * compact, plus browser-refresh recovery from the durable session store. */
61
159
  export function useChatSessions(params) {
62
160
  const { origin, refs, setSession, thread, composer, browser, setError, setNotice, onCompactionChange, setProcessOpen, setAutoScroll, } = params;
63
- const { applyActivatedSession, resetForNewSession, setMessages } = thread;
161
+ const { applyActivatedSession, resetForNewSession } = thread;
64
162
  const { setInput, setPendingImages } = composer;
65
163
  const { setPreviews, setActivePreviewPath } = browser;
164
+ const { workspaceId, blocked } = params;
165
+ const workspaceQuery = workspaceId
166
+ ? `?workspaceId=${encodeURIComponent(workspaceId)}`
167
+ : "";
168
+ /** AC-002 (2026-08-26): session detail and mutation requests follow the
169
+ * session's DURABLE owning workspace, not the global active workspace. The sidebar list
170
+ * items carry workspaceId; once a session is activated its owner is kept
171
+ * on the session record itself. Switching the Operate/Inspect active
172
+ * workspace therefore never retargets an open session's requests. */
173
+ const sessionOwnerQuery = useCallback((ownerWorkspaceId) => {
174
+ const owner = ownerWorkspaceId?.trim() ||
175
+ refs.sessionRef.current?.workspaceId?.trim() ||
176
+ "";
177
+ return owner ? `?workspaceId=${encodeURIComponent(owner)}` : "";
178
+ }, [refs]);
66
179
  const [sessionList, setSessionList] = useState([]);
67
180
  const sessionListRef = useRef([]);
181
+ const pendingDeletedIdsRef = useRef(new Set());
182
+ const pendingCreatedRowsRef = useRef(new Map());
183
+ const sessionMutationVersionRef = useRef(0);
184
+ const deleteRequestVersionsRef = useRef(new Map());
185
+ const activateSessionRef = useRef(null);
68
186
  sessionListRef.current = sessionList;
69
187
  const titleWatcherRef = useRef(null);
70
188
  // Shared busy gate for sidebar + Landing create entries (one render feedback).
@@ -76,11 +194,15 @@ export function useChatSessions(params) {
76
194
  // state. This prevents slow responses from an older selection overwriting a
77
195
  // newer user choice.
78
196
  const sessionSelectionVersionRef = useRef(0);
79
- const resetActiveProjection = useCallback(() => {
80
- // M4.5/M5.2: selection is a hard ownership boundary. Abort every request
81
- // owned by the old projection, then invalidate its async callbacks.
197
+ const resetActiveProjection = useCallback((options) => {
198
+ // M4.5/M5.2: selection is a hard ownership boundary for THIS projection.
199
+ // Multi-workspace (AC-002): keepStreams=true (workspace switch) aborts
200
+ // only projection-local requests and leaves background SSE streams of
201
+ // other sessions/workspaces running.
202
+ const keepStreams = options?.keepStreams === true;
82
203
  refs.sessionGenerationRef.current += 1;
83
- refs.abortRef.current?.abort();
204
+ if (!keepStreams)
205
+ refs.abortRef.current?.abort();
84
206
  refs.reconnectAbortRef.current?.abort();
85
207
  for (const controller of refs.sessionAbortControllersRef.current.values())
86
208
  controller.abort();
@@ -114,43 +236,98 @@ export function useChatSessions(params) {
114
236
  setAutoScroll,
115
237
  ]);
116
238
  const refreshSessionList = useCallback(async () => {
239
+ if (blocked)
240
+ return; // AC-R5-002: fail-closed, zero session requests
117
241
  try {
242
+ // The sidebar is a multi-workspace index. Keep one unscoped summary
243
+ // collection so expanding or switching a workspace never projects the
244
+ // previous workspace's list as an empty result while a scoped refresh is
245
+ // in flight. Session detail and mutation requests remain owner-scoped.
118
246
  const res = await fetch(`${origin}/api/operator/v1/chat/sessions`, {
119
247
  credentials: "include",
120
248
  });
121
- if (!res.ok)
122
- return;
123
- const sessions = (await res.json()).sessions ??
124
- [];
125
- // API returns newest-first; keep only the recent window in the sidebar.
126
- const keep = sessions.slice(0, CHAT_SESSION_LIST_LIMIT);
127
- const excess = sessions.slice(CHAT_SESSION_LIST_LIMIT);
128
- setSessionList(keep);
129
- if (excess.length === 0)
249
+ const body = (await res.json().catch(() => ({})));
250
+ if (!res.ok) {
251
+ setError(body.error?.message ?? `会话列表加载失败(HTTP ${res.status})`);
130
252
  return;
131
- await Promise.all(excess.map((item) => fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(item.sessionId)}`, {
132
- method: "DELETE",
133
- credentials: "include",
134
- headers: {
135
- "x-loop-console-confirmation": confirmationToken(),
136
- },
137
- }).catch(() => undefined)));
138
- const activeId = refs.sessionRef.current?.sessionId;
139
- if (activeId && excess.some((item) => item.sessionId === activeId)) {
140
- sessionSelectionVersionRef.current += 1;
141
- refs.sessionRef.current = null;
142
- resetActiveProjection();
143
- setSession(null);
144
- window.localStorage.removeItem(ACTIVE_CHAT_SESSION_STORAGE_KEY);
253
+ }
254
+ const sessions = body.sessions ?? [];
255
+ const durable = sessions.filter((item) => !pendingDeletedIdsRef.current.has(item.sessionId));
256
+ const optimistic = [...pendingCreatedRowsRef.current.values()].filter((item) => !durable.some((session) => session.sessionId === item.sessionId));
257
+ // Preserve every workspace's summaries. ChatWorkspaceSidebar applies the
258
+ // visible recent-item limit independently inside each workspace group.
259
+ const next = stabilizeSessionList(sessionListRef.current, [...optimistic, ...durable]);
260
+ sessionListRef.current = next;
261
+ setSessionList(next);
262
+ if (body.workspaceErrors?.length) {
263
+ setError(`部分工作区的会话加载失败(${body.workspaceErrors.length} 个)`);
145
264
  }
146
265
  }
147
- catch {
148
- /* Chat remains usable without the sidebar index. */
266
+ catch (error) {
267
+ setError(`会话列表加载失败:${error instanceof Error ? error.message : String(error)}`);
149
268
  }
150
- }, [origin, refs, resetActiveProjection, setSession]);
269
+ }, [origin, blocked, setError]);
151
270
  const deleteSession = useCallback(async (sessionId) => {
271
+ if (pendingDeletedIdsRef.current.has(sessionId))
272
+ return false;
273
+ const requestId = ++sessionMutationVersionRef.current;
274
+ const currentList = sessionListRef.current;
275
+ const { next: removedList, removed, index: removedIndex } = removeSessionById(currentList, sessionId);
276
+ if (!removed || removedIndex < 0)
277
+ return false;
278
+ pendingDeletedIdsRef.current.add(sessionId);
279
+ deleteRequestVersionsRef.current.set(sessionId, requestId);
280
+ const activeSession = refs.sessionRef.current?.sessionId === sessionId
281
+ ? refs.sessionRef.current
282
+ : null;
283
+ const activeWorkspaceId = activeSession?.workspaceId ?? workspaceId;
284
+ const deletingRow = {
285
+ ...removed,
286
+ optimisticState: "deleting",
287
+ };
288
+ const deletingList = restoreSessionAt(removedList, deletingRow, removedIndex);
289
+ sessionListRef.current = deletingList;
290
+ setSessionList(deletingList);
291
+ window.setTimeout(() => {
292
+ if (!pendingDeletedIdsRef.current.has(sessionId) ||
293
+ deleteRequestVersionsRef.current.get(sessionId) !== requestId)
294
+ return;
295
+ const next = sessionListRef.current.filter((item) => item.sessionId !== sessionId);
296
+ sessionListRef.current = next;
297
+ setSessionList(next);
298
+ }, 150);
299
+ const restore = () => {
300
+ if (deleteRequestVersionsRef.current.get(sessionId) !== requestId)
301
+ return;
302
+ pendingDeletedIdsRef.current.delete(sessionId);
303
+ deleteRequestVersionsRef.current.delete(sessionId);
304
+ const restored = restoreSessionAt(sessionListRef.current, removed, removedIndex);
305
+ if (restored === sessionListRef.current)
306
+ return;
307
+ sessionListRef.current = restored;
308
+ setSessionList(restored);
309
+ };
310
+ let deletionSelectionVersion = null;
311
+ if (activeSession) {
312
+ deletionSelectionVersion = ++sessionSelectionVersionRef.current;
313
+ refs.sessionRef.current = null;
314
+ resetActiveProjection();
315
+ setSession(null);
316
+ forgetActiveChatSession(window.localStorage, activeWorkspaceId, sessionId);
317
+ }
318
+ const restoreActiveSession = async () => {
319
+ if (activeSession &&
320
+ deletionSelectionVersion === sessionSelectionVersionRef.current &&
321
+ !refs.sessionRef.current) {
322
+ await activateSessionRef.current?.(activeSession.sessionId, activeSession.workspaceId);
323
+ }
324
+ };
152
325
  try {
153
- const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(sessionId)}`, {
326
+ // AC-002: delete follows the session's durable owner, not the
327
+ // global active workspace.
328
+ const ownerQuery = sessionOwnerQuery(sessionListRef.current.find((item) => item.sessionId === sessionId)
329
+ ?.workspaceId ?? null);
330
+ const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(sessionId)}${ownerQuery}`, {
154
331
  method: "DELETE",
155
332
  credentials: "include",
156
333
  headers: {
@@ -158,21 +335,21 @@ export function useChatSessions(params) {
158
335
  },
159
336
  });
160
337
  if (!res.ok) {
338
+ restore();
339
+ await restoreActiveSession();
161
340
  setError("删除会话失败");
162
341
  return false;
163
342
  }
164
343
  titleWatcherRef.current?.cancel(sessionId);
165
- if (refs.sessionRef.current?.sessionId === sessionId) {
166
- sessionSelectionVersionRef.current += 1;
167
- refs.sessionRef.current = null;
168
- resetActiveProjection();
169
- setSession(null);
170
- window.localStorage.removeItem(ACTIVE_CHAT_SESSION_STORAGE_KEY);
171
- }
172
- await refreshSessionList();
344
+ void refreshSessionList().finally(() => {
345
+ pendingDeletedIdsRef.current.delete(sessionId);
346
+ deleteRequestVersionsRef.current.delete(sessionId);
347
+ });
173
348
  return true;
174
349
  }
175
350
  catch (error) {
351
+ restore();
352
+ await restoreActiveSession();
176
353
  setError(error instanceof Error ? error.message : String(error));
177
354
  return false;
178
355
  }
@@ -183,24 +360,67 @@ export function useChatSessions(params) {
183
360
  resetActiveProjection,
184
361
  refreshSessionList,
185
362
  setError,
363
+ sessionOwnerQuery,
364
+ workspaceId,
186
365
  ]);
187
- const activateSession = useCallback(async (sessionId) => {
366
+ const forgetLostSession = useCallback((sessionId, ownerWorkspaceId) => {
367
+ const active = refs.sessionRef.current;
368
+ const listed = sessionListRef.current.find((item) => item.sessionId === sessionId);
369
+ const scope = ownerWorkspaceId ?? listed?.workspaceId ?? active?.workspaceId ?? workspaceId;
370
+ forgetActiveChatSession(window.localStorage, scope, sessionId);
371
+ pendingDeletedIdsRef.current.add(sessionId);
372
+ const { next } = removeSessionById(sessionListRef.current, sessionId);
373
+ sessionListRef.current = next;
374
+ setSessionList(next);
375
+ if (active?.sessionId === sessionId) {
376
+ sessionSelectionVersionRef.current += 1;
377
+ refs.sessionRef.current = null;
378
+ resetActiveProjection();
379
+ setSession(null);
380
+ }
381
+ void refreshSessionList();
382
+ }, [refs, resetActiveProjection, setSession, workspaceId, refreshSessionList]);
383
+ const activateSession = useCallback(async (sessionId, ownerWorkspaceId) => {
188
384
  const selectionVersion = ++sessionSelectionVersionRef.current;
385
+ // AC-002: activation targets the session's durable owning workspace —
386
+ // never the global active workspace (no cross-workspace leak when
387
+ // Operate/Inspect switch their scope while a session stays open).
388
+ const ownerQuery = sessionOwnerQuery(ownerWorkspaceId);
189
389
  try {
190
- const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(sessionId)}`, { credentials: "include" });
390
+ const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(sessionId)}${ownerQuery}`, { credentials: "include" });
191
391
  const body = (await res.json());
192
- if (!res.ok || !body.session)
392
+ if (!res.ok || !body.session) {
393
+ if (isLostChatSessionError({
394
+ status: res.status,
395
+ code: body.error?.code,
396
+ message: body.error?.message,
397
+ })) {
398
+ forgetLostSession(sessionId, ownerWorkspaceId);
399
+ return false;
400
+ }
193
401
  throw new Error(body.error?.message ?? "会话不可用");
402
+ }
194
403
  if (selectionVersion !== sessionSelectionVersionRef.current)
195
- return;
404
+ return false;
196
405
  const next = {
197
406
  sessionId: body.session.sessionId,
407
+ ...(body.session.workspaceId ? { workspaceId: body.session.workspaceId } : {}),
198
408
  ...runtimeSelectionFromRecord(body.session),
199
409
  };
200
- resetActiveProjection();
410
+ // AC-002: session switch (same or cross workspace) never aborts other
411
+ // sessions' background request controllers; the single /events owner is
412
+ // re-bound by useChatStream's session effect.
413
+ resetActiveProjection({ keepStreams: true });
201
414
  refs.sessionRef.current = next;
202
- refs.streamingRef.current = Boolean(body.session.activeTurnId);
203
415
  refs.activeTurnIdRef.current = body.session.activeTurnId ?? null;
416
+ const visuallyStopped = body.session.turnPhase === "stopping";
417
+ refs.streamingRef.current = visuallyStopped
418
+ ? false
419
+ : Boolean(body.session.activeTurnId);
420
+ refs.stoppingTurnIdRef.current = visuallyStopped
421
+ ? (body.session.activeTurnId ?? null)
422
+ : null;
423
+ refs.stopRequestedRef.current = visuallyStopped;
204
424
  refs.seenEventIdsRef.current = new Set();
205
425
  refs.turnAssistantIdsRef.current = new Map();
206
426
  refs.sealedAssistantIdsRef.current = new Set();
@@ -214,18 +434,32 @@ export function useChatSessions(params) {
214
434
  setPreviews([]);
215
435
  setInput(body.session.composerDraft ?? "");
216
436
  const hydrated = hydrateSessionThread(body.session.messages ?? []);
437
+ hydrated.messages = mergeCompactionMessages(hydrated.messages, body.compactions);
217
438
  applyActivatedSession({
218
439
  messages: hydrated.messages,
219
440
  toolCalls: hydrated.toolCalls,
220
- streaming: Boolean(body.session.activeTurnId),
441
+ sessionStats: body.sessionStats,
442
+ usage: body.usage,
443
+ turnTelemetry: body.turnTelemetry,
444
+ streaming: visuallyStopped ? false : Boolean(body.session.activeTurnId),
445
+ turnPhase: body.session.turnPhase ??
446
+ (body.session.activeTurnId ? "running" : "idle"),
447
+ deferredTurn: body.session.deferredTurn ?? null,
448
+ deferredTurns: body.session.deferredTurns ?? (body.session.deferredTurn ? [body.session.deferredTurn] : []),
449
+ pendingQuestion: body.session.pendingQuestion ?? null,
450
+ todos: body.session.todos ?? [],
451
+ goal: body.session.goal ?? null,
452
+ history: body.history,
221
453
  });
222
- window.localStorage.setItem(ACTIVE_CHAT_SESSION_STORAGE_KEY, sessionId);
454
+ rememberActiveChatSession(window.localStorage, body.session.workspaceId ?? ownerWorkspaceId ?? workspaceId, sessionId);
223
455
  setActivePreviewPath(null);
456
+ return true;
224
457
  }
225
458
  catch (error) {
226
459
  if (selectionVersion !== sessionSelectionVersionRef.current)
227
- return;
460
+ return false;
228
461
  setError(error instanceof Error ? error.message : String(error));
462
+ return false;
229
463
  }
230
464
  }, [
231
465
  origin,
@@ -238,7 +472,11 @@ export function useChatSessions(params) {
238
472
  resetActiveProjection,
239
473
  setActivePreviewPath,
240
474
  setError,
475
+ sessionOwnerQuery,
476
+ workspaceId,
477
+ forgetLostSession,
241
478
  ]);
479
+ activateSessionRef.current = activateSession;
242
480
  useEffect(() => {
243
481
  void refreshSessionList();
244
482
  }, [refreshSessionList]);
@@ -268,28 +506,45 @@ export function useChatSessions(params) {
268
506
  .map((item) => item.sessionId));
269
507
  }, [sessionList]);
270
508
  useEffect(() => () => titleWatcherRef.current?.dispose(), []);
271
- // Browser refresh recovery: retain only the durable session id locally, then
272
- // re-read messages and operation refs/facts from the server-owned stores.
509
+ // Browser refresh/workspace-switch recovery: selection is client state keyed
510
+ // by workspace; messages and operation refs/facts remain server-owned.
273
511
  useEffect(() => {
274
512
  let cancelled = false;
275
- const savedSessionId = window.localStorage.getItem(ACTIVE_CHAT_SESSION_STORAGE_KEY);
276
- if (!savedSessionId)
277
- return;
513
+ if (blocked)
514
+ return; // AC-R5-002: unknown workspace — no restore GET
278
515
  const selectionVersion = ++sessionSelectionVersionRef.current;
516
+ // Remove the old workspace projection immediately. Background session
517
+ // streams remain alive; only the visible selection is rebound below.
518
+ resetActiveProjection({ keepStreams: true });
519
+ refs.sessionRef.current = null;
520
+ setSession(null);
521
+ const savedSessionId = readActiveChatSessionId(window.localStorage, workspaceId);
522
+ if (!savedSessionId) {
523
+ // Keep the per-workspace map intact, but clear the legacy global pointer
524
+ // so Operate/Models cannot link a session from another workspace.
525
+ forgetActiveChatSession(window.localStorage, workspaceId);
526
+ return;
527
+ }
279
528
  void (async () => {
280
529
  try {
281
- const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(savedSessionId)}`, { credentials: "include" });
530
+ const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(savedSessionId)}${workspaceQuery}`, { credentials: "include" });
282
531
  if (!res.ok) {
283
- window.localStorage.removeItem(ACTIVE_CHAT_SESSION_STORAGE_KEY);
532
+ forgetActiveChatSession(window.localStorage, workspaceId, savedSessionId);
284
533
  return;
285
534
  }
286
535
  const body = (await res.json());
287
536
  if (cancelled ||
537
+ blocked ||
288
538
  selectionVersion !== sessionSelectionVersionRef.current ||
289
539
  !body.session)
290
540
  return;
291
541
  const restored = {
292
542
  sessionId: body.session.sessionId,
543
+ ...(body.session.workspaceId
544
+ ? { workspaceId: body.session.workspaceId }
545
+ : workspaceId
546
+ ? { workspaceId }
547
+ : {}),
293
548
  ...runtimeSelectionFromRecord(body.session),
294
549
  };
295
550
  refs.sessionGenerationRef.current += 1;
@@ -299,25 +554,40 @@ export function useChatSessions(params) {
299
554
  // in the event ring and must replay once. applySseBlock dedups by
300
555
  // eventId and marks replay so usage/unread/sound do not double-count.
301
556
  refs.activeTurnIdRef.current = body.session.activeTurnId ?? null;
557
+ const visuallyStopped = body.session.turnPhase === "stopping";
558
+ refs.streamingRef.current = visuallyStopped
559
+ ? false
560
+ : Boolean(body.session.activeTurnId);
561
+ refs.stoppingTurnIdRef.current = visuallyStopped
562
+ ? (body.session.activeTurnId ?? null)
563
+ : null;
564
+ refs.stopRequestedRef.current = visuallyStopped;
302
565
  refs.seenEventIdsRef.current = new Set();
303
566
  refs.turnAssistantIdsRef.current = new Map();
304
567
  refs.sealedAssistantIdsRef.current = new Set();
305
568
  refs.settledTurnIdsRef.current = new Set();
306
569
  refs.lastEventIdRef.current = null;
307
570
  setSession(restored);
571
+ rememberActiveChatSession(window.localStorage, restored.workspaceId ?? workspaceId, restored.sessionId);
308
572
  setInput(body.session.composerDraft ?? "");
309
- setMessages((body.session.messages ?? [])
310
- .filter((message) => message.role === "user" || message.role === "assistant")
311
- .map((message) => {
312
- const content = parseAssistantContent(message.content);
313
- return {
314
- id: message.id,
315
- role: message.role,
316
- text: message.text,
317
- createdAt: Date.parse(message.at) || Date.now(),
318
- ...(content && content.length > 0 ? { content } : {}),
319
- };
320
- }));
573
+ const hydrated = hydrateSessionThread(body.session.messages ?? []);
574
+ hydrated.messages = mergeCompactionMessages(hydrated.messages, body.compactions);
575
+ applyActivatedSession({
576
+ messages: hydrated.messages,
577
+ toolCalls: hydrated.toolCalls,
578
+ sessionStats: body.sessionStats,
579
+ usage: body.usage,
580
+ turnTelemetry: body.turnTelemetry,
581
+ streaming: visuallyStopped ? false : Boolean(body.session.activeTurnId),
582
+ turnPhase: body.session.turnPhase ??
583
+ (body.session.activeTurnId ? "running" : "idle"),
584
+ deferredTurn: body.session.deferredTurn ?? null,
585
+ deferredTurns: body.session.deferredTurns ?? (body.session.deferredTurn ? [body.session.deferredTurn] : []),
586
+ pendingQuestion: body.session.pendingQuestion ?? null,
587
+ todos: body.session.todos ?? [],
588
+ goal: body.session.goal ?? null,
589
+ history: body.history,
590
+ });
321
591
  }
322
592
  catch {
323
593
  // Recovery is best-effort; a new session remains available.
@@ -326,41 +596,115 @@ export function useChatSessions(params) {
326
596
  return () => {
327
597
  cancelled = true;
328
598
  };
329
- }, [origin, refs, setSession, setInput, setMessages]);
599
+ }, [
600
+ origin,
601
+ workspaceQuery,
602
+ refs,
603
+ setSession,
604
+ setInput,
605
+ applyActivatedSession,
606
+ blocked,
607
+ resetActiveProjection,
608
+ workspaceId,
609
+ ]);
330
610
  // The sole production create path delegates to the exported orchestration
331
611
  // helper so its durable commit order is directly traceable and testable.
332
- const createSessionAndPrimeTitleWatcherForHook = useCallback((options) => createSessionAndPrimeTitleWatcher({
333
- origin,
334
- sessionListRef,
335
- setSessionList,
336
- titleWatcher: titleWatcherRef.current,
337
- refreshSessionList,
338
- options,
339
- setCreatingSession,
340
- creatingRef: creatingSessionRef,
341
- }), [origin, refreshSessionList]);
612
+ // AC-003 (2026-08-26): session creation REQUIRES a known workspaceId —
613
+ // either explicit (sidebar create-in-workspace) or the current valid
614
+ // selection. No scope → fail closed client-side (the server would reject
615
+ // with WORKSPACE_REQUIRED anyway); never a default-workspace fallback.
616
+ const createSessionAndPrimeTitleWatcherForHook = useCallback((options) => {
617
+ const scope = options?.workspaceId?.trim() ?? workspaceId?.trim();
618
+ if (!scope) {
619
+ setError("创建会话需要选择一个有效的工作区(不会回退默认工作区)");
620
+ return Promise.reject(new Error("WORKSPACE_REQUIRED"));
621
+ }
622
+ const optimisticSessionId = `optimistic-chat-${Date.now()}-${Math.random().toString(16).slice(2)}`;
623
+ const now = new Date().toISOString();
624
+ const optimisticRow = {
625
+ sessionId: optimisticSessionId,
626
+ workspaceId: scope,
627
+ state: "active",
628
+ updatedAt: now,
629
+ turnPhase: "idle",
630
+ optimisticState: "creating",
631
+ };
632
+ pendingCreatedRowsRef.current.set(optimisticSessionId, optimisticRow);
633
+ const optimisticList = insertOptimisticSession(sessionListRef.current, optimisticRow);
634
+ sessionListRef.current = optimisticList;
635
+ setSessionList(optimisticList);
636
+ return createSessionAndPrimeTitleWatcher({
637
+ origin,
638
+ sessionListRef,
639
+ setSessionList,
640
+ titleWatcher: titleWatcherRef.current,
641
+ refreshSessionList,
642
+ options: { ...options, workspaceId: scope, optimisticSessionId },
643
+ setCreatingSession,
644
+ creatingRef: creatingSessionRef,
645
+ }).then((created) => {
646
+ pendingCreatedRowsRef.current.delete(optimisticSessionId);
647
+ return created;
648
+ }).catch((error) => {
649
+ pendingCreatedRowsRef.current.delete(optimisticSessionId);
650
+ const cleaned = sessionListRef.current.filter((item) => item.sessionId !== optimisticSessionId);
651
+ sessionListRef.current = cleaned;
652
+ setSessionList(cleaned);
653
+ throw error;
654
+ });
655
+ }, [origin, refreshSessionList, workspaceId, setError]);
342
656
  const createSession = useCallback(async (options) => {
343
657
  // Suppress concurrent create from any entry (sidebar / Landing / chip).
344
658
  if (creatingSessionRef.current)
345
659
  return null;
660
+ if (blocked)
661
+ return null; // AC-R5-002: unknown workspace — no POST
346
662
  const selectionVersion = ++sessionSelectionVersionRef.current;
347
663
  setError(null);
664
+ const previousSession = refs.sessionRef.current;
665
+ const scope = options?.workspaceId?.trim() ?? workspaceId?.trim();
666
+ if (!scope) {
667
+ setError("创建会话需要选择一个有效的工作区(不会回退默认工作区)");
668
+ return null;
669
+ }
670
+ // A caller-provided snapshot is an explicit new-session boundary; reusing
671
+ // an existing shell would silently drop that context suffix.
672
+ const reusable = options?.snapshot
673
+ ? undefined
674
+ : findReusableBlankSession(sessionListRef.current, scope);
675
+ if (reusable) {
676
+ if (previousSession?.sessionId === reusable.sessionId)
677
+ return previousSession;
678
+ const activated = await activateSession(reusable.sessionId, reusable.workspaceId);
679
+ if (!activated)
680
+ return null;
681
+ return {
682
+ sessionId: reusable.sessionId,
683
+ ...(reusable.workspaceId ? { workspaceId: reusable.workspaceId } : {}),
684
+ ...runtimeSelectionFromRecord(reusable),
685
+ };
686
+ }
348
687
  try {
688
+ resetActiveProjection({ keepStreams: true });
689
+ refs.sessionRef.current = null;
690
+ setSession(null);
349
691
  const created = await createSessionAndPrimeTitleWatcherForHook(options);
350
692
  if (selectionVersion !== sessionSelectionVersionRef.current)
351
693
  return null;
352
- resetActiveProjection();
353
694
  // Set ref synchronously BEFORE setState so a chained
354
695
  // createSession().then(sendPrompt) reads the new session even
355
696
  // though sendPrompt's closure captured the stale (null) value.
356
697
  refs.sessionRef.current = created;
357
- window.localStorage.setItem(ACTIVE_CHAT_SESSION_STORAGE_KEY, created.sessionId);
698
+ rememberActiveChatSession(window.localStorage, created.workspaceId ?? options?.workspaceId ?? workspaceId, created.sessionId);
358
699
  setSession(created);
359
700
  return created;
360
701
  }
361
702
  catch (e) {
362
703
  if (selectionVersion !== sessionSelectionVersionRef.current)
363
704
  return null;
705
+ if (previousSession) {
706
+ await activateSession(previousSession.sessionId, previousSession.workspaceId);
707
+ }
364
708
  const message = e instanceof Error ? e.message : String(e);
365
709
  if (message !== "CREATE_SESSION_IN_FLIGHT") {
366
710
  setError(message);
@@ -373,6 +717,9 @@ export function useChatSessions(params) {
373
717
  setError,
374
718
  resetActiveProjection,
375
719
  createSessionAndPrimeTitleWatcherForHook,
720
+ activateSession,
721
+ blocked,
722
+ workspaceId,
376
723
  ]);
377
724
  // Phase-1: fork / in-session branch / mainline switch UI deferred; API routes remain.
378
725
  /** Single compact helper for toolbar + `/compact <instructions>` (AC-1). */
@@ -389,7 +736,8 @@ export function useChatSessions(params) {
389
736
  if (trimmed) {
390
737
  headers["content-type"] = "application/json";
391
738
  }
392
- const response = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(current.sessionId)}/compact`, {
739
+ // AC-002: compaction follows the session's durable owner.
740
+ const response = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(current.sessionId)}/compact${sessionOwnerQuery()}`, {
393
741
  method: "POST",
394
742
  credentials: "include",
395
743
  headers,
@@ -418,22 +766,8 @@ export function useChatSessions(params) {
418
766
  // pi-web parity: reload the compacted session, then leave a distinct
419
767
  // compaction summary card in the timeline plus a transient toast.
420
768
  const summary = body.snapshot?.summary?.trim();
421
- const tokensBefore = body.snapshot?.tokensBefore;
422
769
  const summaryText = summary || "历史上下文已精简,关键决策与当前任务已保留。";
423
770
  await activateSession(current.sessionId);
424
- setMessages((messages) => [
425
- ...messages,
426
- {
427
- id: `compaction-${Date.now()}`,
428
- role: "assistant",
429
- kind: "compaction",
430
- text: summaryText,
431
- createdAt: Date.now(),
432
- ...(tokensBefore
433
- ? { compaction: { tokensBefore } }
434
- : {}),
435
- },
436
- ]);
437
771
  setNotice({
438
772
  id: Date.now(),
439
773
  message: `已压缩上下文:${summaryText.slice(0, 72)}${summaryText.length > 72 ? "…" : ""}`,
@@ -450,12 +784,14 @@ export function useChatSessions(params) {
450
784
  refs,
451
785
  setError,
452
786
  setNotice,
453
- setMessages,
454
787
  onCompactionChange,
455
788
  activateSession,
789
+ sessionOwnerQuery,
456
790
  ]);
457
791
  const updateSession = async (sessionId, patch) => {
458
- const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(sessionId)}`, {
792
+ // AC-002: rename/archive follows the session's durable owner.
793
+ const res = await fetch(`${origin}/api/operator/v1/chat/sessions/${encodeURIComponent(sessionId)}${sessionOwnerQuery(sessionListRef.current.find((item) => item.sessionId === sessionId)
794
+ ?.workspaceId ?? null)}`, {
459
795
  method: "PATCH",
460
796
  credentials: "include",
461
797
  headers: {
@@ -474,11 +810,13 @@ export function useChatSessions(params) {
474
810
  }
475
811
  if (patch.state === "archived" &&
476
812
  refs.sessionRef.current?.sessionId === sessionId) {
813
+ const activeWorkspaceId = refs.sessionRef.current.workspaceId ?? workspaceId;
814
+ const activeSessionId = refs.sessionRef.current.sessionId;
477
815
  sessionSelectionVersionRef.current += 1;
478
816
  refs.sessionRef.current = null;
479
817
  resetActiveProjection();
480
818
  setSession(null);
481
- window.localStorage.removeItem(ACTIVE_CHAT_SESSION_STORAGE_KEY);
819
+ forgetActiveChatSession(window.localStorage, activeWorkspaceId, activeSessionId);
482
820
  }
483
821
  };
484
822
  return {
@@ -491,5 +829,6 @@ export function useChatSessions(params) {
491
829
  updateSession,
492
830
  watchSessionTitle,
493
831
  compactSession,
832
+ forgetLostSession,
494
833
  };
495
834
  }