@kabmo-labs/kabmo 0.23.0 → 0.25.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 +805 -736
  3. package/dist/client/static/js/index-bc9aa4mx.css +1 -0
  4. package/dist/client/static/js/{index-ph0q59rs.js → index-ga8cbpt4.js} +1071 -1171
  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/Modal.tsx +2 -6
  13. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  14. package/src/client/components/common/code-surface/shiki.ts +28 -7
  15. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
  16. package/src/client/components/common/session-actions-menu/index.tsx +33 -2
  17. package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
  18. package/src/client/components/common/session-row/index.tsx +27 -1
  19. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +7 -1
  20. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  21. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
  22. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
  23. package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.test.tsx +20 -0
  25. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +59 -12
  26. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  28. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
  29. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/index.test.tsx +122 -0
  31. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +55 -46
  32. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
  33. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
  34. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
  35. package/src/client/components/settings/categories/harness-settings/EnvProviderForm.tsx +31 -0
  36. package/src/client/components/settings/categories/harness-settings/provider-panel.test.tsx +49 -0
  37. package/src/client/components/workspace/chat-timeline/ChatOverlays.tsx +5 -2
  38. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  39. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  40. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
  41. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  42. package/src/client/components/workspace/chat-timeline/MessageList.test.ts +14 -0
  43. package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
  44. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  45. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +4 -3
  46. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  47. package/src/client/components/workspace/chat-timeline/index.tsx +5 -2
  48. package/src/client/components/workspace/chat-timeline/pending-harness.test.tsx +1 -1
  49. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FrameControl.tsx +11 -20
  50. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/GroupedAsk.tsx +1 -1
  51. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionBlock.tsx +1 -1
  52. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/drafts.ts +1 -1
  53. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/index.tsx +2 -1
  54. package/src/client/components/workspace/file-explorer/index.test.ts +25 -0
  55. package/src/client/components/workspace/file-explorer/index.tsx +9 -3
  56. package/src/client/components/workspace/model-dropdown/harness-models.test.ts +17 -0
  57. package/src/client/components/workspace/model-dropdown/harness-models.ts +33 -18
  58. package/src/client/components/workspace/model-dropdown/index.tsx +3 -3
  59. package/src/client/components/workspace/model-dropdown/popover-metrics.ts +4 -1
  60. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  61. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  62. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  63. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  64. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  65. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  66. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  67. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  68. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  69. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  70. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  71. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  72. package/src/client/data/settings/omp-schema.json +5 -5
  73. package/src/client/data/theme/terminal.test.ts +25 -0
  74. package/src/client/data/theme/terminal.ts +96 -79
  75. package/src/client/hooks/chat/composer/items.test.ts +12 -26
  76. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  77. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  78. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  79. package/src/client/hooks/chat/timeline/actions.ts +2 -2
  80. package/src/client/hooks/chat/timeline/ask-frames.ts +5 -4
  81. package/src/client/hooks/chat/timeline/new-chat-open.test.ts +86 -0
  82. package/src/client/hooks/chat/timeline/new-chat-open.ts +23 -5
  83. package/src/client/hooks/chat/timeline/new-chat.test.ts +32 -4
  84. package/src/client/hooks/chat/timeline/new-chat.ts +18 -6
  85. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  86. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  87. package/src/client/hooks/chat/timeline/rewind-actions.test.ts +24 -1
  88. package/src/client/hooks/chat/timeline/rewind-actions.ts +15 -11
  89. package/src/client/hooks/chat/timeline/run-identity.test.ts +52 -0
  90. package/src/client/hooks/chat/timeline/run-identity.ts +23 -11
  91. package/src/client/hooks/chat/timeline/send-execute.test.ts +56 -0
  92. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  93. package/src/client/hooks/chat/timeline/send-props.ts +5 -3
  94. package/src/client/hooks/chat/timeline/send-steer.test.ts +4 -4
  95. package/src/client/hooks/chat/timeline/send.test-util.ts +8 -2
  96. package/src/client/hooks/chat/timeline/send.test.ts +4 -4
  97. package/src/client/hooks/chat/timeline/send.ts +59 -53
  98. package/src/client/hooks/chat/timeline/session-load.test-util.ts +6 -2
  99. package/src/client/hooks/chat/timeline/session-load.test.ts +31 -0
  100. package/src/client/hooks/chat/timeline/session-load.ts +6 -14
  101. package/src/client/hooks/chat/timeline/session-shapes.ts +32 -0
  102. package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
  103. package/src/client/hooks/models/harness-catalog.ts +114 -0
  104. package/src/client/hooks/models/provider-writes.test.ts +81 -0
  105. package/src/client/hooks/models/provider-writes.ts +10 -3
  106. package/src/client/hooks/models/use-harness-update.test.ts +193 -0
  107. package/src/client/hooks/models/use-harness-update.ts +202 -0
  108. package/src/client/hooks/models/use-harnesses-controller.ts +57 -0
  109. package/src/client/hooks/models/use-harnesses-signal.test.ts +128 -0
  110. package/src/client/hooks/models/use-harnesses.test.ts +2 -1
  111. package/src/client/hooks/models/use-harnesses.ts +48 -114
  112. package/src/client/hooks/workspace/child-expansion.ts +33 -0
  113. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  114. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  115. package/src/client/lib/session-tree.test.ts +50 -0
  116. package/src/client/lib/session-tree.ts +59 -0
  117. package/src/client/tailwind.css +26 -12
  118. package/src/server/index.ts +2 -0
  119. package/src/server/lib/auth/guard.ts +10 -0
  120. package/src/server/lib/btw/session-copy.server.ts +6 -44
  121. package/src/server/lib/btw/session-copy.test.ts +2 -1
  122. package/src/server/lib/db/schema.ts +4 -0
  123. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  124. package/src/server/lib/db/seed.test.ts +1 -1
  125. package/src/server/lib/harness/acp/activation.test.ts +81 -0
  126. package/src/server/lib/harness/acp/activation.ts +72 -0
  127. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  128. package/src/server/lib/harness/acp/background-work.ts +320 -0
  129. package/src/server/lib/harness/acp/client.ts +2 -2
  130. package/src/server/lib/harness/acp/frames.test.ts +50 -1
  131. package/src/server/lib/harness/acp/frames.ts +17 -5
  132. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  133. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  134. package/src/server/lib/harness/acp/mapper.ts +6 -4
  135. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  136. package/src/server/lib/harness/acp/prompt.ts +19 -3
  137. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  138. package/src/server/lib/harness/acp/session-config.test.ts +73 -0
  139. package/src/server/lib/harness/acp/session-config.ts +87 -6
  140. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  141. package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
  142. package/src/server/lib/harness/acp/session-handshake.ts +36 -3
  143. package/src/server/lib/harness/acp/session-idle.ts +51 -0
  144. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  145. package/src/server/lib/harness/acp/session-notifications.ts +19 -3
  146. package/src/server/lib/harness/acp/session-observers.test.ts +9 -0
  147. package/src/server/lib/harness/acp/session-options.ts +33 -0
  148. package/src/server/lib/harness/acp/session-reaper.test.ts +96 -0
  149. package/src/server/lib/harness/acp/session-requests.ts +47 -0
  150. package/src/server/lib/harness/acp/session-turns.ts +20 -5
  151. package/src/server/lib/harness/acp/session.test-util.ts +54 -3
  152. package/src/server/lib/harness/acp/session.test.ts +65 -3
  153. package/src/server/lib/harness/acp/session.ts +79 -79
  154. package/src/server/lib/harness/acp/turn.test.ts +81 -0
  155. package/src/server/lib/harness/acp/turn.ts +54 -13
  156. package/src/server/lib/harness/acp/verbs.ts +12 -2
  157. package/src/server/lib/harness/auto-probe.server.test.ts +121 -0
  158. package/src/server/lib/harness/auto-probe.server.ts +178 -0
  159. package/src/server/lib/harness/config.server.test.ts +1 -1
  160. package/src/server/lib/harness/config.server.ts +1 -1
  161. package/src/server/lib/harness/launch-table.ts +195 -0
  162. package/src/server/lib/harness/launch.test.ts +37 -0
  163. package/src/server/lib/harness/launch.ts +16 -116
  164. package/src/server/lib/harness/provider-entry.ts +32 -0
  165. package/src/server/lib/harness/provider-file.server.ts +3 -0
  166. package/src/server/lib/harness/provider-sources.server.test.ts +45 -0
  167. package/src/server/lib/harness/provider-sources.server.ts +26 -2
  168. package/src/server/lib/harness/provider-write.server.ts +21 -32
  169. package/src/server/lib/harness/provider-zcode.server.test.ts +270 -0
  170. package/src/server/lib/harness/provider-zcode.server.ts +324 -0
  171. package/src/server/lib/harness/spawn.server.ts +15 -2
  172. package/src/server/lib/harness/update-job-store.test.ts +126 -0
  173. package/src/server/lib/harness/update-job-store.ts +109 -0
  174. package/src/server/lib/harness/update-job.server.ts +203 -0
  175. package/src/server/lib/harness/update-state.server.ts +15 -20
  176. package/src/server/lib/harness/update-worker.test.ts +153 -0
  177. package/src/server/lib/harness/update-worker.ts +197 -0
  178. package/src/server/lib/lifecycle/after-listen.ts +7 -0
  179. package/src/server/lib/lifecycle/paths.ts +23 -0
  180. package/src/server/lib/models/registry-refresh.server.test.ts +87 -0
  181. package/src/server/lib/models/registry-refresh.server.ts +98 -0
  182. package/src/server/lib/omp/rpc/child-config.ts +5 -4
  183. package/src/server/lib/omp/rpc/constants.test.ts +2 -1
  184. package/src/server/lib/omp/rpc/forked-resume.test.ts +14 -3
  185. package/src/server/lib/omp/rpc/manager.ts +5 -5
  186. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  187. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  188. package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
  189. package/src/server/lib/omp/session/delete-flow.server.ts +62 -8
  190. package/src/server/lib/omp/session/delete.server.ts +17 -0
  191. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  192. package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
  193. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  194. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  195. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  196. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  197. package/src/server/lib/sessions/answers.server.ts +37 -0
  198. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  199. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  200. package/src/server/lib/sessions/fork.server.test.ts +209 -0
  201. package/src/server/lib/sessions/fork.server.ts +304 -0
  202. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  203. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  204. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  205. package/src/server/lib/sessions/notify.server.ts +212 -0
  206. package/src/server/lib/sessions/relation-types.ts +76 -0
  207. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  208. package/src/server/lib/sessions/relations.server.ts +337 -0
  209. package/src/server/lib/sessions/resolve.server.ts +106 -0
  210. package/src/server/lib/sessions/schema.server.ts +82 -0
  211. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  212. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  213. package/src/server/lib/sessions/spawn.server.test.ts +196 -0
  214. package/src/server/lib/sessions/spawn.server.ts +310 -0
  215. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  216. package/src/server/lib/terminal/output.test.ts +2 -2
  217. package/src/server/lib/terminal/output.ts +1 -1
  218. package/src/server/lib/terminal/resize.test.ts +99 -0
  219. package/src/server/lib/terminal/runtime.server.ts +26 -6
  220. package/src/server/lib/terminal/send-result.test.ts +18 -1
  221. package/src/server/lib/terminal/send-result.ts +26 -2
  222. package/src/server/lib/terminal/session.server.ts +6 -6
  223. package/src/server/lib/usage/new-api.test.ts +92 -0
  224. package/src/server/lib/usage/new-api.ts +131 -0
  225. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  226. package/src/server/lib/usage/provider-key.ts +33 -0
  227. package/src/server/lib/usage/providers.server.ts +10 -3
  228. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  229. package/src/server/lib/usage/vendor-http.ts +41 -0
  230. package/src/server/lib/usage/window.ts +55 -0
  231. package/src/server/routes/agent/command.ts +14 -1
  232. package/src/server/routes/agent/harness-command.ts +6 -0
  233. package/src/server/routes/agent/new.ts +15 -0
  234. package/src/server/routes/chat/rewind.test.ts +147 -0
  235. package/src/server/routes/chat/rewind.ts +29 -7
  236. package/src/server/routes/chat/session.test.ts +165 -10
  237. package/src/server/routes/chat/session.ts +60 -7
  238. package/src/server/routes/harness/add-provider.test.ts +9 -1
  239. package/src/server/routes/harness/import-action.ts +22 -4
  240. package/src/server/routes/harness/import.test.ts +1 -1
  241. package/src/server/routes/harness/index.ts +5 -1
  242. package/src/server/routes/harness/root.ts +8 -49
  243. package/src/server/routes/harness/toggle.test.ts +20 -0
  244. package/src/server/routes/harness/update-status.ts +26 -0
  245. package/src/server/routes/harness/update.test.ts +119 -0
  246. package/src/server/routes/harness/update.ts +67 -113
  247. package/src/server/routes/harness/versions.ts +5 -1
  248. package/src/server/routes/sessions/answer.ts +24 -0
  249. package/src/server/routes/sessions/batch-delete.ts +11 -5
  250. package/src/server/routes/sessions/delete-acp.test.ts +227 -0
  251. package/src/server/routes/sessions/delete.ts +4 -2
  252. package/src/server/routes/sessions/fork.ts +74 -0
  253. package/src/server/routes/sessions/index.ts +14 -0
  254. package/src/server/routes/sessions/relations.ts +85 -0
  255. package/src/server/routes/sessions/session.ts +4 -0
  256. package/src/server/routes/sessions/spawn.ts +134 -0
  257. package/src/server/routes/settings/model-override.ts +5 -2
  258. package/src/server/routes/settings/provider-entry.ts +2 -2
  259. package/src/server/routes/settings/provider-model.ts +2 -2
  260. package/src/server/routes/settings/provider-models.ts +2 -2
  261. package/src/server/routes/settings/provider-refresh.ts +6 -4
  262. package/src/server/routes/settings/providers.ts +3 -1
  263. package/src/server/routes/settings/settings-config-routes.test.ts +10 -2
  264. package/src/server/routes/terminal/ws.ts +3 -3
  265. package/src/shared/lib/chat/ask-form/fields.ts +76 -0
  266. package/src/shared/lib/chat/ask-form/index.ts +323 -0
  267. package/src/shared/lib/chat/ask-form/tokens.ts +199 -0
  268. package/src/shared/lib/chat/ask-form/types.ts +43 -0
  269. package/src/shared/lib/chat/ask-form.test.ts +137 -0
  270. package/src/shared/lib/chat/ask-questions.test.ts +65 -1
  271. package/src/shared/lib/chat/ask-questions.ts +51 -145
  272. package/src/shared/lib/chat/ask-results.ts +198 -0
  273. package/src/shared/lib/chat/composer/client.ts +31 -2
  274. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  275. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  276. package/src/shared/lib/chat/notice-text.ts +1 -1
  277. package/src/shared/lib/chat/timeline/omp-callbacks.ts +13 -1
  278. package/src/shared/lib/chat/timeline/prompt-error.test.ts +146 -0
  279. package/src/shared/lib/chat/timeline/prompt-error.ts +88 -0
  280. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  281. package/src/shared/lib/code/ansi.ts +1 -1
  282. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  283. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  284. package/src/shared/lib/harness/catalog.test.ts +1 -1
  285. package/src/shared/lib/harness/config-fields.test.ts +4 -0
  286. package/src/shared/lib/harness/config-fields.ts +19 -4
  287. package/src/shared/lib/harness/dialects.test.ts +8 -0
  288. package/src/shared/lib/harness/dialects.ts +12 -0
  289. package/src/shared/lib/harness/provider-facts.test.ts +59 -8
  290. package/src/shared/lib/harness/provider-facts.ts +46 -11
  291. package/src/shared/lib/harness/providers.ts +44 -1
  292. package/src/shared/lib/harness/rewind.ts +24 -0
  293. package/src/shared/lib/harness/update-job.ts +33 -0
  294. package/src/shared/lib/harness/update-plan.test.ts +69 -4
  295. package/src/shared/lib/harness/update-plan.ts +57 -9
  296. package/src/shared/lib/harness/updates.test.ts +22 -0
  297. package/src/shared/lib/harness/updates.ts +24 -1
  298. package/src/shared/lib/models/client.ts +10 -1
  299. package/src/shared/lib/omp/dialog-methods.ts +4 -3
  300. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  301. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  302. package/src/shared/lib/theme/catalog.test.ts +13 -9
  303. package/src/shared/lib/theme/color.test.ts +2 -2
  304. package/src/shared/lib/theme/color.ts +4 -4
  305. package/src/shared/lib/theme/css.ts +2 -0
  306. package/src/shared/lib/theme/ink-scale.ts +21 -1
  307. package/src/shared/lib/theme/theme.test.ts +26 -10
  308. package/src/shared/lib/ui/safe-area.test.ts +28 -0
  309. package/src/shared/lib/ui/safe-area.ts +42 -0
  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 +65 -0
  316. package/src/shared/types/harness.ts +30 -4
  317. package/src/shared/types/omp/agent.ts +19 -2
  318. package/src/shared/types/workspace.ts +4 -0
  319. package/src/test-support/fake-omp-fork.ts +16 -2
  320. package/src/test-support/file-explorer-render.test-util.ts +37 -0
  321. package/src/test-support/file-explorer.test-util.ts +20 -18
  322. package/src/test-support/harness-table.test-util.ts +21 -4
  323. package/dist/client/static/js/index-jhmg4w91.css +0 -1
  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
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * `POST /api/harness/update` and `GET /api/harness/update/status`.
8
+ *
9
+ * The route used to run the installs itself; it now starts a background worker
10
+ * and answers `202`. These cases pin the answers that do NOT spawn anything —
11
+ * the refusals and the progress read — because those are the shapes the dialog
12
+ * branches on, and a wrong status there either starts a competing install or
13
+ * reports success it never observed.
14
+ */
15
+
16
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
17
+ import { mkdtempSync, rmSync } from 'node:fs';
18
+ import { tmpdir } from 'node:os';
19
+ import { join } from 'node:path';
20
+ import { action } from '@/server/routes/harness/update';
21
+ import { loader as statusLoader } from '@/server/routes/harness/update-status';
22
+ import { writeUpdateJob } from '@/server/lib/harness/update-job-store';
23
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
24
+
25
+ let dir = '';
26
+ let originalDataDir: string | undefined;
27
+
28
+ beforeEach(() => {
29
+ originalDataDir = Bun.env.KABMO_DATA_DIR;
30
+ dir = mkdtempSync(join(tmpdir(), 'kabmo-update-route-'));
31
+ Bun.env.KABMO_DATA_DIR = dir;
32
+ });
33
+
34
+ afterEach(() => {
35
+ if (originalDataDir === undefined) delete Bun.env.KABMO_DATA_DIR;
36
+ else Bun.env.KABMO_DATA_DIR = originalDataDir;
37
+ rmSync(dir, { recursive: true, force: true });
38
+ });
39
+
40
+ function post(harness: string): Parameters<typeof action>[0] {
41
+ return {
42
+ request: new Request('http://localhost/api/harness/update', {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json' },
45
+ body: JSON.stringify({ harness }),
46
+ }),
47
+ params: {},
48
+ } as Parameters<typeof action>[0];
49
+ }
50
+
51
+ function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
52
+ return {
53
+ harness: 'claude',
54
+ label: 'claude',
55
+ startedAt: Date.now(),
56
+ finishedAt: null,
57
+ pid: process.pid,
58
+ steps: [{ part: 'adapter', command: 'npm install -g x', argv: ['npm', 'install', '-g', 'x'], state: 'running', code: null }],
59
+ output: '',
60
+ ok: null,
61
+ message: null,
62
+ applied: false,
63
+ repointed: null,
64
+ ...overrides,
65
+ };
66
+ }
67
+
68
+ describe('POST /api/harness/update', () => {
69
+ test('an unknown harness is refused before anything runs', async () => {
70
+ const response = (await action(post('nope'))) as Response;
71
+ expect(response.status).toBe(400);
72
+ expect(((await response.json()) as { error: string }).error).toBe('Unknown harness');
73
+ });
74
+
75
+ test('a vendor-managed harness is refused with the reason', async () => {
76
+ // `cursor` is updated by its own installer; Kabmo replacing it would be an
77
+ // install it did not make.
78
+ const response = (await action(post('cursor'))) as Response;
79
+ expect(response.status).toBe(400);
80
+ const payload = (await response.json()) as { error: string; code: string };
81
+ expect(payload.code).toBe('vendor_managed');
82
+ expect(payload.error).toContain('installed by its vendor');
83
+ });
84
+
85
+ test('a second press while a run is in flight is a 409 that names the run', async () => {
86
+ // Measured corruption vector: a reload forgot the run and offered the button,
87
+ // so two `npm install -g` wrote the same prefix at once. The record on disk is
88
+ // what refuses it now.
89
+ await writeUpdateJob(job());
90
+ const response = (await action(post('claude'))) as Response;
91
+ expect(response.status).toBe(409);
92
+ const payload = (await response.json()) as { error: string; job: HarnessUpdateJob };
93
+ expect(payload.error).toContain('already running');
94
+ expect(payload.job.harness).toBe('claude');
95
+ });
96
+ });
97
+
98
+ describe('GET /api/harness/update/status', () => {
99
+ test('no run ever started is null, not a 404', async () => {
100
+ const response = (await statusLoader()) as Response;
101
+ expect(response.status).toBe(200);
102
+ expect(((await response.json()) as { job: unknown }).job).toBeNull();
103
+ });
104
+
105
+ test('a finished run is reported with its message', async () => {
106
+ const done = job({
107
+ pid: null,
108
+ finishedAt: Date.now(),
109
+ ok: true,
110
+ applied: true,
111
+ message: 'claude updated (adapter) — check its status to read the new version',
112
+ });
113
+ await writeUpdateJob(done);
114
+ const response = (await statusLoader()) as Response;
115
+ const payload = (await response.json()) as { job: HarnessUpdateJob };
116
+ expect(payload.job.ok).toBe(true);
117
+ expect(payload.job.message).toContain('claude updated');
118
+ });
119
+ });
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  /**
7
- * Updating ONE harness — and refusing where Kabmo must not act.
7
+ * Updating ONE harness — as a BACKGROUND job, and refusing where Kabmo must not act.
8
8
  *
9
9
  * Three mechanisms, and the refusal is as much of the feature as the button:
10
10
  *
@@ -21,70 +21,64 @@
21
21
  * **An adapter is TWO installs.** `claude` is `@agentclientprotocol/claude-agent-acp`
22
22
  * (the number the probe reports) on top of the `claude` CLI, and they move
23
23
  * independently — measured here: adapter 0.100.0 under CLI 2.1.318. So one press
24
- * moves EVERY part that is behind and none that is current:
24
+ * moves EVERY part that is behind and none that is current. The decision itself
25
+ * is pure (`planHarnessUpdate`); this route only resolves the facts it needs and
26
+ * hands the argv to the worker.
25
27
  *
26
- * - both behind → `npm i -g <adapter>@<latest>` then `claude update`;
27
- * - only the CLI → `claude update`, with no adapter install at all;
28
- * - only the adapter → the npm install alone.
29
- *
30
- * Running both unconditionally was the first shape, and it reinstalled an adapter
31
- * that was already current while reporting "updated to 0.101.0" about a version
32
- * that never moved.
33
- *
34
- * Every run is a POST that answers plain JSON, not an SSE stream: an npm install
35
- * of one package, or one `upgrade` subcommand, is seconds rather than the minutes
36
- * `omp update` and the Kabmo self-update take. If one of these grows long enough
37
- * to need streaming, it should reuse `updates/apply.ts` rather than grow a second
38
- * progress protocol here.
28
+ * **The route does not run the installs.** They used to run here, inside the POST:
29
+ * the request stayed open for minutes, a reload forgot the run, and a five-minute
30
+ * child timeout could kill `npm install -g` halfway through writing a package
31
+ * tree — the corruption this design removes. The run is a detached worker
32
+ * (`update-worker.ts`) that writes progress to `harness-update.json`; this route
33
+ * answers `202` in milliseconds and `GET /api/harness/update/status` reports the
34
+ * outcome. A second press while one runs is a `409`, read from that same record,
35
+ * so a reloaded page cannot start a competing install.
39
36
  */
