@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
@@ -23,6 +23,7 @@ import { fetchOmpRegistrySnapshot } from '@/server/lib/models/provider-registry.
23
23
  import { readProviderIconUrls } from '@/server/lib/models/provider-icon.server';
24
24
  import { buildDeepSeekReport } from '@/server/lib/usage/deepseek';
25
25
  import { buildKenariReport } from '@/server/lib/usage/kenari';
26
+ import { buildNewApiReports } from '@/server/lib/usage/new-api';
26
27
  import { fetchOmpUsageSnapshot, type OmpUsageSnapshot } from '@/server/lib/usage/omp-usage.server';
27
28
  import { fetchVendorBalance, type VendorBalance } from '@/server/lib/usage/vendor-balance.server';
28
29
  import { kenariProviderSlugs, listCredentialedProviders, type CredentialedProvider } from '@/server/lib/usage/provider-key';
@@ -123,10 +124,13 @@ export async function buildUsageProviders(options: { force?: boolean } = {}): Pr
123
124
  // one (`kenari2`) with no quota card while its key was never read. DeepSeek
124
125
  // still resolves by its canonical slug.
125
126
  const kenariSlugs = await kenariProviderSlugs(credentials.keys());
126
- const [kenariReports, deepseek, balances] = await Promise.all([
127
+ const [kenariReports, deepseek, balances, gateways] = await Promise.all([
127
128
  Promise.all([...kenariSlugs].map(async (slug) => [slug, await buildKenariReport(slug)] as const)),
128
129
  credentials.has('deepseek') ? buildDeepSeekReport() : Promise.resolve(null),
129
130
  loadVendorBalances([...credentials.keys()]),
131
+ // Self-hosted relays answer on the provider's OWN base URL, so they cannot
132
+ // live in `vendor-balance`'s fixed-URL table.
133
+ buildNewApiReports(credentials.keys()),
130
134
  ]);
131
135
  const kenariBySlug = new Map<string, KenariUsageReport>();
132
136
  for (const [slug, report] of kenariReports) {
@@ -137,6 +141,7 @@ export async function buildUsageProviders(options: { force?: boolean } = {}): Pr
137
141
  for (const [slug, sources] of credentials) {
138
142
  const report = snapshot.reports.get(slug);
139
143
  const balance = balances.get(slug);
144
+ const gateway = gateways.get(slug);
140
145
  const { tracked, limitsUnavailable } = resolveUsageTracking(slug, snapshot);
141
146
  const summary: UsageProviderSummary = {
142
147
  id: slug,
@@ -144,8 +149,8 @@ export async function buildUsageProviders(options: { force?: boolean } = {}): Pr
144
149
  ...(iconUrls.get(slug) ? { iconUrl: iconUrls.get(slug) } : {}),
145
150
  credentialSources: sources,
146
151
  // A vendor balance is real quota data even when omp has no adapter for it.
147
- tracked: tracked || Boolean(balance && balance.limits.length > 0),
148
- limits: [...(report?.limits ?? []), ...(balance?.limits ?? [])],
152
+ tracked: tracked || Boolean(balance?.limits.length) || Boolean(gateway?.limits.length),
153
+ limits: [...(report?.limits ?? []), ...(balance?.limits ?? []), ...(gateway?.limits ?? [])],
149
154
  ...(limitsUnavailable ? { limitsUnavailable: true } : {}),
150
155
  ...(report?.notes ? { notes: report.notes } : {}),
151
156
  };
@@ -157,6 +162,8 @@ export async function buildUsageProviders(options: { force?: boolean } = {}): Pr
157
162
  } else if (slug === 'deepseek' && deepseek) {
158
163
  summary.deepseek = deepseek;
159
164
  if (deepseek.error) summary.error = deepseek.error;
165
+ } else if (gateway?.error) {
166
+ summary.error = gateway.error;
160
167
  } else if (balance?.error && !summary.error) {
161
168
  // Only surface a balance failure when nothing richer already reported one.
162
169
  summary.error = balance.error;
@@ -24,10 +24,11 @@
24
24
 
25
25
  import { readOmpProviderApiKey } from '@/server/lib/omp/core/auth-credentials';
26
26
  import { loadProviderEntries } from '@/server/lib/usage/provider-key';
27
+ import { fetchProviderJson } from '@/server/lib/usage/vendor-http';
28
+ import { num, usdWindow } from '@/server/lib/usage/window';
27
29
  import { isRecord } from '@/shared/lib/util/guards';
28
- import type { UsageLimitWindow, UsageWindowStatus } from '@/shared/types';
30
+ import type { UsageLimitWindow } from '@/shared/types';
29
31
 
30
- const FETCH_TIMEOUT_MS = 10_000;
31
32
  const MASKED_KEY_PATTERN = /•{3,}/;
32
33
 
33
34
  /** A vendor balance adapter: where to ask, and how to read the answer. */
@@ -41,46 +42,6 @@ interface BalanceAdapter {
41
42
  parse: (payload: unknown) => UsageLimitWindow[];
42
43
  }
43
44
 
44
- function num(value: unknown): number | undefined {
45
- if (typeof value === 'number' && Number.isFinite(value)) return value;
46
- if (typeof value === 'string' && value.trim() !== '') {
47
- const parsed = Number(value);
48
- if (Number.isFinite(parsed)) return parsed;
49
- }
50
- return undefined;
51
- }
52
-
53
- /** Status for a credit window: exhausted at zero remaining, else ok. */
54
- function balanceStatus(remaining: number | undefined): UsageWindowStatus {
55
- if (remaining === undefined) return 'unknown';
56
- return remaining <= 0 ? 'exhausted' : 'ok';
57
- }
58
-
59
- /** One USD window from a balance; `limit` is omitted when the vendor has none. */
60
- function usdWindow(input: {
61
- id: string;
62
- label: string;
63
- used?: number;
64
- limit?: number;
65
- remaining?: number;
66
- note?: string;
67
- }): UsageLimitWindow {
68
- const usedFraction = input.limit && input.limit > 0 && input.used !== undefined
69
- ? input.used / input.limit
70
- : undefined;
71
- return {
72
- id: input.id,
73
- label: input.label,
74
- unit: 'usd',
75
- status: balanceStatus(input.remaining),
76
- ...(input.used !== undefined ? { used: input.used } : {}),
77
- ...(input.limit !== undefined ? { limit: input.limit } : {}),
78
- ...(input.remaining !== undefined ? { remaining: input.remaining } : {}),
79
- ...(usedFraction !== undefined ? { usedFraction } : {}),
80
- ...(input.note ? { notes: [input.note] } : {}),
81
- };
82
- }
83
-
84
45
  /** Pull `data` (or the root) out of a vendor envelope. */
85
46
  function envelope(payload: unknown): Record<string, unknown> {
86
47
  if (!isRecord(payload)) throw new Error('unexpected balance response');
@@ -263,17 +224,7 @@ export async function fetchVendorBalance(slug: string): Promise<VendorBalance |
263
224
  const apiKey = await resolveVendorKey(adapter);
264
225
  if (!apiKey) return null;
265
226
  try {
266
- const response = await fetch(adapter.url, {
267
- headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
268
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
269
- });
270
- if (response.status === 401 || response.status === 403) {
271
- return { limits: [], error: `${adapter.slug} rejected the API key (HTTP ${response.status}).` };
272
- }
273
- if (response.status < 200 || response.status >= 300) {
274
- return { limits: [], error: `${adapter.slug} balance request failed (HTTP ${response.status}).` };
275
- }
276
- const limits = adapter.parse(await response.json());
227
+ const limits = adapter.parse(await fetchProviderJson(adapter.url, apiKey, adapter.slug));
277
228
  return { limits };
278
229
  } catch (error) {
279
230
  return {
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * One authenticated GET against a provider's own balance/usage endpoint.
8
+ *
9
+ * Every balance source needs the same three answers — key rejected, request
10
+ * failed, response is not JSON — and they must read the same on every card, so
11
+ * the status handling lives here rather than in each adapter.
12
+ */
13
+
14
+ const FETCH_TIMEOUT_MS = 10_000;
15
+
16
+ /**
17
+ * Fetch and parse JSON, or throw an error whose message is safe to show in the
18
+ * provider card (it names the provider, never the credential).
19
+ */
20
+ export async function fetchProviderJson(url: string, apiKey: string, label: string): Promise<unknown> {
21
+ let response: Response;
22
+ try {
23
+ response = await fetch(url, {
24
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
25
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
26
+ });
27
+ } catch (error) {
28
+ throw new Error(error instanceof Error ? error.message : `${label} balance request failed`);
29
+ }
30
+ if (response.status === 401 || response.status === 403) {
31
+ throw new Error(`${label} rejected the API key (HTTP ${response.status}).`);
32
+ }
33
+ if (response.status < 200 || response.status >= 300) {
34
+ throw new Error(`${label} balance request failed (HTTP ${response.status}).`);
35
+ }
36
+ try {
37
+ return await response.json();
38
+ } catch {
39
+ throw new Error(`${label} returned an unreadable balance response.`);
40
+ }
41
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The USD window shape every provider-reported credit source produces
8
+ * (OpenRouter's key limits, a New API gateway's billing endpoints, …).
9
+ *
10
+ * One builder: `remaining` means the same thing on every card, and a
11
+ * vendor-specific copy drifts the moment one of them is "fixed".
12
+ */
13
+
14
+ import type { UsageLimitWindow, UsageWindowStatus } from '@/shared/types';
15
+
16
+ /** A finite number from a JSON value, including the numeric strings vendors send. */
17
+ export function num(value: unknown): number | undefined {
18
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
19
+ if (typeof value === 'string' && value.trim() !== '') {
20
+ const parsed = Number(value);
21
+ if (Number.isFinite(parsed)) return parsed;
22
+ }
23
+ return undefined;
24
+ }
25
+
26
+ /** Status for a credit window: exhausted at zero remaining, else ok. */
27
+ function balanceStatus(remaining: number | undefined): UsageWindowStatus {
28
+ if (remaining === undefined) return 'unknown';
29
+ return remaining <= 0 ? 'exhausted' : 'ok';
30
+ }
31
+
32
+ /** One USD window from a balance; `limit` is omitted when the vendor has none. */
33
+ export function usdWindow(input: {
34
+ id: string;
35
+ label: string;
36
+ used?: number;
37
+ limit?: number;
38
+ remaining?: number;
39
+ note?: string;
40
+ }): UsageLimitWindow {
41
+ const usedFraction = input.limit && input.limit > 0 && input.used !== undefined
42
+ ? input.used / input.limit
43
+ : undefined;
44
+ return {
45
+ id: input.id,
46
+ label: input.label,
47
+ unit: 'usd',
48
+ status: balanceStatus(input.remaining),
49
+ ...(input.used !== undefined ? { used: input.used } : {}),
50
+ ...(input.limit !== undefined ? { limit: input.limit } : {}),
51
+ ...(input.remaining !== undefined ? { remaining: input.remaining } : {}),
52
+ ...(usedFraction !== undefined ? { usedFraction } : {}),
53
+ ...(input.note ? { notes: [input.note] } : {}),
54
+ };
55
+ }
@@ -11,6 +11,7 @@ import { assertBtwIdle } from '@/server/lib/btw/service.server';
11
11
  import { loadPersistedModes } from '@/server/lib/omp/session/modes';
12
12
  import { isModeCommandType, modeCommandPrompt, parseModeRequest, parseModeSelection } from '@/server/lib/omp/mode/request';
13
13
  import { kabmoModeEnv } from '@/server/lib/omp/extensions/locator';
14
+ import { mintAgentEnvironment, rememberAgentToken } from '@/server/lib/sessions/agent-token.server';
14
15
  import { resetGoalDriverState } from '@/server/lib/omp/session/goal-driver.server';
15
16
  import { forwardToPeer, isPeerRelayed, peerOriginForSession } from '@/server/lib/omp/rpc/peer-proxy.server';
16
17
  import { applyHarnessMode, resumeRecordedHarnessSession } from '@/server/routes/agent/harness-command';
@@ -176,7 +177,19 @@ export async function sendCommand({ params, request }: ActionFunctionArgs) {
176
177
  const asked = body.type === 'set_model' && typeof body.provider === 'string' && typeof body.modelId === 'string'
177
178
  ? { provider: body.provider, modelId: body.modelId }
178
179
  : undefined;
179
- const { session } = await startRpcSession(sessionId, filePath, cwd, recordedCwd, spawnMode, modeEnv, asked);
180
+ const { token, env: agentEnv } = mintAgentEnvironment();
181
+ const { session } = await startRpcSession(
182
+ sessionId,
183
+ filePath,
184
+ cwd,
185
+ recordedCwd,
186
+ spawnMode,
187
+ { ...(modeEnv ?? {}), ...agentEnv },
188
+ asked,
189
+ );
190
+ await rememberAgentToken(sessionId, token).catch((cause: unknown) => {
191
+ console.error(`[sessions] could not record the agent token for ${sessionId}:`, cause);
192
+ });
180
193
  const result = await session.send(forwarded);
181
194
  // Same Resume nudge as the live path: a resumed goal must not sit idle
182
195
  // waiting for the operator's next message.
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { freshProbe } from '@/server/lib/harness/probe-cache.server';
17
17
  import { startAcpSession } from '@/server/lib/harness/spawn.server';
18
+ import { mintAgentEnvironment, rememberAgentToken } from '@/server/lib/sessions/agent-token.server';
18
19
  import { knownHarness, loadHarnessSession, repointHarnessSession } from '@/server/lib/harness/session-store.server';
19
20
  import { selectValues } from '@/server/lib/harness/launch';
20
21
  import { harnessOfSession } from '@/server/lib/omp/rpc/session-registry';
@@ -39,9 +40,10 @@ import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
39
40
  *
40
41
  * - an id this build's catalog no longer lists spawns NOTHING (a retired
41
42
  * adapter must not be guessed at from a stale row);
42
- * - a harness whose probe says it cannot `session/load` is refused in words,
43
- * because the only alternative is starting a FRESH agent session under this
44
- * chat's id — which would silently throw the conversation away.
43
+ * - a harness whose probe says it can neither `session/load` nor
44
+ * `session/resume` is refused in words, because the only alternative is
45
+ * starting a FRESH agent session under this chat's id — which would silently
46
+ * throw the conversation away.
45
47
  *
46
48
  * `omp-acp` is excluded even though ACP is what it speaks. It WRITES a session
47
49
  * file, so the locator resumes it in place over RPC — the same chat, the same
@@ -62,9 +64,10 @@ export async function resumeRecordedHarnessSession(
62
64
 
63
65
  const label = harnessDescriptor(harness)?.label ?? harness;
64
66
  const probe = await freshProbe(harness);
65
- if (probe?.capabilities.loadSession === false) {
66
- throw new Error(`${label} cannot restore this chat: it does not support session/load.`);
67
+ if (probe && !probe.capabilities.loadSession && !probe.capabilities.resumeSession) {
68
+ throw new Error(`${label} cannot restore this chat: it supports neither session/load nor session/resume.`);
67
69
  }
70
+ const { token, env } = mintAgentEnvironment();
68
71
  const { session, realSessionId } = await startAcpSession({
69
72
  harness,
70
73
  sessionId,
@@ -77,6 +80,10 @@ export async function resumeRecordedHarnessSession(
77
80
  resumeAgentSessionId: record.agentSessionId || sessionId,
78
81
  cwd: record.cwd,
79
82
  accessMode,
83
+ env,
84
+ });
85
+ await rememberAgentToken(sessionId, token).catch((cause: unknown) => {
86
+ console.error(`[sessions] could not record the agent token for ${sessionId}:`, cause);
80
87
  });
81
88
  // A forking load answers a NEW agent id, and the spawn recorded that id as its
82
89
  // own row — a second sidebar row for one conversation. The chat keeps ITS id
@@ -10,6 +10,8 @@ import { parseModeSelection } from '@/server/lib/omp/mode/request';
10
10
  import { projectModelForCwd } from '@/server/lib/workspace/project-model.server';
11
11
  import { HARNESS_IDS, type HarnessId } from '@/shared/lib/harness/catalog';
12
12
  import { startAcpSession } from '@/server/lib/harness/spawn.server';
13
+ import { mintAgentEnvironment, rememberAgentToken } from '@/server/lib/sessions/agent-token.server';
14
+ import { isMockMode } from '@/server/mock.server';
13
15
 
14
16
  /** The model-dropdown persists its selection here (actionType 'selectModel');
15
17
  * a spawn that arrives without an explicit provider/modelId falls back to it. */
@@ -40,6 +42,14 @@ async function loadPersistedModel(): Promise<{ provider: string; modelId: string
40
42
  // omp itself, so Kabmo adopts it via the URL param after the response.
41
43
  export async function action({ request }: ActionFunctionArgs) {
42
44
  try {
45
+ // MOCK mode has no agent process to start, and saying so with a CODE is what
46
+ // lets the composer take its simulated path instead of reporting "Prompt not
47
+ // sent: omp binary not found" — measured in the demo shell on a host without
48
+ // omp, where the landing composer silently did nothing. Real spawn failures
49
+ // still report, because they carry no `mock_mode`.
50
+ if (isMockMode()) {
51
+ return json({ error: 'Mock mode runs no agent process', code: 'mock_mode' }, { status: 400 });
52
+ }
43
53
  const body = await request.json().catch(() => null);
44
54
  if (!body || typeof body.type !== 'string' || !body.type.trim()) {
45
55
  return json({ error: 'command type is required', code: 'command_type_required' }, { status: 400 });
@@ -151,6 +161,7 @@ async function startAcpChat({ harness, cwd, body, model, accessMode }: {
151
161
  const projectModel = await projectModelForCwd(await getDb(), cwd);
152
162
  const thinkingLevel = typeof body.thinkingLevel === 'string' ? body.thinkingLevel : null;
153
163
  const mode = harnessModeSelection(body);
164
+ const { token, env: agentEnv } = mintAgentEnvironment();
154
165
  const { session, realSessionId } = await startAcpSession({
155
166
  harness,
156
167
  sessionId: `__new__${Bun.randomUUIDv7()}`,
@@ -159,6 +170,10 @@ async function startAcpChat({ harness, cwd, body, model, accessMode }: {
159
170
  thinkingLevel,
160
171
  mode,
161
172
  accessMode,
173
+ env: agentEnv,
174
+ });
175
+ await rememberAgentToken(realSessionId, token).catch((cause: unknown) => {
176
+ console.error(`[sessions] could not record the agent token for ${realSessionId}:`, cause);
162
177
  });
163
178
 
164
179
  if (type === 'ensure_session') {
@@ -46,6 +46,8 @@ async function handleStreamingRequest(request: Request) {
46
46
  headers: { 'Cache-Control': 'no-cache, no-transform', 'X-Accel-Buffering': 'no' },
47
47
  async onStart(handlers) {
48
48
  let isAborted = false;
49
+ /** The reason the simulated stream threw, when it did. */
50
+ let failure: string | null = null;
49
51
  const abortListener = () => {
50
52
  isAborted = true;
51
53
  };
@@ -94,13 +96,16 @@ async function handleStreamingRequest(request: Request) {
94
96
  } catch (err: unknown) {
95
97
  if (!isAborted) {
96
98
  const message = err instanceof Error ? err.message : 'Streaming execution error';
99
+ failure = message;
97
100
  sendEvent('error', { error: message });
98
101
  }
99
102
  } finally {
100
103
  request.signal.removeEventListener('abort', abortListener);
101
104
  // Terminal badge, not a deletion: opening the session acknowledges it,
102
- // exactly as it does for a real run. An aborted stream is `abort`.
103
- void markStreamStatus(sessionId, isAborted ? 'abort' : 'finish');
105
+ // exactly as it does for a real run. An aborted stream is `abort`, and a
106
+ // stream that threw carries its reason so the same failure notification
107
+ // fires here as on a real run.
108
+ void markStreamStatus(sessionId, isAborted ? 'abort' : 'finish', undefined, failure);
104
109
  localRuns().delete(sessionId);
105
110
  handlers.close();
106
111
  }
@@ -198,11 +198,19 @@ describe('adding a provider to an environment harness', () => {
198
198
  }));
199
199
  const payload = await response.json() as { config?: { env: string }; envWritten?: string[]; error?: string };
200
200
  expect(payload.error).toBeUndefined();
201
- expect(payload.envWritten).toEqual(['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL']);
201
+ expect(payload.envWritten).toEqual([
202
+ 'ANTHROPIC_BASE_URL',
203
+ 'ANTHROPIC_AUTH_TOKEN',
204
+ 'ANTHROPIC_MODEL',
205
+ 'ANTHROPIC_DEFAULT_SONNET_MODEL',
206
+ ]);
202
207
  // `/v1` stripped: the SDK appends `/v1/messages` itself.
203
208
  expect(payload.config?.env).toContain(`ANTHROPIC_BASE_URL=${baseUrl.replace(/\/v1$/, '')}`);
204
209
  expect(payload.config?.env).toContain('ANTHROPIC_AUTH_TOKEN=sk-claude');
205
210
  expect(payload.config?.env).toContain('ANTHROPIC_MODEL=claude-sonnet-5');
211
+ // The picker's `sonnet` alias now resolves to the id this endpoint serves;
212
+ // unpinned it would send the literal alias and answer 400.
213
+ expect(payload.config?.env).toContain('ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-5');
206
214
  });
207
215
 
208
216
  test('no name is refused before anything is written', async () => {
@@ -185,6 +185,10 @@ export async function applyProvider(target: HarnessId, candidate: Candidate, sou
185
185
  baseUrl: adaptBaseUrl(draft.baseUrl ?? '', 'root'),
186
186
  apiKey: draft.apiKey ?? '',
187
187
  ...(pinnedModel(planned, draft.models) ? { model: pinnedModel(planned, draft.models)! } : {}),
188
+ // The endpoint's own listing decides what each picker alias resolves to.
189
+ // Without it Claude Code sends the literal alias as the model id and the
190
+ // gateway answers 400.
191
+ models: draft.models,
188
192
  });
189
193
  if (Object.keys(env).length === 0) {
190
194
  return json({ error: `Nothing to write: "${candidate.id}" has no endpoint or key.` }, { status: 400 });
@@ -132,7 +132,7 @@ describe('importing a custom provider into claude', () => {
132
132
  // even though the source declares openai-completions.
133
133
  expect(payload.protocol).toBe('anthropic-messages');
134
134
  expect(payload.envWritten).toEqual(
135
- ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL'],
135
+ ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL'],
136
136
  );
137
137
  // The stub's `/v1` is stripped: the SDK appends `/v1/messages` itself.
138
138
  expect(payload.config?.env).toContain(`ANTHROPIC_BASE_URL=${baseUrl.replace(/\/v1$/, '')}`);
@@ -1,6 +1,7 @@
1
- import { actionBindings, type HandlerBinding } from '@/server/lib/route-adapter';
1
+ import { actionBindings, bindingsFor, type HandlerBinding } from '@/server/lib/route-adapter';
2
2
  import * as harnessRoot from '@/server/routes/harness/root';
3
3
  import * as harnessUpdate from '@/server/routes/harness/update';
4
+ import * as harnessUpdateStatus from '@/server/routes/harness/update-status';
4
5
  import * as harnessVersions from '@/server/routes/harness/versions';
5
6
 
6
7
  export const harnessBindings: HandlerBinding[] = [
@@ -8,6 +9,9 @@ export const harnessBindings: HandlerBinding[] = [
8
9
  // Static paths registered as their own routes. A `/api/harness/:id` parameter
9
10
  // route sharing this position is the shape that makes the parameter win the
10
11
  // match and hide the real handler behind a 405.
12
+ // The update's BACKGROUND progress is its own GET: `/api/harness/update` keeps
13
+ // answering the version rows for compatibility.
14
+ ...bindingsFor(harnessUpdateStatus, '/api/harness/update/status'),
11
15
  ...actionBindings(harnessUpdate.action, '/api/harness/update', harnessVersions.loader),
12
16
  ...actionBindings(harnessRoot.action, '/api/harness/versions', harnessVersions.loader),
13
17
  ];
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * `GET /api/harness/update/status` — every harness's background update record.
8
+ *
9
+ * The POST answers in milliseconds and the install keeps running in a detached
10
+ * worker, so this is how the dialog learns where each run is and whether it
11
+ * finished. One record per harness, because two presses are a queue: a run
12
+ * installing and a run waiting its turn are two different rows.
13
+ *
14
+ * A poll is also where the SERVER acts on the records: it applies the
15
+ * post-install side effects (`forgetProbe`, the launch-line repoint), settles a
16
+ * run that died without reporting, and starts the next waiting one. The ticker
17
+ * in `update-queue.server.ts` does the same without a browser, so this route is
18
+ * a read with the same pass in front of it — never the only thing keeping the
19
+ * queue moving.
20
+ *
21
+ * An empty array is a real answer — no update has ever run — and it must not be
22
+ * a 404: the About card asks this on every open, and a "not found" would read as
23
+ * a broken route rather than "nothing is running".
24
+ */
25
+
26
+ import { json, NO_STORE_HEADERS } from '@/server/lib/remix-compat';
27
+ import { pumpUpdateQueue } from '@/server/lib/harness/update-queue.server';
28
+
29
+ export async function loader() {
30
+ const jobs = await pumpUpdateQueue();
31
+ return json({ jobs }, { headers: NO_STORE_HEADERS });
32
+ }
@@ -0,0 +1,156 @@
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 accepts a run as a
10
+ * background job and answers `202`. These cases pin the answers that do NOT
11
+ * spawn anything — the refusals and the progress read — because those are the
12
+ * shapes the dialog branches on, and a wrong status there either starts a
13
+ * competing install or reports success it never observed.
14
+ *
15
+ * The queue's own decision (a second harness is accepted and waits) is pinned in
16
+ * `update-queue.test.ts`: reaching it through this route means planning an
17
+ * install, which reads the npm registry and probes the machine.
18
+ */
19
+
20
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
21
+ import { mkdtempSync, rmSync } from 'node:fs';
22
+ import { tmpdir } from 'node:os';
23
+ import { join } from 'node:path';
24
+ import { action } from '@/server/routes/harness/update';
25
+ import { loader as statusLoader } from '@/server/routes/harness/update-status';
26
+ import { writeUpdateJob } from '@/server/lib/harness/update-job-store';
27
+ import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
28
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
29
+
30
+ let dir = '';
31
+ let originalDataDir: string | undefined;
32
+
33
+ beforeEach(() => {
34
+ originalDataDir = Bun.env.KABMO_DATA_DIR;
35
+ dir = mkdtempSync(join(tmpdir(), 'kabmo-update-route-'));
36
+ Bun.env.KABMO_DATA_DIR = dir;
37
+ });
38
+
39
+ afterEach(() => {
40
+ if (originalDataDir === undefined) delete Bun.env.KABMO_DATA_DIR;
41
+ else Bun.env.KABMO_DATA_DIR = originalDataDir;
42
+ rmSync(dir, { recursive: true, force: true });
43
+ });
44
+
45
+ function post(harness: string): Parameters<typeof action>[0] {
46
+ return {
47
+ request: new Request('http://localhost/api/harness/update', {
48
+ method: 'POST',
49
+ headers: { 'content-type': 'application/json' },
50
+ body: JSON.stringify({ harness }),
51
+ }),
52
+ params: {},
53
+ } as Parameters<typeof action>[0];
54
+ }
55
+
56
+ function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
57
+ return {
58
+ harness: 'claude',
59
+ label: 'claude',
60
+ startedAt: Date.now(),
61
+ finishedAt: null,
62
+ queuedAt: null,
63
+ pid: process.pid,
64
+ steps: [{ part: 'adapter', command: 'npm install -g x', argv: ['npm', 'install', '-g', 'x'], state: 'running', code: null }],
65
+ output: '',
66
+ ok: null,
67
+ message: null,
68
+ applied: false,
69
+ repointed: null,
70
+ ...overrides,
71
+ };
72
+ }
73
+
74
+ describe('POST /api/harness/update', () => {
75
+ test('an unknown harness is refused before anything runs', async () => {
76
+ const response = (await action(post('nope'))) as Response;
77
+ expect(response.status).toBe(400);
78
+ expect(((await response.json()) as { error: string }).error).toBe('Unknown harness');
79
+ });
80
+
81
+ test('a vendor-managed harness is refused with the reason', async () => {
82
+ // `cursor` is updated by its own installer; Kabmo replacing it would be an
83
+ // install it did not make.
84
+ const response = (await action(post('cursor'))) as Response;
85
+ expect(response.status).toBe(400);
86
+ const payload = (await response.json()) as { error: string; code: string };
87
+ expect(payload.code).toBe('vendor_managed');
88
+ expect(payload.error).toContain('installed by its vendor');
89
+ });
90
+
91
+ test('a second press for the SAME harness is a 409 that names the run', async () => {
92
+ // Measured corruption vector: a reload forgot the run and offered the button,
93
+ // so two `npm install -g` wrote the same prefix at once. The record on disk is
94
+ // what refuses it now. A DIFFERENT harness is accepted and queued instead —
95
+ // see `update-queue.test.ts`.
96
+ await writeUpdateJob(job(), getHarnessUpdateStatusPath('claude'));
97
+ const response = (await action(post('claude'))) as Response;
98
+ expect(response.status).toBe(409);
99
+ const payload = (await response.json()) as { error: string; job: HarnessUpdateJob };
100
+ expect(payload.error).toContain('already running');
101
+ expect(payload.job.harness).toBe('claude');
102
+ });
103
+
104
+ test('a press for a harness that is already QUEUED says queued, not running', async () => {
105
+ await writeUpdateJob(
106
+ job({ harness: 'codex', label: 'codex', pid: null, queuedAt: Date.now() }),
107
+ getHarnessUpdateStatusPath('codex'),
108
+ );
109
+ const response = (await action(post('codex'))) as Response;
110
+ expect(response.status).toBe(409);
111
+ const payload = (await response.json()) as { error: string; job: HarnessUpdateJob };
112
+ expect(payload.error).toContain('already queued');
113
+ expect(payload.job.queuedAt).not.toBeNull();
114
+ });
115
+ });
116
+
117
+ describe('GET /api/harness/update/status', () => {
118
+ test('no run ever started is an empty list, not a 404', async () => {
119
+ const response = (await statusLoader()) as Response;
120
+ expect(response.status).toBe(200);
121
+ expect(((await response.json()) as { jobs: unknown[] }).jobs).toEqual([]);
122
+ });
123
+
124
+ test('a finished run is reported with its message', async () => {
125
+ await writeUpdateJob(job({
126
+ pid: null,
127
+ finishedAt: Date.now(),
128
+ ok: true,
129
+ applied: true,
130
+ message: 'claude updated (adapter) — check its status to read the new version',
131
+ }), getHarnessUpdateStatusPath('claude'));
132
+ const response = (await statusLoader()) as Response;
133
+ const { jobs } = (await response.json()) as { jobs: HarnessUpdateJob[] };
134
+ expect(jobs).toHaveLength(1);
135
+ expect(jobs[0].ok).toBe(true);
136
+ expect(jobs[0].message).toContain('claude updated');
137
+ });
138
+
139
+ test('an installing run and a QUEUED one are two records, and the queue is not started', async () => {
140
+ // The press that would have been a 409 is now a waiting record. The poll must
141
+ // report both, and the waiting one must stay waiting while the first installs
142
+ // — the whole point of one install at a time.
143
+ await writeUpdateJob(job(), getHarnessUpdateStatusPath('claude'));
144
+ await writeUpdateJob(
145
+ job({ harness: 'codex', label: 'codex', pid: null, queuedAt: Date.now() }),
146
+ getHarnessUpdateStatusPath('codex'),
147
+ );
148
+
149
+ const response = (await statusLoader()) as Response;
150
+ const { jobs } = (await response.json()) as { jobs: HarnessUpdateJob[] };
151
+ expect(jobs.map((entry) => entry.harness).sort()).toEqual(['claude', 'codex']);
152
+ const codex = jobs.find((entry) => entry.harness === 'codex');
153
+ expect(codex?.queuedAt).not.toBeNull();
154
+ expect(codex?.pid).toBeNull();
155
+ });
156
+ });