@kabmo-labs/kabmo 0.24.0 → 0.26.0

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 (325) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +585 -512
  3. package/dist/client/static/js/{index-jcr5twtp.js → index-95b3n20k.js} +1105 -1207
  4. package/dist/client/static/js/index-p2yw9ywf.css +1 -0
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  13. package/src/client/components/common/code-surface/shiki.ts +28 -7
  14. package/src/client/components/common/session-actions-menu/index.tsx +59 -2
  15. package/src/client/components/common/session-branch/BranchGuides.tsx +93 -0
  16. package/src/client/components/common/session-branch/SubagentRow.tsx +77 -0
  17. package/src/client/components/common/session-branch/index.tsx +169 -0
  18. package/src/client/components/common/session-branch/session-branch.test.tsx +240 -0
  19. package/src/client/components/common/session-branch/style.ts +29 -0
  20. package/src/client/components/common/session-row/StatusSlot.tsx +17 -5
  21. package/src/client/components/common/session-row/index.tsx +28 -3
  22. package/src/client/components/common/session-row/session-row.test.tsx +11 -0
  23. package/src/client/components/common/session-state-provider/index.tsx +1 -1
  24. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  25. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +70 -61
  26. package/src/client/components/layout/session-sidebar/SessionItem.batch.test.ts +3 -3
  27. package/src/client/components/layout/session-sidebar/SessionItem.test.ts +25 -2
  28. package/src/client/components/layout/session-sidebar/SessionItem.tsx +35 -7
  29. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +261 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +39 -198
  31. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +114 -0
  32. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  33. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +128 -0
  34. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +56 -0
  35. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +44 -36
  36. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +62 -47
  37. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +63 -50
  38. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +5 -0
  39. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +37 -12
  40. package/src/client/components/settings/Sidebar.tsx +1 -1
  41. package/src/client/components/settings/categories/NotificationSettings.test.tsx +92 -0
  42. package/src/client/components/settings/categories/NotificationSettings.tsx +112 -2
  43. package/src/client/components/settings/categories/harness-settings/HarnessCard.tsx +1 -1
  44. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +94 -0
  45. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +31 -5
  46. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  47. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  48. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +128 -122
  49. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  50. package/src/client/components/workspace/chat-timeline/MessageList.tsx +11 -5
  51. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +10 -0
  52. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +12 -3
  53. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  54. package/src/client/components/workspace/chat-timeline/chat-input/AttachmentToolbar.tsx +2 -0
  55. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.tsx +15 -1
  56. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +85 -0
  57. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +84 -0
  58. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +2 -0
  59. package/src/client/components/workspace/chat-timeline/chat-input/modes-props.ts +5 -0
  60. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  61. package/src/client/components/workspace/chat-timeline/index.tsx +11 -20
  62. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +115 -0
  63. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +173 -0
  64. package/src/client/components/workspace/chat-timeline/target-picker/parent-session-options.test.ts +49 -0
  65. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  66. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  67. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  68. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  69. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  70. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  71. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  72. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  73. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  74. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  75. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  76. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  77. package/src/client/data/settings/omp-schema.json +1 -1
  78. package/src/client/data/theme/terminal.test.ts +25 -0
  79. package/src/client/data/theme/terminal.ts +96 -79
  80. package/src/client/hooks/chat/composer/items.test.ts +31 -26
  81. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  82. package/src/client/hooks/chat/omp/folder-auto-expand.ts +1 -1
  83. package/src/client/hooks/chat/omp/pending-adoption.ts +51 -0
  84. package/src/client/hooks/chat/omp/pending-child.test.ts +73 -0
  85. package/src/client/hooks/chat/omp/pending-entry.ts +59 -0
  86. package/src/client/hooks/chat/omp/pending-rows.ts +6 -2
  87. package/src/client/hooks/chat/omp/pending-sessions.test.ts +1 -2
  88. package/src/client/hooks/chat/omp/pending-sessions.ts +45 -69
  89. package/src/client/hooks/chat/omp/pending-waiting.ts +1 -1
  90. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  91. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  92. package/src/client/hooks/chat/omp/run-switch.ts +1 -1
  93. package/src/client/hooks/chat/omp/session-list.tsx +4 -0
  94. package/src/client/hooks/chat/subagents/roster.ts +122 -0
  95. package/src/client/hooks/chat/timeline/child-spawn.test.ts +55 -0
  96. package/src/client/hooks/chat/timeline/child-spawn.ts +45 -0
  97. package/src/client/hooks/chat/timeline/fork-request.test.ts +54 -0
  98. package/src/client/hooks/chat/timeline/fork-request.ts +43 -0
  99. package/src/client/hooks/chat/timeline/mode-availability.test.ts +1 -1
  100. package/src/client/hooks/chat/timeline/mode-availability.ts +33 -0
  101. package/src/client/hooks/chat/timeline/mode-markers.ts +7 -1
  102. package/src/client/hooks/chat/timeline/mode-post.ts +15 -3
  103. package/src/client/hooks/chat/timeline/modes-contract.ts +9 -4
  104. package/src/client/hooks/chat/timeline/modes.test.ts +56 -18
  105. package/src/client/hooks/chat/timeline/modes.ts +42 -29
  106. package/src/client/hooks/chat/timeline/pending-branch.ts +205 -0
  107. package/src/client/hooks/chat/timeline/pending-dispatch.ts +253 -0
  108. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  109. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  110. package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
  111. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  112. package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
  113. package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
  114. package/src/client/hooks/chat/timeline/send.test.ts +3 -1
  115. package/src/client/hooks/chat/timeline/send.ts +48 -133
  116. package/src/client/hooks/chat/timeline/session-harness.ts +6 -0
  117. package/src/client/hooks/chat/timeline/stop-with-queue.ts +42 -0
  118. package/src/client/hooks/chat/timeline/use-fork-session.ts +58 -0
  119. package/src/client/hooks/models/use-harness-update.test.ts +286 -0
  120. package/src/client/hooks/models/use-harness-update.ts +250 -0
  121. package/src/client/hooks/ui/input-required-alert.ts +12 -5
  122. package/src/client/hooks/ui/notifications.ts +45 -0
  123. package/src/client/hooks/ui/run-outcome-alert.ts +48 -0
  124. package/src/client/hooks/workspace/expanded-sessions.ts +36 -7
  125. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  126. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  127. package/src/client/lib/native/open-session.ts +33 -0
  128. package/src/client/lib/notifications/os.test.ts +125 -0
  129. package/src/client/lib/notifications/os.ts +130 -0
  130. package/src/client/lib/plugins/sidebar-bridge.ts +2 -20
  131. package/src/client/lib/router/open-session.test.ts +75 -0
  132. package/src/client/lib/router/open-session.ts +34 -0
  133. package/src/client/lib/session-tree.test.ts +50 -0
  134. package/src/client/lib/session-tree.ts +59 -0
  135. package/src/client/lib/signals.ts +5 -1
  136. package/src/client/main.tsx +6 -0
  137. package/src/client/tailwind.css +17 -11
  138. package/src/server/index.ts +2 -0
  139. package/src/server/lib/auth/guard.ts +10 -0
  140. package/src/server/lib/btw/session-copy.server.ts +6 -44
  141. package/src/server/lib/btw/session-copy.test.ts +2 -1
  142. package/src/server/lib/db/schema.ts +5 -0
  143. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  144. package/src/server/lib/db/seed.test.ts +1 -1
  145. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  146. package/src/server/lib/harness/acp/background-work.ts +320 -0
  147. package/src/server/lib/harness/acp/calls.ts +15 -1
  148. package/src/server/lib/harness/acp/client-capabilities.test.ts +55 -0
  149. package/src/server/lib/harness/acp/client-capabilities.ts +61 -0
  150. package/src/server/lib/harness/acp/client-fs.test.ts +135 -0
  151. package/src/server/lib/harness/acp/client-fs.ts +131 -0
  152. package/src/server/lib/harness/acp/client-initialize.test.ts +70 -0
  153. package/src/server/lib/harness/acp/client-initialize.ts +84 -0
  154. package/src/server/lib/harness/acp/client.ts +33 -23
  155. package/src/server/lib/harness/acp/commands.test.ts +5 -5
  156. package/src/server/lib/harness/acp/commands.ts +14 -2
  157. package/src/server/lib/harness/acp/frames-timing.test.ts +68 -0
  158. package/src/server/lib/harness/acp/frames-v2.test.ts +85 -0
  159. package/src/server/lib/harness/acp/frames.ts +71 -158
  160. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  161. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  162. package/src/server/lib/harness/acp/mapper.test.ts +40 -0
  163. package/src/server/lib/harness/acp/mapper.ts +12 -0
  164. package/src/server/lib/harness/acp/permissions.ts +6 -0
  165. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  166. package/src/server/lib/harness/acp/prompt.ts +19 -3
  167. package/src/server/lib/harness/acp/protocol.ts +41 -2
  168. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  169. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  170. package/src/server/lib/harness/acp/session-facts.ts +1 -1
  171. package/src/server/lib/harness/acp/session-handshake.test.ts +197 -0
  172. package/src/server/lib/harness/acp/session-handshake.ts +110 -7
  173. package/src/server/lib/harness/acp/session-idle.ts +7 -6
  174. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  175. package/src/server/lib/harness/acp/session-notifications.ts +41 -2
  176. package/src/server/lib/harness/acp/session-observers.test.ts +63 -0
  177. package/src/server/lib/harness/acp/session-permissions.test.ts +29 -0
  178. package/src/server/lib/harness/acp/session-permissions.ts +36 -0
  179. package/src/server/lib/harness/acp/session-requests.test.ts +92 -0
  180. package/src/server/lib/harness/acp/session-requests.ts +89 -0
  181. package/src/server/lib/harness/acp/session-turns.ts +28 -8
  182. package/src/server/lib/harness/acp/session-usage.ts +4 -0
  183. package/src/server/lib/harness/acp/session-web-state.ts +30 -2
  184. package/src/server/lib/harness/acp/session.test-util.ts +42 -2
  185. package/src/server/lib/harness/acp/session.ts +115 -115
  186. package/src/server/lib/harness/acp/tool-calls.ts +223 -0
  187. package/src/server/lib/harness/acp/turn.test.ts +183 -0
  188. package/src/server/lib/harness/acp/turn.ts +102 -10
  189. package/src/server/lib/harness/acp/v2.test.ts +144 -0
  190. package/src/server/lib/harness/acp/v2.ts +220 -0
  191. package/src/server/lib/harness/acp/verbs.ts +58 -8
  192. package/src/server/lib/harness/launch.test.ts +25 -0
  193. package/src/server/lib/harness/launch.ts +24 -10
  194. package/src/server/lib/harness/session.ts +3 -0
  195. package/src/server/lib/harness/spawn.server.ts +15 -2
  196. package/src/server/lib/harness/update-job-store.test.ts +151 -0
  197. package/src/server/lib/harness/update-job-store.ts +115 -0
  198. package/src/server/lib/harness/update-job.server.ts +94 -0
  199. package/src/server/lib/harness/update-queue.server.ts +292 -0
  200. package/src/server/lib/harness/update-queue.test.ts +265 -0
  201. package/src/server/lib/harness/update-spawn.server.ts +96 -0
  202. package/src/server/lib/harness/update-worker.test.ts +153 -0
  203. package/src/server/lib/harness/update-worker.ts +202 -0
  204. package/src/server/lib/lifecycle/after-listen.ts +9 -0
  205. package/src/server/lib/lifecycle/paths.ts +28 -0
  206. package/src/server/lib/omp/rpc/manager.ts +5 -5
  207. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  208. package/src/server/lib/omp/rpc/run-settle.server.ts +10 -1
  209. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  210. package/src/server/lib/omp/rpc/subagent-liveness.ts +5 -5
  211. package/src/server/lib/omp/rpc/terminal-settle.ts +58 -6
  212. package/src/server/lib/omp/session/delete-flow.server.ts +48 -0
  213. package/src/server/lib/omp/session/delete.server.ts +5 -0
  214. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  215. package/src/server/lib/omp/session/sidebar-data.server.ts +16 -18
  216. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  217. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  218. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  219. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  220. package/src/server/lib/sessions/answers.server.ts +37 -0
  221. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  222. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  223. package/src/server/lib/sessions/fork.server.test.ts +277 -0
  224. package/src/server/lib/sessions/fork.server.ts +329 -0
  225. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  226. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  227. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  228. package/src/server/lib/sessions/notify.server.ts +212 -0
  229. package/src/server/lib/sessions/relation-types.ts +76 -0
  230. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  231. package/src/server/lib/sessions/relations.server.ts +337 -0
  232. package/src/server/lib/sessions/resolve.server.ts +106 -0
  233. package/src/server/lib/sessions/schema.server.ts +82 -0
  234. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  235. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  236. package/src/server/lib/sessions/spawn.server.test.ts +237 -0
  237. package/src/server/lib/sessions/spawn.server.ts +335 -0
  238. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  239. package/src/server/lib/terminal/output.test.ts +2 -2
  240. package/src/server/lib/terminal/output.ts +1 -1
  241. package/src/server/lib/terminal/resize.test.ts +99 -0
  242. package/src/server/lib/terminal/runtime.server.ts +26 -6
  243. package/src/server/lib/terminal/send-result.test.ts +18 -1
  244. package/src/server/lib/terminal/send-result.ts +26 -2
  245. package/src/server/lib/terminal/session.server.ts +6 -6
  246. package/src/server/lib/usage/new-api.test.ts +92 -0
  247. package/src/server/lib/usage/new-api.ts +131 -0
  248. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  249. package/src/server/lib/usage/provider-key.ts +33 -0
  250. package/src/server/lib/usage/providers.server.ts +10 -3
  251. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  252. package/src/server/lib/usage/vendor-http.ts +41 -0
  253. package/src/server/lib/usage/window.ts +55 -0
  254. package/src/server/routes/agent/command.ts +14 -1
  255. package/src/server/routes/agent/harness-command.ts +12 -5
  256. package/src/server/routes/agent/new.ts +15 -0
  257. package/src/server/routes/chat/stream.ts +7 -2
  258. package/src/server/routes/harness/add-provider.test.ts +9 -1
  259. package/src/server/routes/harness/import-action.ts +4 -0
  260. package/src/server/routes/harness/import.test.ts +1 -1
  261. package/src/server/routes/harness/index.ts +5 -1
  262. package/src/server/routes/harness/update-status.ts +32 -0
  263. package/src/server/routes/harness/update.test.ts +156 -0
  264. package/src/server/routes/harness/update.ts +64 -147
  265. package/src/server/routes/sessions/answer.ts +24 -0
  266. package/src/server/routes/sessions/batch-delete.ts +11 -5
  267. package/src/server/routes/sessions/body-readers.ts +43 -0
  268. package/src/server/routes/sessions/delete.ts +4 -2
  269. package/src/server/routes/sessions/fork.ts +89 -0
  270. package/src/server/routes/sessions/index.ts +14 -0
  271. package/src/server/routes/sessions/relations.ts +85 -0
  272. package/src/server/routes/sessions/routes.test.ts +1 -2
  273. package/src/server/routes/sessions/session.ts +23 -0
  274. package/src/server/routes/sessions/spawn.ts +137 -0
  275. package/src/server/routes/terminal/ws.ts +3 -3
  276. package/src/shared/lib/chat/composer/client.ts +31 -2
  277. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  278. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  279. package/src/shared/lib/chat/notice-text.ts +1 -1
  280. package/src/shared/lib/chat/omp/agent-events.ts +11 -0
  281. package/src/shared/lib/chat/omp/session-modes-signal.test.ts +41 -0
  282. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  283. package/src/shared/lib/code/ansi.ts +1 -1
  284. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  285. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  286. package/src/shared/lib/harness/mode-signal.ts +20 -0
  287. package/src/shared/lib/harness/provider-facts.test.ts +27 -0
  288. package/src/shared/lib/harness/providers.ts +35 -1
  289. package/src/shared/lib/harness/session-modes.ts +24 -0
  290. package/src/shared/lib/harness/update-job.ts +80 -0
  291. package/src/shared/lib/harness/update-plan.test.ts +21 -6
  292. package/src/shared/lib/harness/update-plan.ts +12 -4
  293. package/src/shared/lib/icons/tint-hues.generated.ts +34 -34
  294. package/src/shared/lib/notifications/outcomes.test.ts +96 -0
  295. package/src/shared/lib/notifications/outcomes.ts +64 -0
  296. package/src/shared/lib/notifications/settings.test.ts +49 -0
  297. package/src/shared/lib/notifications/settings.ts +34 -0
  298. package/src/shared/lib/omp/session/default-title.ts +5 -4
  299. package/src/shared/lib/omp/session/prewarm-misc.test.ts +3 -2
  300. package/src/shared/lib/omp/session/schema-migrations.ts +4 -0
  301. package/src/shared/lib/omp/session/stream-state.server.test.ts +19 -0
  302. package/src/shared/lib/omp/session/stream-state.server.ts +24 -4
  303. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  304. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  305. package/src/shared/lib/settings/defaults.ts +3 -0
  306. package/src/shared/lib/theme/catalog.test.ts +13 -9
  307. package/src/shared/lib/theme/color.test.ts +2 -2
  308. package/src/shared/lib/theme/color.ts +4 -4
  309. package/src/shared/lib/theme/theme.test.ts +1 -1
  310. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  311. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  312. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  313. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  314. package/src/shared/types/chat.ts +1 -1
  315. package/src/shared/types/harness-update.ts +89 -0
  316. package/src/shared/types/omp/agent.ts +19 -2
  317. package/src/shared/types/realtime.ts +2 -0
  318. package/src/shared/types/settings/state.ts +10 -0
  319. package/src/shared/types/workspace.ts +8 -0
  320. package/src/test-support/fake-omp-fork.ts +16 -2
  321. package/src/test-support/harness-table.test-util.ts +31 -1
  322. package/dist/client/static/js/index-z3w7n85q.css +0 -1
  323. package/src/client/components/common/subagent-list/index.tsx +0 -165
  324. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  325. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