40
37
 
41
- import { json } from '@/server/lib/remix-compat';
38
+ import { json, NO_STORE_HEADERS } from '@/server/lib/remix-compat';
42
39
  import type { ActionFunctionArgs } from '@/server/lib/remix-compat';
43
40
  import { methodNotAllowed } from '@/server/lib/route-adapter';
44
41
  import { HARNESS_IDS, harnessDescriptor, type HarnessId } from '@/shared/lib/harness/catalog';
45
42
  import { harnessUpdateFacts, latestSourceFor } from '@/shared/lib/harness/updates';
46
- import { forgetProbe, loadProbes } from '@/server/lib/harness/probe-cache.server';
47
- import { forgetCliVersion, harnessVersionState } from '@/server/lib/harness/update-state.server';
48
- import { planHarnessUpdate } from '@/shared/lib/harness/update-plan';
49
- import { harnessVersionRows } from '@/server/routes/harness/versions';
50
-
51
- /** Longest one update may run before it is killed and reported as a timeout. */
52
- const UPDATE_TIMEOUT_MS = 5 * 60_000;
53
-
54
- /** The result the UI reports, in the agent's own terms. */
43
+ import { loadProbes } from '@/server/lib/harness/probe-cache.server';
44
+ import { harnessVersionState, type HarnessVersionState } from '@/server/lib/harness/update-state.server';
45
+ import { planHarnessUpdate, type HarnessUpdateStep } from '@/shared/lib/harness/update-plan';
46
+ import { resolveOmpBin } from '@/server/lib/omp/core/cli';
47
+ import {
48
+ runningUpdateJob,
49
+ startHarnessUpdateJob,
50
+ } from '@/server/lib/harness/update-job.server';
51
+
52
+ /** The answer to a press that has nothing to move, still plain JSON. */
55
53
  interface HarnessUpdateOutcome {
56
54
  success: boolean;
57
55
  id: string;
58
56
  message: string;
59
- /** The commands that ran, so the reader can repeat them themselves. */
60
- command?: string;
61
- /** The tail of their output — what actually failed, when it failed. */
62
- output?: string;
63
57
  }
64
58
 
65
- /** Run a command, capturing its combined output for the report. */
66
- async function run(command: string[], cwd?: string): Promise<{ code: number | null; output: string }> {
67
- const proc = Bun.spawn({
68
- cmd: command,
69
- stdin: 'ignore',
70
- stdout: 'pipe',
71
- stderr: 'pipe',
72
- timeout: UPDATE_TIMEOUT_MS,
73
- env: { ...Bun.env, PAGER: 'cat', FORCE_COLOR: '0' },
74
- ...(cwd ? { cwd } : {}),
75
- });
76
- const [stdout, stderr] = await Promise.all([
77
- new Response(proc.stdout).text(),
78
- new Response(proc.stderr).text(),
79
- ]);
80
- const code = await proc.exited;
81
- return { code, output: [stdout, stderr].filter(Boolean).join('\n').trim() };
59
+ /** A readable description of the numbers currently on disk, for "already current". */
60
+ function currentParts(state: HarnessVersionState, cliName: string | undefined): string {
61
+ return [
62
+ state.agent.version && `adapter ${state.agent.version}`,
63
+ state.cli?.version && `${cliName ?? 'CLI'} ${state.cli.version}`,
64
+ ].filter(Boolean).join(', ');
82
65
  }
83
66
 
84
- /** The last few lines of a run, which is where a failure explains itself. */
85
- function tail(output: string, lines = 12): string {
86
- const all = output.split('\n');
87
- return all.slice(Math.max(0, all.length - lines)).join('\n').trim();
67
+ /**
68
+ * The argv for a `self` harness: the vendor's own updater, resolved by name.
69
+ *
70
+ * `omp` has its own resolver (`KABMO_OMP_BIN`, then PATH): a custom install is
71
+ * launchable and already reported as installed, so checking PATH alone refused
72
+ * the one updater the harness actually has.
73
+ */
74
+ function selfSteps(harness: HarnessId, label: string, command: string): { steps: HarnessUpdateStep[]; error?: string } {
75
+ const argv = command.split(' ');
76
+ const binary = argv[0];
77
+ const resolved = harness === 'omp-acp' ? resolveOmpBin() : binary ? Bun.which(binary) : null;
78
+ if (!binary || !resolved) {
79
+ return { steps: [], error: `${label}: \`${binary || 'the updater'}\` is not on PATH` };
80
+ }
81
+ return { steps: [{ part: label, command, argv: [resolved, ...argv.slice(1)] }] };
88
82
  }
89
83
 
90
84
  export async function action({ request, params }: ActionFunctionArgs) {
@@ -117,28 +111,31 @@ export async function action({ request, params }: ActionFunctionArgs) {
117
111
  }, { status: 400 });
118
112
  }
119
113
 
114
+ // Read BEFORE planning: the answer to a press while an install runs must not
115
+ // depend on what this press would have planned, and planning reads the npm
116
+ // registry.
117
+ const running = await runningUpdateJob();
118
+ if (running) {
119
+ return json({
120
+ error: `${running.label} update is already running — it continues in the background`,
121
+ job: running,
122
+ }, { status: 409, headers: NO_STORE_HEADERS });
123
+ }
124
+
120
125
  if (facts.kind === 'self') {
121
- const command = facts.command?.split(' ') ?? [];
122
- const binary = command[0];
123
- if (!binary || !Bun.which(binary)) {
124
- return json({ error: `${label}: \`${binary ?? 'the updater'}\` is not on PATH` }, { status: 400 });
125
- }
126
- const result = await run(command);
127
- const ok = result.code === 0;
128
- const outcome: HarnessUpdateOutcome = {
129
- success: ok,
130
- id: harness,
131
- message: ok ? `${label} updated` : `${label} update failed (exit ${result.code ?? 'killed'})`,
132
- command: facts.command,
133
- ...(result.output ? { output: tail(result.output) } : {}),
134
- };
135
- return json(outcome);
126
+ if (!facts.command) return json({ error: `${label} names no updater command` }, { status: 400 });
127
+ const { steps, error } = selfSteps(harness, label, facts.command);
128
+ if (error) return json({ error }, { status: 400 });
129
+ const job = await startHarnessUpdateJob(harness, label, steps);
130
+ return json({ started: true, job }, { status: 202, headers: NO_STORE_HEADERS });
136
131
  }
137
132
 
138
133
  // `npm`: install the package at the version the registry reports NOW, so the
139
- // number on screen and the install cannot disagree.
134
+ // number on screen and the install cannot disagree. A harness can have no
135
+ // AGENT package while its CLI has one (`dsh`): the CLI step is then the whole
136
+ // update, so the missing agent package is not a refusal.
140
137
  const pkg = latestSourceFor(harness);
141
- if (!pkg) return json({ error: `${label} has no package to install` }, { status: 400 });
138
+ if (!pkg && !facts.cli?.pkg) return json({ error: `${label} has no package to install` }, { status: 400 });
142
139
 
143
140
  const probe = (await loadProbes()).get(harness);
144
141
  const agentVersion = probe?.capabilities.agentVersion ?? null;
@@ -152,17 +149,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
152
149
  return json({ error: `${label} is not installed on this machine` }, { status: 400 });
153
150
  }