@@ -15,12 +15,10 @@ import type { ChatTimelineSendDeps, ChatTimelineSendResult } from '@/client/hook
15
15
 
16
16
  export type { ChatTimelineSendDeps, ChatTimelineSendResult };
17
17
  import type { AgentImage, Attachment, PromptDispatchResult, QueuedMessageModel } from '@/shared/types';
18
- import { buildPromptText } from '@/client/hooks/chat/timeline/prompt-text';
19
18
  import { flushDeferredPick } from '@/client/hooks/chat/timeline/deferred-model';
20
- import { readTextAttachments } from '@/shared/lib/chat/attachments';
21
- import { buildOptimisticRows, collectImages, streamMockFallback } from '@/client/hooks/chat/timeline/send-helpers';
22
- import { adoptPendingSession, markPendingSessionSent } from '@/client/hooks/chat/omp/pending-sessions';
23
- import { recordSpawnHarness } from '@/client/hooks/chat/timeline/spawn-harness';
19
+ import { buildOptimisticRows, collectImages, assemblePrompt, streamMockFallback } from '@/client/hooks/chat/timeline/send-helpers';
20
+ import { markPendingSessionSent } from '@/client/hooks/chat/omp/pending-sessions';
21
+ import { dispatchPendingChat } from '@/client/hooks/chat/timeline/pending-dispatch';
24
22
  import { postModeCommand } from '@/client/hooks/chat/timeline/mode-post';
25
23
  import type { ArmedGoal } from '@/shared/lib/omp/mode/actions';
26
24
  import { blockTuiOnlySend } from '@/client/hooks/chat/timeline/tui-only-guard';
@@ -43,23 +41,18 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
43
41
  scrollToBottom,
44
42
  jumpToBottom,
45
43
  aiPlaceholderIdRef,
46
- adoptedSessionIdRef,
47
44
  optimisticUserIdRef,
48
45
  pendingUserDisplaysRef,
49
46
  seedSession,
50
47
  pendingComposerModelRef,
51
48
  pendingThinkingLevelRef,
52
- pendingHarnessRef,
53
49
  deferredComposerPickRef,
54
50
  accessModeRef,
55
- spawnSelectionRef,
56
51
  goalArmRef,
57
52
  disarmGoal,
58
- spawnWorktreeRef,
59
53
  abortControllerRef,
60
54
  setInputValue,
61
55
  reportActionError,
62
- setSearchParams,
63
56
  } = deps;
64
57
 
65
58
  // `@agent` mentions are omp's subagent syntax. An ACP harness has no such
@@ -67,24 +60,10 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
67
60
  const includeAgents = !harness || harness === 'omp-rpc' || harness === 'omp-acp';
68
61
 
69
62
  /**
70
- * Start the armed goal in `sessionId`, from the operator's own prompt.
71
- *
72
- * Awaited BEFORE the prompt leaves, so the order is a fact. Resolves TRUE when
73
- * the goal consumed the prompt — the caller must then not send it again.
74
- *
75
- * - `create` — the record is written with `startTurn: false`, and the prompt
76
- * that follows is the goal's first turn. The prompt is still sent.
77
- * - `guided` — there is no objective yet (the model writes it at the end of
78
- * the interview), so the operator's message IS the interview's opening
79
- * turn: the extension renders its kickoff prompt with their words folded
80
- * in (`<rough-goal>`) and runs that as turn one. The raw message is
81
- * therefore NOT sent separately — it is already inside that turn.
82
- *
83
- * A refusal is reported rather than swallowed, and the prompt still goes out
84
- * for `create`: the goal the operator set is missing, but their words are not
85
- * the goal's business. A refused `guided` cannot fall back the same way — the
86
- * interview kickoff is the extension's text — so it resolves false and the
87
- * caller sends the message as an ordinary prompt.
63
+ * Start the armed goal before the prompt leaves. `guided` folds the operator's
64
+ * words into the interview's opening turn (the caller must not send it again);
65
+ * `create` writes the record and lets the prompt be its first turn. A refusal
66
+ * is reported, and the prompt still goes out for `create`.
88
67
  */