154
151
 
155
- // `harnessVersionState` was read with `force`, so both latest numbers are what
156
- // the registry serves NOW rather than what the dialog remembered.
157
-
158
152
  const steps = planHarnessUpdate(label, facts, state, agentVersion);
159
153
 
160
154
  if (steps.length === 0) {
161
155
  // Nothing to install. Reported as a success the UI can state plainly, rather
162
156
  // than running an install that would change nothing.
163
- const current = [state.agent.version && `adapter ${state.agent.version}`, state.cli?.version && `${facts.cli?.name} ${state.cli.version}`]
164
- .filter(Boolean)
165
- .join(', ');
157
+ const current = currentParts(state, facts.cli?.name);
166
158
  return json({
167
159
  success: true,
168
160
  id: harness,
@@ -174,44 +166,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
174
166
  } satisfies HarnessUpdateOutcome);
175
167
  }
176
168
 
177
- /** Did every step that ran succeed, and what did each print? */
178
- const outputs: string[] = [];
179
- let ok = true;
180
- for (const step of steps) {
181
- const result = await run(step.argv);
182
- if (result.output) outputs.push(result.output);
183
- if (result.code !== 0) {
184
- ok = false;
185
- // The first failure ends the run: installing the CLI on top of a failed
186
- // adapter install would report two outcomes for one broken state.
187
- break;
188
- }
189
- }
190
-
191
- if (ok) {
192
- // The cached probe describes the binary that WAS installed. Keeping it would
193
- // report the old version until the TTL (30 min) or a manual re-probe — and
194
- // measured after a real `npm install`: the row still read 0.100.0 while npm
195
- // had 0.101.0 on disk, because the running adapter was the previous process.
196
- await forgetProbe(harness);
197
- // The CLI's `--version` read has the same problem: it is cached for ten
198
- // minutes, so the row would keep claiming the old number after it moved.
199
- if (facts.cli) forgetCliVersion(facts.cli.bin);
200
- }
201
-
202
- const moved = steps.map((step) => step.part);
203
- return json({
204
- success: ok,
205
- id: harness,
206
- message: ok
207
- ? `${label} updated (${moved.join(' + ')}) — check its status to read the new version`
208
- : `${label} update failed`,
209
- command: steps.map((step) => step.command).join(' && '),
210
- ...(outputs.length > 0 ? { output: tail(outputs.join('\n')) } : {}),
211
- } satisfies HarnessUpdateOutcome);
212
- }
213
-
214
- /** GET answers the same rows the versions route does, so a mistake reads plainly. */
215
- export async function loader() {
216
- return json({ harnesses: await harnessVersionRows() });
169
+ const job = await startHarnessUpdateJob(harness, label, steps);
170
+ return json({ started: true, job }, { status: 202, headers: NO_STORE_HEADERS });
217
171
  }