89
68
  const startArmedGoal = useCallback(async (targetId: string, armed: ArmedGoal, promptText: string): Promise<boolean> => {
90
69
  const posted = armed.kind === 'guided'
@@ -114,11 +93,11 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
114
93
  text: string,
115
94
  attachments: Attachment[],
116
95
  ): Promise<{ promptText: string; images?: AgentImage[] }> => {
117
- const textFiles = await readTextAttachments(attachments);
118
- const promptText = await buildPromptText(text, textFiles, { includeAgents });
119
- pendingUserDisplaysRef.current = [...pendingUserDisplaysRef.current.slice(-7), { sent: promptText, display: text }];
120
- return { promptText, images: collectImages(attachments) };
121
- }, [includeAgents]);
96
+ const assembled = await assemblePrompt(text, attachments, includeAgents);
97
+ if (!assembled.ok) throw new Error(assembled.error);
98
+ pendingUserDisplaysRef.current = [...pendingUserDisplaysRef.current.slice(-7), { sent: assembled.promptText, display: text }];
99
+ return { promptText: assembled.promptText, images: collectImages(attachments) };
100
+ }, [includeAgents, pendingUserDisplaysRef]);
122
101
 
123
102
  // Steer the running omp agent (interrupt-and-reply). Returns the outcome so
124
103
  // the caller can report a refusal: the composer is cleared before this runs.
@@ -126,11 +105,19 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
126
105
  // A steer IS a new prompt: a pick made during the interrupted turn belongs
127
106
  // to it, so it is pushed before the interrupt-and-reply starts the turn.
128
107
  await flushDeferredPick(ompAgent, deferredComposerPickRef);
129
- const { promptText, images } = await prepareDeliverable(text, attachments);
130
- const result = await ompAgent.steerOmpRun(promptText, images);
108
+ let deliverable: { promptText: string; images?: AgentImage[] };
109
+ try {
110
+ deliverable = await prepareDeliverable(text, attachments);
111
+ } catch (error) {
112
+ const message = error instanceof Error ? error.message : String(error);
113
+ reportActionError(message);
114
+ setInputValue(text);
115
+ return { ok: false, busy: false, error: message };
116
+ }
117
+ const result = await ompAgent.steerOmpRun(deliverable.promptText, deliverable.images);
131
118
  if (!result.ok) setInputValue(text);
132
119
  return result;
133
- }, [ompAgent, prepareDeliverable, setInputValue, deferredComposerPickRef]);
120
+ }, [ompAgent, prepareDeliverable, setInputValue, deferredComposerPickRef, reportActionError]);
134
121
 
135
122
  const executeSend = useCallback(async (
136
123
  text: string,
@@ -151,12 +138,15 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
151
138
  const userMsgId = `msg-${Date.now()}-user`;
152
139
  const aiPlaceholderId = `msg-${Date.now() + 1}-ai`;
153
140
 
154
- // Read text-file contents once: used for the editor (attachment.content)
155
- // and for inlining into the prompt. Reads a persisted `content` when the
156
- // attachment is a replay (queue delivery, retry) and has no live File.
157
- const textFiles = await readTextAttachments(attachments);
141
+ // A delegation refusal (two harnesses in one paragraph, an unknown
142
+ // harness, an empty task) must land before any optimistic bubble exists.
143
+ const assembled = await assemblePrompt(text, attachments, includeAgents);
144
+ if (!assembled.ok) {
145
+ reportActionError(assembled.error);
146
+ return { ok: false, busy: false, error: assembled.error };
147
+ }
148
+ const { textFiles, promptText } = assembled;
158
149
  const textContentById = new Map(textFiles.map((file) => [file.id, file.content]));
159
-
160
150
  const now = Date.now();
161
151
  const { newUserMsg, initialAiMsg } = buildOptimisticRows({
162
152
  text,
@@ -214,13 +204,7 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
214
204
  }
215
205
  }
216
206
  const images = collectImages(attachments);
217
- // Inline text-file contents into the prompt: the model sees the full file
218
- // content as fenced blocks, not just the filename.
219
- const promptText = await buildPromptText(text, textFiles, { includeAgents });
220
- // The armed goal is created HERE, at the fence of the prompt that will be
221
- // its first turn — never earlier (nothing to act on) and never after the
222
- // prompt (the goal would miss its opening turn). An armed INTERVIEW
223
- // consumes this prompt as its kickoff, so nothing is sent after it.
207
+ // `promptText` was assembled once above, so no refusal can reach here.
224
208
  const armed = goalArmRef.current;
225
209
  const consumed = armed && sessionId ? await startArmedGoal(sessionId, armed, promptText) : false;
226
210
  if (consumed) return { ok: true, busy: false };
@@ -240,91 +224,22 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
240
224
  return result;
241
225
  }
242
226
 
243
- // No active session (fresh "New Session"): in real mode spawn a brand-new
244
- // omp session and adopt its id; fall back to the mock/simulated path only
245
- // when the spawn fails (e.g. MOCK=true or no workspace context).
246
- if (!isOmpSession) {
247
- const currentFolder = folders.find(f => String(f.id) === String(selectedFolderId));
248
- // A worktree pick wins: the chat is BORN there, so no relocation is ever
249
- // needed and the child's cwd is right for its whole life.
250
- const cwd = spawnWorktreeRef.current || currentFolder?.project_path || currentFolder?.name;
251
- if (cwd) {
252
- const images = collectImages(attachments);
253
- const promptText = await buildPromptText(text, textFiles, { includeAgents });
254
- optimisticUserIdRef.current = userMsgId;
255
- const composerModel = pendingComposerModelRef.current;
256
- const composerThinking = pendingThinkingLevelRef.current;
257
- // The mode picks made on the pending view ride the spawn. Read once,
258
- // here, and cleared below on success: a selection that outlived its
259
- // spawn would re-apply to the NEXT new session the user opens.
260
- const spawnModes = spawnSelectionRef.current;
261
- // An armed goal is recorded between the spawn and the prompt: the id
262
- // exists by then, and the prompt below is the goal's first turn. Not
263
- // after the prompt — a fast turn could finish before the record landed,
264
- // leaving a goal with no turn to act on.
265
- const armed = goalArmRef.current;
266
- const spawned = await ompAgent.sendNewPrompt(
227
+ // No active session (fresh "New Session"): a top-level chat or a pending
228
+ // child spawns its real session and adopts its id. `null` means the
229
+ // simulated path below owns it (no cwd, MOCK mode).
230
+ const pending = !isOmpSession
231
+ ? await dispatchPendingChat(deps, {
232
+ text,
233
+ attachments,
267
234
  promptText,
268
- cwd,
269
- images,
270
- {
271
- model: composerModel,
272
- thinkingLevel: composerThinking,
273
- accessMode: accessModeRef.current,
274
- modes: spawnModes,
275
- // A harness picked on the pending view rides the spawn; cleared on
276
- // success below so it cannot leak onto the next new chat. A New
277
- // Chat opened from an ACP answer passes the SOURCE chat's harness
278
- // explicitly (that dialog has no picker), and it must outrank the
279
- // ref a previous pick left behind.
280
- ...((options?.harness ?? pendingHarnessRef.current)
281
- ? { harness: options?.harness ?? pendingHarnessRef.current }
282
- : {}),
283
- },
284
- armed ? (id) => startArmedGoal(id, armed, promptText) : undefined,
285
- );
286
- if (spawned) {
287
- // The harness the SERVER answered with: `new.ts` reports it for an ACP
288
- // spawn and omits it for the RPC branch, which means omp. Read rather
289
- // than replayed from the request, so a pick the server did not honour
290
- // cannot be reported as the agent running the chat.
291
- recordSpawnHarness(spawned.sessionId, spawned.harness ?? 'omp-rpc');
292
- spawnSelectionRef.current = null;
293
- adoptedSessionIdRef.current = spawned.sessionId;
294
- // The sidebar's row moves with the id: `new-…` was the client's own
295
- // placeholder, and the spawn answers with omp's real one, which omp
296
- // has still not written a transcript for. Without this the row
297
- // vanished at exactly the moment the URL stopped naming the pending
298
- // id, which is the gap this store exists to close.
299
- adoptPendingSession(sessionId, spawned.sessionId, currentFolder?.id ?? null);
300
- // The placeholder ref is already armed (with its row) before the
301
- // spawn — see the note at the assignment; re-arming here would be
302
- // harmless but is redundant.
303
- // The spawn already applied this level to the session; seed it so the
304
- // composer taking over from the pending view reports the run's real
305
- // setting instead of a catalog default (the JSONL that carries it is
306
- // not locatable yet).
307
- seedSession({ model: spawned.model, thinkingLevel: composerThinking });
308
- pendingComposerModelRef.current = null;
309
- pendingThinkingLevelRef.current = null;
310
- pendingHarnessRef.current = null;
311
- fetch(`/api/chat/${encodeURIComponent(spawned.sessionId)}`, {
312
- method: 'POST',
313
- headers: { 'Content-Type': 'application/json' },
314
- body: JSON.stringify({ messages: [newUserMsg] }),
315
- }).catch(err => console.error('Error persisting spawned user turn:', err));
316
- setSearchParams(prev => {
317
- const next = new URLSearchParams(prev);
318
- next.set('sessionId', spawned.sessionId);
319
- return next;
320
- }, { replace: true });
321
- // The sidebar already re-read at prompt dispatch (sendNewPrompt
322
- // signals it), so the new session shows its live badge without
323
- // waiting for the JSONL to carry the user turn.
324
- return { ok: true, busy: false };
325
- }
326
- }
327
- }
235
+ userMsgId,
236
+ aiPlaceholderId,
237
+ newUserMsg,
238
+ ...(options ? { options } : {}),
239
+ startArmedGoal,
240
+ })
241
+ : null;
242
+ if (pending) return pending;
328
243
 
329
244
  // Mock / Kabmo-created session: existing simulated SSE path.
330
245
  const currentFolder = folders.find(f => String(f.id) === String(selectedFolderId));
@@ -343,6 +258,6 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
343
258
  setGeneratingVerb,
344
259
  scrollToBottom,
345
260
  });