@@ -66,7 +66,11 @@ function toRow(
66
66
  else if (!facts) note = 'Kabmo knows nothing about updating this harness.';
67
67
  else if (!state.agent.version) note = 'Not probed yet — check its status to learn the version it runs.';
68
68
  else if (facts.kind !== 'npm') note = facts.command ? `Updated by \`${facts.command}\`.` : note;
69
- else if (!state.agent.latest) note = `Could not read ${facts.pkg} from the registry.`;
69
+ // An npm harness can have no AGENT package (`dsh`: the probe reports the ACP
70
+ // surface, the package is the CLI). The note names whichever package was
71
+ // actually read, instead of "Could not read undefined".
72
+ else if (facts.pkg && !state.agent.latest) note = `Could not read ${facts.pkg} from the registry.`;
73
+ else if (facts.cli?.pkg && state.cli?.version && !state.cli.latest) note = `Could not read ${facts.cli.pkg} from the registry.`;
70
74
 
71
75
  return {
72
76
  id,
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * GET /api/sessions/:sessionId/answer — the last assistant text a turn closed.
8
+ *
9
+ * ACP has no transcript for `/api/chat/:id` to read after the process dies, so
10
+ * `kabmo session output` needs this row. A null answer is a real state (the
11
+ * session has not answered yet), not an error.
12
+ */
13
+
14
+ import { json } from '@/server/lib/remix-compat';
15
+ import type { LoaderFunctionArgs } from '@/server/lib/remix-compat';
16
+ import { methodNotAllowed } from '@/server/lib/route-adapter';
17
+ import { loadSessionAnswer } from '@/server/lib/sessions/answers.server';
18
+
19
+ export async function getSessionAnswer({ request, params }: LoaderFunctionArgs) {
20
+ if (request.method !== 'GET') return methodNotAllowed({ request, params });
21
+ const sessionId = params.sessionId;
22
+ if (!sessionId) return json({ error: 'Missing session id' }, { status: 400 });
23
+ return json({ sessionId, answer: await loadSessionAnswer(sessionId) });
24
+ }
@@ -20,7 +20,7 @@
20
20
  import { json } from '@/server/lib/remix-compat';
21
21
  import type { ActionFunctionArgs } from '@/server/lib/remix-compat';
22
22
  import { methodNotAllowed, parseJsonBody } from '@/server/lib/route-adapter';
23
- import { removeSession } from '@/server/lib/omp/session/delete-flow.server';
23
+ import { removeSessionTree } from '@/server/lib/omp/session/delete-flow.server';
24
24
 
25
25
  /** One request cannot carry an unbounded selection. */
26
26
  const MAX_BATCH = 500;
@@ -44,6 +44,7 @@ export async function batchDeleteSessions({ request }: ActionFunctionArgs) {
44
44
  }
45
45
 
46
46
  const removed: string[] = [];
47
+ const removedDependents: string[] = [];
47
48
  const refused: { id: string; error: string; code?: string }[] = [];
48
49
 
49
50
  // Sequential, deliberately: every removal may have to destroy an omp child
@@ -51,10 +52,15 @@ export async function batchDeleteSessions({ request }: ActionFunctionArgs) {
51
52
  // transcript writer per session at once for no gain — the work is dominated
52
53
  // by process teardown, not by the filesystem.
53
54
  for (const id of ids) {
54
- const result = await removeSession(id);
55
- if (result.ok) removed.push(id);
56
- else refused.push({ id, error: result.error ?? 'Could not delete the session.', code: result.code });
55
+ const tree = await removeSessionTree(id);
56
+ const result = tree.result;
57
+ if (result.ok) {
58
+ removed.push(id);
59
+ removedDependents.push(...tree.removedDependents);
60
+ } else {
61
+ refused.push({ id, error: result.error ?? 'Could not delete the session.', code: result.code });
62
+ }
57
63
  }
58
64
 
59
- return json({ success: refused.length === 0, removed, refused });
65
+ return json({ success: refused.length === 0, removed, removedDependents, refused });
60
66
  }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Deleting a chat that ran on an ACP harness.
8
+ *
9
+ * An ACP agent writes no session file, so `harness_sessions` IS the row the
10
+ * sidebar draws — and the delete flow used to purge only Kabmo's own tables.
11
+ * Measured before the fix, both failure modes:
12
+ *
13
+ * - a `claude` chat answered 404 "Session not found" and stayed in the
14
+ * sidebar (nothing matched, so the purge reported nothing to remove);
15
+ * - an `omp-acp` chat answered 200 and removed its JSONL, then reappeared
16
+ * from the record the very next sidebar build. Deleting an ARCHIVED ACP
17
+ * chat looked the same: the archive row was purged, the record was not, so
18
+ * the row came back unarchived — the reported "archive is undone by delete".
19
+ *
20
+ * The live child is looked up in the harness-agnostic registry now, so a busy
21
+ * ACP chat is refused rather than removed underneath its own agent, and an idle
22
+ * one is torn down before its rows go.
23
+ */
24
+
25
+ import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
26
+ import fs from 'node:fs';
27
+ import { tmpdir } from 'node:os';
28
+ import { join } from 'node:path';
29
+
30
+ import { getDb } from '@/server/db.server';
31
+ import { saveHarnessSession } from '@/server/lib/harness/session-store.server';
32
+ import { clearSessionFileCaches } from '@/server/lib/omp/session/files';
33
+ import { invalidateOmpSidebarData } from '@/server/lib/omp/session/reader';
34
+ import { loadSidebarStructure } from '@/server/lib/omp/session/sidebar-data.server';
35
+ import { deleteSession } from '@/server/routes/sessions/delete';
36
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
37
+ import { removeDir } from '@/test-support/remove-dir';
38
+
39
+ /** The sidebar build spawns `git worktree list` for a folder with sessions. */
40
+ setDefaultTimeout(30_000);
41
+
42
+ const saved = {
43
+ agentDir: Bun.env.PI_CODING_AGENT_DIR,
44
+ mock: Bun.env.MOCK,
45
+ sync: Bun.env.SYNC_WORKSPACE,
46
+ };
47
+
48
+ let root = '';
49
+ let sessionsRoot = '';
50
+ let project = '';
51
+ let folderId = 0;
52
+
53
+ beforeAll(async () => {
54
+ root = await fs.promises.mkdtemp(join(tmpdir(), 'omc-delete-acp-'));
55
+ const agent = join(root, 'agent');
56
+ sessionsRoot = join(agent, 'sessions');
57
+ await fs.promises.mkdir(sessionsRoot, { recursive: true });
58
+ project = join(root, 'project');
59
+ await fs.promises.mkdir(project, { recursive: true });
60
+
61
+ Bun.env.PI_CODING_AGENT_DIR = agent;
62
+ Bun.env.MOCK = 'false';
63
+ Bun.env.SYNC_WORKSPACE = 'false';
64
+ });
65
+
66
+ afterAll(async () => {
67
+ if (saved.agentDir === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
68
+ else Bun.env.PI_CODING_AGENT_DIR = saved.agentDir;
69
+ if (saved.mock === undefined) delete Bun.env.MOCK;
70
+ else Bun.env.MOCK = saved.mock;
71
+ if (saved.sync === undefined) delete Bun.env.SYNC_WORKSPACE;
72
+ else Bun.env.SYNC_WORKSPACE = saved.sync;
73
+ await releaseDb();
74
+ removeDir(root);
75
+ });
76
+
77
+ beforeEach(async () => {
78
+ await isolateDb();
79
+ const db = await getDb();
80
+ await db.run('INSERT INTO workspace_folders (name, project_path) VALUES (?, ?)', ['ws', project]);
81
+ const row = await db.get<{ id: number }>('SELECT id FROM workspace_folders ORDER BY id DESC LIMIT 1');
82
+ folderId = Number(row?.id);
83
+ await fs.promises.rm(join(sessionsRoot, 'project'), { recursive: true, force: true });
84
+ invalidateOmpSidebarData();
85
+ clearSessionFileCaches();
86
+ });
87
+
88
+ async function deleteSessionRoute(sessionId: string): Promise<Response> {
89
+ return (await deleteSession({
90
+ request: new Request(`http://localhost/api/sessions/${sessionId}`, { method: 'DELETE' }),
91
+ params: { sessionId },
92
+ } as never)) as Response;
93
+ }
94
+
95
+ /** The row the sidebar would draw for this id, after a real rebuild. */
96
+ async function sidebarRow(sessionId: string) {
97
+ invalidateOmpSidebarData();
98
+ clearSessionFileCaches();
99
+ const structure = await loadSidebarStructure();
100
+ const folder = structure.folders.find((entry) => Number(entry.id) === folderId);
101
+ return (folder?.sessions ?? []).find((entry) => String(entry.id) === sessionId);
102
+ }
103
+
104
+ /** One omp session file: the transcript `omp-acp` writes over ACP. */
105
+ async function writeOmpSession(id: string): Promise<void> {
106
+ const dir = join(sessionsRoot, 'project');
107
+ await fs.promises.mkdir(dir, { recursive: true });
108
+ const now = new Date().toISOString();
109
+ const lines = [
110
+ JSON.stringify({ type: 'session', id, cwd: project, timestamp: now }),
111
+ JSON.stringify({
112
+ type: 'message', id: `${id}-m1`, parentId: null, timestamp: now,
113
+ message: { role: 'user', content: 'hello' },
114
+ }),
115
+ ];
116
+ await Bun.write(join(dir, `${id}.jsonl`), `${lines.join('\n')}\n`);
117
+ }
118
+
119
+ /** A live session in the shared registry, as a driver would have registered it. */
120
+ function registerLive(session: Record<string, unknown>): void {
121
+ globalThis.__ompSessions ??= new Map();
122
+ globalThis.__ompSessions.set(String(session.sessionId), session as never);
123
+ }
124
+
125
+ function forgetLive(sessionId: string): void {
126
+ globalThis.__ompSessions?.delete(sessionId);
127
+ }
128
+
129
+ describe('deleting an ACP chat', () => {
130
+ test('the record is the thing removed — a chat with no transcript is a 200, not a 404', async () => {
131
+ const id = 'ses_acp_only';
132
+ await saveHarnessSession({ sessionId: id, harness: 'opencode', agentSessionId: id, cwd: project });
133
+ expect(await sidebarRow(id)).toBeDefined();
134
+
135
+ const res = await deleteSessionRoute(id);
136
+ expect(res.status).toBe(200);
137
+
138
+ expect(await sidebarRow(id)).toBeUndefined();
139
+ const db = await getDb();
140
+ expect(await db.get('SELECT session_id FROM harness_sessions WHERE session_id = ?', [id])).toBeNull();
141
+ });
142
+
143
+ test('the goal and usage rows keyed to the chat go with it', async () => {
144
+ const id = 'ses_acp_extras';
145
+ await saveHarnessSession({ sessionId: id, harness: 'claude', agentSessionId: id, cwd: project });
146
+ const db = await getDb();
147
+ await db.run('INSERT INTO harness_goal_state (session_id, plan, updated_at) VALUES (?, 1, 1)', [id]);
148
+ await db.run('INSERT INTO harness_usage_state (session_id, updated_at) VALUES (?, 1)', [id]);
149
+
150
+ expect((await deleteSessionRoute(id)).status).toBe(200);
151
+
152
+ // Same final rule as the composer's Context ring: a deleted chat has no
153
+ // stored goal or usage left to answer from a reload.
154
+ expect(await db.get('SELECT session_id FROM harness_goal_state WHERE session_id = ?', [id])).toBeNull();
155
+ expect(await db.get('SELECT session_id FROM harness_usage_state WHERE session_id = ?', [id])).toBeNull();
156
+ });
157
+
158
+ test('an archived ACP chat disappears instead of coming back unarchived', async () => {
159
+ const id = 'ses_acp_archived';
160
+ await saveHarnessSession({ sessionId: id, harness: 'opencode', agentSessionId: id, cwd: project });
161
+ const db = await getDb();
162
+ await db.run('INSERT INTO archived_sessions (session_id) VALUES (?)', [id]);
163
+ expect((await sidebarRow(id))?.is_archived).toBe(1);
164
+
165
+ expect((await deleteSessionRoute(id)).status).toBe(200);
166
+
167
+ // The row is GONE, not merely moved out of the archive view.
168
+ expect(await sidebarRow(id)).toBeUndefined();
169
+ expect(await db.all('SELECT session_id FROM archived_sessions WHERE session_id = ?', [id])).toEqual([]);
170
+ });
171
+
172
+ test('an `omp-acp` chat whose JSONL the scan found is not re-listed from its record', async () => {
173
+ const id = '11111111-1111-4111-8111-111111111111';
174
+ await writeOmpSession(id);
175
+ await saveHarnessSession({ sessionId: id, harness: 'omp-acp', agentSessionId: id, cwd: project });
176
+ expect(await sidebarRow(id)).toBeDefined();
177
+
178
+ expect((await deleteSessionRoute(id)).status).toBe(200);
179
+
180
+ expect(await sidebarRow(id)).toBeUndefined();
181
+ expect(fs.existsSync(join(sessionsRoot, 'project', `${id}.jsonl`))).toBe(false);
182
+ });
183
+
184
+ test('a busy ACP chat is refused and left alive', async () => {
185
+ const id = 'ses_acp_busy';
186
+ await saveHarnessSession({ sessionId: id, harness: 'claude', agentSessionId: id, cwd: project });
187
+ let destroyed = false;
188
+ registerLive({
189
+ sessionId: id,
190
+ harness: 'claude',
191
+ isAlive: () => true,
192
+ isBusy: () => true,
193
+ destroyAndWait: async () => { destroyed = true; },
194
+ });
195
+
196
+ try {
197
+ const res = await deleteSessionRoute(id);
198
+ expect(res.status).toBe(409);
199
+ expect(await res.json()).toMatchObject({ code: 'session_busy' });
200
+ expect(destroyed).toBe(false);
201
+ expect(await sidebarRow(id)).toBeDefined();
202
+ } finally {
203
+ forgetLive(id);
204
+ }
205
+ });
206
+
207
+ test('an idle live ACP chat is torn down before its rows are purged', async () => {
208
+ const id = 'ses_acp_idle';
209
+ await saveHarnessSession({ sessionId: id, harness: 'claude', agentSessionId: id, cwd: project });
210
+ let destroyed = false;
211
+ registerLive({
212
+ sessionId: id,
213
+ harness: 'claude',
214
+ isAlive: () => true,
215
+ isBusy: () => false,
216
+ destroyAndWait: async () => { destroyed = true; },
217
+ });
218
+
219
+ try {
220
+ expect((await deleteSessionRoute(id)).status).toBe(200);
221
+ expect(destroyed).toBe(true);
222
+ expect(await sidebarRow(id)).toBeUndefined();
223
+ } finally {
224
+ forgetLive(id);
225
+ }
226
+ });
227
+ });