346
- }, [appSettings, folders, isOmpSession, harness, ompAgent, selectedFolderId, sessionId, scrollToBottom, jumpToBottom, persistMessages, seedSession, pendingComposerModelRef, pendingThinkingLevelRef, deferredComposerPickRef, accessModeRef, setLocalMessages]);
261
+ }, [appSettings, folders, isOmpSession, harness, ompAgent, selectedFolderId, sessionId, scrollToBottom, jumpToBottom, persistMessages, seedSession, pendingComposerModelRef, pendingThinkingLevelRef, deferredComposerPickRef, accessModeRef, setLocalMessages, reportActionError]);
347
262
  return { steerOmpAgent, executeSend };
348
263
  }
@@ -100,6 +100,12 @@ export function resolveSessionHarness(
100
100
  picked: string | undefined,
101
101
  ): { harness: string | undefined; fromRow: boolean } {
102
102
  if (!sessionId) return { harness: undefined, fromRow: false };
103
+ // A pending row carries the harness as a MARK for its future self, not as a
104
+ // spawned fact: treating it as the row `fromRow` locked the picker on the
105
+ // composer that is supposed to choose it.
106
+ if (sessionId.startsWith('new-')) {
107
+ return { harness: spawnedHarnessFor(sessionId) ?? picked, fromRow: false };
108
+ }
103
109
  for (const folder of folders) {
104
110
  for (const entry of folder.sessions ?? []) {
105
111
  if (entry.id === sessionId) return { harness: entry.harness, fromRow: true };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Stop a run and offer the delivery of the follow-ups it leaves queued.
8
+ *
9
+ * Stop-all semantics: the queue is NOT discarded, so the one useful next action
10
+ * is "send the head now" — surfaced on the toast rather than on a row the user
11
+ * has to find. Kept out of the timeline component because it is one verb and its
12
+ * dependencies, not the layout.
13
+ */
14
+
15
+ import { useCallback } from 'preact/hooks';
16
+ import type { ToastsHandle } from '@/client/hooks/ui/toasts';
17
+
18
+ export function useStopWithQueuedPrompts<T>(
19
+ stopGenerating: () => number,
20
+ messageQueue: readonly T[],
21
+ sendNow: (item: T) => void,
22
+ pushToast: ToastsHandle['pushToast'],
23
+ ): () => void {
24
+ return useCallback(() => {
25
+ const heldCount = stopGenerating();
26
+ if (heldCount === 0) return;
27
+ pushToast(
28
+ `Stopped. ${heldCount} message${heldCount > 1 ? 's' : ''} still queued — nothing was sent.`,
29
+ 'success',
30
+ {
31
+ action: {
32
+ label: 'Send now',
33
+ onClick: () => {
34
+ const first = messageQueue[0];
35
+ if (first) sendNow(first);
36
+ },
37
+ },
38
+ duration: 8000,
39
+ },
40
+ );
41
+ }, [stopGenerating, pushToast, messageQueue, sendNow]);
42
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Open a FORK as the same pending-chat composer New Session uses.
8
+ *
9
+ * Fork used to create the branch before the operator could say what to do in
10
+ * it. Now it navigates to a `new-…` chat that carries the source and anchor in
11
+ * the pending store, so the normal empty-workspace composer (model, thinking,
12
+ * access, attachments) writes the branch's first turn. The POST happens on
13
+ * SEND, in `pending-dispatch.ts`.
14
+ */
15
+
16
+ import { useCallback } from 'preact/hooks';
17
+ import { useSearchParams } from '@/client/lib/router/search-params';
18
+ import { startPendingSession } from '@/client/hooks/chat/omp/pending-sessions';
19
+ import { setHarnessPick } from '@/client/hooks/chat/timeline/session-harness';
20
+ import { formatNewSessionTitle } from '@/shared/lib/omp/session/default-title';
21
+ import type { WorkspaceFolderData } from '@/shared/types';
22
+
23
+ export function useForkSession(
24
+ sessionId: string | null | undefined,
25
+ folders: WorkspaceFolderData[],
26
+ selectedFolderId: number | null,
27
+ ): (messageId: string) => void {
28
+ const [, setSearchParams] = useSearchParams();
29
+
30
+ return useCallback(
31
+ (messageId: string) => {
32
+ if (!sessionId) return;
33
+ const source = folders
34
+ .flatMap((folder) => folder.sessions ?? [])
35
+ .find((session) => String(session.id) === sessionId);
36
+ const folderId = source?.folder_id ?? selectedFolderId ?? null;
37
+ const pendingId = startPendingSession(folderId, {
38
+ title: formatNewSessionTitle(new Date(), 'Fork'),
39
+ ...(source?.harness ? { harness: source.harness } : {}),
40
+ forkSourceSessionId: String(sessionId),
41
+ forkAnchorEntryId: messageId,
42
+ });
43
+ // The picker's first tab is the source's agent; the fork cannot change
44
+ // provider because that agent owns the history being branched.
45
+ if (source?.harness) setHarnessPick(pendingId, source.harness);
46
+ setSearchParams((prev) => {
47
+ const next = new URLSearchParams(prev);
48
+ next.set('sessionId', pendingId);
49
+ next.set('forkFrom', String(sessionId));
50
+ next.set('forkAt', messageId);
51
+ next.delete('parentSessionId');
52
+ if (folderId !== null && folderId !== undefined) next.set('folderId', String(folderId));
53
+ return next;
54
+ }, { replace: true });
55
+ },
56
+ [sessionId, folders, selectedFolderId, setSearchParams],
57
+ );
58
+ }
@@ -0,0 +1,286 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The dialog's half of the background harness update.
8
+ *
9
+ * Four properties, and each one is a failure this design exists to prevent:
10
+ * a `202` means the install is running in a WORKER (so the card must follow it);
11
+ * a second harness pressed while the first installs is ACCEPTED and QUEUED (it
12
+ * must be followed too, and its own settle reported); a `409` for the SAME
13
+ * harness must come back as the refusal it is (no second install); and a run
14
+ * already in flight must be ADOPTED when the card opens — otherwise a reload
15
+ * loses the spinner and the user presses the button again.
16
+ *
17
+ * Every wait here is on the settle callback, not on a duration: the poll cadence
18
+ * is handed in at 1ms, so a race shows up as a missing signal rather than as a
19
+ * sleep that "usually" covers it.
20
+ */
21
+
22
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
23
+ import { Window } from 'happy-dom';
24
+ import { h, render } from 'preact';
25
+ import { act } from 'preact/test-utils';
26
+ import { useHarnessUpdate } from '@/client/hooks/models/use-harness-update';
27
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
28
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
29
+
30
+ const realFetch = Bun.fetch;
31
+ const TEST_POLL_MS = 1;
32
+ let container: HTMLElement;
33
+ let calls: string[] = [];
34
+ let postReplies: { status: number; body: unknown }[] = [];
35
+ let statusJobs: HarnessUpdateJob[] = [];
36
+ /** Called when the card re-reads the version rows (the probe-arrival signal). */
37
+ let onVersionsRead: (() => void) | null = null;
38
+
39
+ function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
40
+ return {
41
+ harness: 'claude',
42
+ label: 'claude',
43
+ startedAt: Date.now(),
44
+ finishedAt: null,
45
+ queuedAt: null,
46
+ pid: 1234,
47
+ steps: [{ part: 'adapter', command: 'npm install -g x', argv: ['npm', 'install', '-g', 'x'], state: 'running', code: null }],
48
+ output: '',
49
+ ok: null,
50
+ message: null,
51
+ applied: false,
52
+ repointed: null,
53
+ ...overrides,
54
+ };
55
+ }
56
+
57
+ function finished(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
58
+ return job({ pid: null, finishedAt: Date.now(), ok: true, applied: true, ...overrides });
59
+ }
60
+
61
+ beforeEach(() => {
62
+ installDomGlobals(new Window({ url: 'http://localhost' }));
63
+ container = document.createElement('div');
64
+ document.body.appendChild(container);
65
+ calls = [];
66
+ statusJobs = [];
67
+ postReplies = [];
68
+ onVersionsRead = null;
69
+ (globalThis as unknown as Record<string, unknown>).fetch = async (input: unknown, init?: { method?: string }) => {
70
+ calls.push(`${init?.method ?? 'GET'} ${String(input)}`);
71
+ if (init?.method === 'POST') {
72
+ const reply = postReplies.length > 1 ? postReplies.shift()! : postReplies[0];
73
+ return new Response(JSON.stringify(reply?.body ?? {}), { status: reply?.status ?? 202 });
74
+ }
75
+ if (String(input).includes('/api/harness/versions')) {
76
+ onVersionsRead?.();
77
+ onVersionsRead = null;
78
+ return new Response(JSON.stringify({ harnesses: [] }), { status: 200 });
79
+ }
80
+ return new Response(JSON.stringify({ jobs: statusJobs }), { status: 200 });
81
+ };
82
+ });
83
+
84
+ afterEach(() => {
85
+ render(null, container);
86
+ container.remove();
87
+ restoreDomGlobals();
88
+ (globalThis as unknown as Record<string, unknown>).fetch = realFetch;
89
+ });
90
+
91
+ interface Harness {
92
+ current: () => ReturnType<typeof useHarnessUpdate>;
93
+ /** The settled messages, in order. */
94
+ settlements: Array<{ message: string; ok: boolean }>;
95
+ /** Resolves when settlement number `index` has been reported. */
96
+ settlement: (index: number) => Promise<{ message: string; ok: boolean }>;
97
+ }
98
+
99
+ function mount(): Harness {
100
+ const settlements: Array<{ message: string; ok: boolean }> = [];
101
+ const waiters: Array<() => void> = [];
102
+ const box = { latest: null as ReturnType<typeof useHarnessUpdate> | null };
103
+ function Consumer() {
104
+ box.latest = useHarnessUpdate((message, ok) => {
105
+ settlements.push({ message, ok });
106
+ waiters.shift()?.();
107
+ }, { pollMs: TEST_POLL_MS });
108
+ return null;
109
+ }
110
+ const host = document.createElement('div');
111
+ container.appendChild(host);
112
+ act(() => render(h(Consumer, {}), host));
113
+ return {
114
+ current: () => {
115
+ if (!box.latest) throw new Error('consumer did not render');
116
+ return box.latest;
117
+ },
118
+ settlements,
119
+ settlement: async (index) => {
120
+ while (settlements.length <= index) {
121
+ const { promise, resolve } = Promise.withResolvers<void>();
122
+ waiters.push(resolve);
123
+ await promise;
124
+ }
125
+ return settlements[index];
126
+ },
127
+ };
128
+ }
129
+
130
+ /** Let the mount's own status read settle. */
131
+ async function flush(): Promise<void> {
132
+ await act(async () => {
133
+ await Promise.resolve();
134
+ await Promise.resolve();
135
+ });
136
+ }
137
+
138
+ const GETS = (): string[] => calls.filter((call) => call.startsWith('GET /api/harness/update/status'));
139
+
140
+ describe('useHarnessUpdate', () => {
141
+ test('a 202 starts a run and the finished record settles it', async () => {
142
+ const harness = mount();
143
+ await flush();
144
+ expect(harness.current().jobs).toEqual([]);
145
+
146
+ postReplies = [{ status: 202, body: { started: true, queued: false, job: job() } }];
147
+ // The worker is already done by the time the first status read lands: this
148
+ // is the spinners-then-message path, with no real delay anywhere.
149
+ statusJobs = [finished({ message: 'claude updated (adapter)' })];
150
+
151
+ const started: { problem: string | null } = { problem: 'unset' };
152
+ await act(async () => {
153
+ started.problem = await harness.current().start('claude');
154
+ });
155
+ expect(started.problem).toBeNull();
156
+ expect(await harness.settlement(0)).toEqual({ message: 'claude updated (adapter)', ok: true });
157
+ // The record outlives the spinner: the log panel reads it AFTER the run, and
158
+ // a cleared list would close the reader's only view of what was installed.
159
+ expect(harness.current().jobs[0]?.message).toBe('claude updated (adapter)');
160
+ });
161
+
162
+ test('a second harness is ACCEPTED as queued, and both settles are reported', async () => {
163
+ // The bug this fixes: pressing the second row while the first installed got
164
+ // a 409 and nothing else. Both presses now return 202 — the second with a
165
+ // `queued` record — and the queue starts it after the first settles.
166
+ const harness = mount();
167
+ await flush();
168
+
169
+ postReplies = [
170
+ { status: 202, body: { started: true, queued: false, job: job() } },
171
+ { status: 202, body: { started: true, queued: true, job: job({ harness: 'codex', label: 'codex', pid: null, queuedAt: Date.now() }) } },
172
+ ];
173
+ statusJobs = [job(), job({ harness: 'codex', label: 'codex', pid: null, queuedAt: Date.now() })];
174
+
175
+ let first: string | null = 'unset';
176
+ let second: string | null = 'unset';
177
+ await act(async () => {
178
+ first = await harness.current().start('claude');
179
+ second = await harness.current().start('codex');
180
+ });
181
+ expect(first).toBeNull();
182
+ expect(second).toBeNull();
183
+ expect(harness.current().jobs.map((entry) => entry.harness).sort()).toEqual(['claude', 'codex']);
184
+
185
+ // Claude finishes, the queue starts codex, codex finishes.
186
+ statusJobs = [
187
+ finished({ message: 'claude updated (adapter)' }),
188
+ job({ harness: 'codex', label: 'codex' }),
189
+ ];
190
+ expect(await harness.settlement(0)).toEqual({ message: 'claude updated (adapter)', ok: true });
191
+
192
+ statusJobs = [
193
+ finished({ message: 'claude updated (adapter)' }),
194
+ finished({ harness: 'codex', label: 'codex', message: 'codex updated (codex-acp)' }),
195
+ ];
196
+ expect(await harness.settlement(1)).toEqual({ message: 'codex updated (codex-acp)', ok: true });
197
+ // One settle each, not one per poll.
198
+ expect(harness.settlements).toHaveLength(2);
199
+ });
200
+
201
+ test('a 409 comes back as the refusal, and its record is still readable', async () => {
202
+ // The refusal carries the unfinished record (`job`), so the press that lost
203
+ // the race can still open the log of the install it collided with.
204
+ postReplies = [{
205
+ status: 409,
206
+ body: { error: 'claude update is already running — it continues in the background', job: job({ pid: 999 }) },
207
+ }];
208
+ const harness = mount();
209
+ await flush();
210
+
211
+ const refusal: { problem: string | null } = { problem: null };
212
+ await act(async () => {
213
+ refusal.problem = await harness.current().start('claude');
214
+ });
215
+ expect(refusal.problem).toContain('already running');
216
+ expect(harness.current().jobs[0]?.pid).toBe(999);
217
+ expect(harness.settlements).toEqual([]);
218
+ });
219
+
220
+ test('an in-flight run is adopted when the card opens', async () => {
221
+ statusJobs = [job()];
222
+ const harness = mount();
223
+ await flush();
224
+ // The spinner belongs to a run this page did not start — a second tab, or
225
+ // this one after a reload.
226
+ expect(harness.current().jobs[0]?.harness).toBe('claude');
227
+
228
+ statusJobs = [finished({ ok: false, message: 'claude update failed (exit 1)' })];
229
+ expect(await harness.settlement(0)).toEqual({ message: 'claude update failed (exit 1)', ok: false });
230
+ });
231
+
232
+ test('a settled run keeps polling until its PROBE answers, then re-reads the rows', async () => {
233
+ // The row quotes the version the install just replaced until the server has
234
+ // asked the new binary what it is. The poll is what carries that answer to
235
+ // the row; without it, "updated" and a stale number sit side by side and the
236
+ // only way out is pressing Check status.
237
+ statusJobs = [finished({ message: 'claude updated (adapter)', probe: 'pending' })];
238
+ const versionsRead = Promise.withResolvers<void>();
239
+ onVersionsRead = versionsRead.resolve;
240
+ const harness = mount();
241
+ await flush();
242
+ expect(harness.current().jobs[0]?.probe).toBe('pending');
243
+ expect(harness.settlements).toEqual([]);
244
+
245
+ // The probe answers on a later poll; the row's own read is the proof that it
246
+ // arrived, and it is awaited rather than slept for.
247
+ statusJobs = [finished({ message: 'claude updated (adapter) — it now reports 0.103.0', probe: 'done' })];
248
+ await versionsRead.promise;
249
+ expect(calls).toContain('GET /api/harness/versions');
250
+ expect(harness.current().jobs[0]?.probe).toBe('done');
251
+ // The probe arriving is not a second toast: one run, one report.
252
+ expect(harness.settlements).toEqual([]);
253
+ });
254
+
255
+ test('a finished record on open is history, not a run to toast about', async () => {
256
+ statusJobs = [finished({ message: 'claude updated (adapter)' })];
257
+ const harness = mount();
258
+ await flush();
259
+ // The loop stopped after the ONE read: no unfinished record means nothing to
260
+ // follow, so a finished record can never be reported as a fresh settle.
261
+ expect(harness.settlements).toEqual([]);
262
+ // No spinner, but the row can still offer the log of what ran.
263
+ expect(harness.current().jobs[0]?.harness).toBe('claude');
264
+ // One read and no follow-up: nothing is unfinished.
265
+ expect(GETS()).toHaveLength(1);
266
+ });
267
+
268
+ test('"already up to date" is reported without following a job', async () => {
269
+ postReplies = [{
270
+ status: 200,
271
+ body: { success: true, id: 'claude', message: 'claude is already up to date (adapter 0.102.0)' },
272
+ }];
273
+ const harness = mount();
274
+ await flush();
275
+
276
+ const current: { problem: string | null } = { problem: null };
277
+ await act(async () => {
278
+ current.problem = await harness.current().start('claude');
279
+ });
280
+ expect(current.problem).toBeNull();
281
+ expect(harness.current().jobs).toEqual([]);
282
+ expect(await harness.settlement(0)).toEqual({ message: 'claude is already up to date (adapter 0.102.0)', ok: true });
283
+ // One read — the mount's — and no poll for a job that does not exist.
284
+ expect(GETS()).toHaveLength(1);
285
+ });
286
+ });