@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
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The body of `POST /api/sessions/:id/fork` for the fork composer.
8
+ *
9
+ * Same rule as the child-session spawn: a field the composer has no value for
10
+ * is OMITTED, so the server keeps what the source transcript already carries.
11
+ * A fork with no message is a real case — the branch is still created.
12
+ */
13
+
14
+ import type { AgentImage } from '@/shared/types';
15
+ import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
16
+
17
+ export interface ForkComposerPicks {
18
+ prompt?: string | null;
19
+ images?: AgentImage[] | null;
20
+ model?: { provider: string; modelId: string } | null;
21
+ thinkingLevel?: string | null;
22
+ accessMode?: ApprovalMode | null;
23
+ }
24
+
25
+ export function forkRequestBody(
26
+ anchorEntryId: string | null | undefined,
27
+ picks: ForkComposerPicks = {},
28
+ ): Record<string, unknown> {
29
+ const prompt = picks.prompt?.trim() ? picks.prompt.trim() : null;
30
+ const images = picks.images?.length ? picks.images : null;
31
+ const model = picks.model;
32
+ return {
33
+ ...(anchorEntryId ? { anchorEntryId } : {}),
34
+ ...(prompt ? { prompt } : {}),
35
+ ...(images ? { images } : {}),
36
+ ...(model?.provider && model.modelId ? { model } : {}),
37
+ // `auto` means "leave the source transcript's level alone".
38
+ ...(picks.thinkingLevel && picks.thinkingLevel !== 'auto'
39
+ ? { thinkingLevel: picks.thinkingLevel }
40
+ : {}),
41
+ ...(picks.accessMode ? { accessMode: picks.accessMode } : {}),
42
+ };
43
+ }
@@ -14,7 +14,7 @@
14
14
  */
15
15
 
16
16
  import { describe, expect, test } from 'bun:test';
17
- import { modeAvailability } from '@/client/hooks/chat/timeline/modes';
17
+ import { modeAvailability } from '@/client/hooks/chat/timeline/mode-availability';
18
18
 
19
19
  describe('modeAvailability', () => {
20
20
  test('omp RPC carries both modes', () => {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Which mode toggles a harness can actually honour.
8
+ *
9
+ * Pure, so the rule is testable without a render. Split from `modes.ts` when
10
+ * the compositor's ACP mode selector pushed that hook toward the file ceiling.
11
+ *
12
+ * Goal is available on every harness: Kabmo owns the record and the loop for
13
+ * ACP (`acp-goal.server.ts`), and omp carries the extension. Plan is different —
14
+ * it must be a real mode the agent publishes (`claude` does, `opencode` does
15
+ * not), except on omp's own two transports, which always expose the Plan
16
+ * toggle. An unknown harness keeps the old surface: the row may simply not have
17
+ * arrived yet.
18
+ */
19
+
20
+ export interface ModeCapabilities {
21
+ /** The harness that owns this chat, when the tab knows it. */
22
+ harness?: string | null;
23
+ /** The harness's own `mode` values, from its probe: `plan` is a real mode on
24
+ * the agents that publish one. */
25
+ modeValues?: string[];
26
+ }
27
+
28
+ export function modeAvailability(capabilities: ModeCapabilities): { plan: boolean; goal: boolean } {
29
+ if (capabilities.harness === 'omp-rpc') return { plan: true, goal: true };
30
+ if (!capabilities.harness) return { plan: true, goal: true };
31
+ if (capabilities.harness === 'omp-acp') return { plan: true, goal: true };
32
+ return { plan: capabilities.modeValues?.includes('plan') === true, goal: true };
33
+ }
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { useEffect, useRef } from 'preact/hooks';
17
17
  import type { KabmoModeSelection, GoalContinuation, GoalRecord } from '@/shared/lib/omp/mode/types';
18
+ import type { SessionModeState } from '@/shared/lib/harness/session-modes';
18
19
  import { KABMO_MODE_SIGNAL } from '@/shared/lib/omp/mode/client-signal';
19
20
  import { isModeMarker } from '@/shared/lib/omp/mode/constants';
20
21
  import { subscribeClientSignal } from '@/client/lib/signals';
@@ -27,7 +28,12 @@ import {
27
28
 
28
29
  /** The persisted selection, plus the goal record the same read returns. */
29
30
  export interface ModesResponse {
30
- modes?: KabmoModeSelection & { goalRecord?: GoalRecord | null; goalContinuation?: GoalContinuation | null };
31
+ modes?: KabmoModeSelection & {
32
+ goalRecord?: GoalRecord | null;
33
+ goalContinuation?: GoalContinuation | null;
34
+ /** The agent's own mode selector, for an ACP chat. */
35
+ mode?: SessionModeState | null;
36
+ };
31
37
  }
32
38
 
33
39
  /**
@@ -28,16 +28,28 @@ export async function postModeCommand(
28
28
  scope: 'plan' | 'goal',
29
29
  action: string,
30
30
  payload?: Record<string, unknown>,
31
+ ): Promise<ModeCommandResult> {
32
+ return postAgentCommand(sessionId, { type: MODE_COMMAND_TYPE, scope, action, ...(payload ? { payload } : {}) });
33
+ }
34
+
35
+ /** POST the agent's own `set_mode` command (an ACP mode selector value). */
36
+ export async function postSessionMode(sessionId: string, mode: string): Promise<ModeCommandResult> {
37
+ return postAgentCommand(sessionId, { type: 'set_mode', mode });
38
+ }
39
+
40
+ async function postAgentCommand(
41
+ sessionId: string,
42
+ body: Record<string, unknown>,
31
43
  ): Promise<ModeCommandResult> {
32
44
  try {
33
45
  const res = await fetch(`/api/agent/${encodeURIComponent(sessionId)}`, {
34
46
  method: 'POST',
35
47
  headers: { 'Content-Type': 'application/json' },
36
- body: JSON.stringify({ type: MODE_COMMAND_TYPE, scope, action, ...(payload ? { payload } : {}) }),
48
+ body: JSON.stringify(body),
37
49
  });
38
50
  if (!res.ok) {
39
- const body = (await res.json().catch(() => ({}))) as { error?: string };
40
- return { ok: false, error: body.error ?? 'Mode command failed' };
51
+ const answer = (await res.json().catch(() => ({}))) as { error?: string };
52
+ return { ok: false, error: answer.error ?? 'Mode command failed' };
41
53
  }
42
54
  return { ok: true };
43
55
  } catch (err) {
@@ -16,6 +16,7 @@
16
16
  import type { KabmoModeSelection, GoalContinuation, GoalRecord } from '@/shared/lib/omp/mode/types';
17
17
  import type { GoalActionResult } from '@/client/hooks/chat/timeline/goal-command';
18
18
  import type { ArmedGoal, GoalAction } from '@/shared/lib/omp/mode/actions';
19
+ import type { SessionModeState } from '@/shared/lib/harness/session-modes';
19
20
 
20
21
  export interface ChatTimelineModes {
21
22
  plan: boolean;
@@ -52,12 +53,16 @@ export interface ChatTimelineModes {
52
53
  * flag only hides a button: a stale client or a typed `/plan` used to reach
53
54
  * the child and turn both modes on. */
54
55
  planAvailable: boolean;
55
- /**
56
- * Whether Goal is offered at all. An ACP agent that is not omp has no
57
- * `/kabmo-mode` extension, so the toggle could only ever produce a refusal —
58
- * the same rule `planAvailable` already follows for the plan/goal exclusion.
56
+ /** Whether Goal is offered at all. An ACP agent that is not omp has no
57
+ * `/kabmo-mode` extension, so the toggle could only ever produce a refusal —
58
+ * the same rule `planAvailable` already follows for the plan/goal exclusion.
59
59
  */
60
60
  goalAvailable: boolean;
61
+ /** The agent's own mode selector (ACP). Null for omp and for an agent that
62
+ * publishes none; the composer then keeps the Plan toggle. */
63
+ sessionMode?: SessionModeState | null;
64
+ /** Move the agent's mode selector. */
65
+ onSelectSessionMode?: (value: string) => void;
61
66
  /**
62
67
  * The last refusal, from either side of the wire: the route's own error, or a
63
68
  * `KABMO_MODE_ERROR` the extension emitted (an unknown action, a missing
@@ -5,16 +5,7 @@
5
5
 
6
6
  /**
7
7
  * The composer's mode hydration, and the rule that a session never wears
8
- * another session's modes.
9
- *
10
- * The mode record is read per session (`GET /api/sessions/:id/modes`), and the
11
- * read FAILS for a session with no file — a pending `new-…` chat, a deleted
12
- * one: the route answers 404. Keeping the previous answer there meant the goal
13
- * strip rendered the last chat's objective over a chat that has no goal at all,
14
- * and the Goal button stayed pressed for a mode this session is not in.
15
- *
16
- * Rendered with `h()` (no JSX) against happy-dom, the same way
17
- * `ModeToggles.test.ts` and `GoalBanner.test.ts` do.
8
+ * another session's modes. Rendered with `h()` against happy-dom.
18
9
  */
19
10
 
20
11
  import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
@@ -27,15 +18,15 @@ import { KABMO_MODE_SIGNAL } from '@/shared/lib/omp/mode/client-signal';
27
18
  import { publishClientSignal } from '@/client/lib/signals';
28
19
 
29
20
  const DOM_GLOBALS = ['window', 'document', 'navigator', 'Node', 'Element', 'HTMLElement', 'Event', 'CustomEvent'] as const;
30
- /** The runner's own globals, restored on teardown — deleting them would strip natives (Event/CustomEvent) every later file needs. */const nativeGlobals: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
31
- /** The runner's own fetch — this file replaces it for the whole process. */
32
- /** The runner's own fetch, reached through `Bun` so a stub leaked onto the global cannot be mistaken for it. */
21
+ /** The runner's own globals, restored on teardown — deleting them would strip natives (Event/CustomEvent) every later file needs. */
22
+ const nativeGlobals: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
23
+ /** The runner's own fetch, reached through `Bun` so a leaked stub cannot be mistaken for it. */
33
24
  const nativeFetch = Bun.fetch;
34
25
 
35
26
  const WITH_GOAL = 'session-with-goal';
36
- /** A live goal whose loop has NOT reported a verdict — the state in which the
37
- * evaluating frame is the only activity to show. */
38
27
  const LIVE_GOAL = 'session-live-goal';
28
+ /** An ACP chat whose agent publishes a mode selector. */
29
+ const WITH_MODE = 'session-with-mode';
39
30
  const WITHOUT_FILE = 'new-1790756769131';
40
31
 
41
32
  let container: HTMLElement | undefined;
@@ -58,6 +49,8 @@ function Probe({ sessionId }: { sessionId: string }) {
58
49
  ),
59
50
  h('span', { id: 'spawn' }, JSON.stringify(modes.spawnSelectionRef.current)),
60
51
  h('span', { id: 'error' }, modes.error ?? ''),
52
+ h('span', { id: 'mode' }, modes.sessionMode?.currentValue ?? 'none'),
53
+ h('button', { id: 'set-code', onClick: () => modes.onSelectSessionMode?.('code') }, 'code'),
61
54
  modes.goalOpen && modes.goalRecord
62
55
  ? h(GoalBanner, {
63
56
  record: modes.goalRecord,
@@ -73,7 +66,7 @@ function Probe({ sessionId }: { sessionId: string }) {
73
66
  }
74
67
 
75
68
  /** Every request the hook issued, so a test can assert what was NOT sent. */
76
- const requests: Array<{ url: string; method: string }> = [];
69
+ const requests: Array<{ url: string; method: string; body?: string }> = [];
77
70
  /** When set, a POST to the agent route answers this instead of success. */
78
71
  let postFailure: { status: number; error: string } | null = null;
79
72
 
@@ -84,9 +77,9 @@ beforeAll(() => {
84
77
  if (!(key in nativeGlobals)) nativeGlobals[key] = target[key];
85
78
  target[key] = (win as unknown as Record<string, unknown>)[key];
86
79
  }
87
- target.fetch = async (input: unknown, init?: { method?: string }) => {
80
+ target.fetch = async (input: unknown, init?: { method?: string; body?: string }) => {
88
81
  const url = String(input);
89
- requests.push({ url, method: init?.method ?? 'GET' });
82
+ requests.push({ url, method: init?.method ?? 'GET', ...(init?.body ? { body: init.body } : {}) });
90
83
  if (init?.method === 'POST') {
91
84
  if (postFailure) {
92
85
  return new Response(JSON.stringify({ error: postFailure.error }), {
@@ -99,6 +92,22 @@ beforeAll(() => {
99
92
  headers: { 'content-type': 'application/json' },
100
93
  });
101
94
  }
95
+ if (url.includes(`/${WITH_MODE}/modes`)) {
96
+ return new Response(
97
+ JSON.stringify({
98
+ sessionId: WITH_MODE,
99
+ modes: {
100
+ plan: false,
101
+ goal: false,
102
+ mode: {
103
+ currentValue: 'ask',
104
+ values: [{ value: 'ask', name: 'Ask' }, { value: 'code', name: 'Code' }],
105
+ },
106
+ },
107
+ }),
108
+ { status: 200, headers: { 'content-type': 'application/json' } },
109
+ );
110
+ }
102
111
  if (url.includes(`/${WITH_GOAL}/modes`) || url.includes(`/${LIVE_GOAL}/modes`)) {
103
112
  const live = url.includes(`/${LIVE_GOAL}/modes`);
104
113
  return new Response(
@@ -237,6 +246,35 @@ describe('useChatTimelineModes hydration', () => {
237
246
  });
238
247
  });
239
248
 
249
+ describe('the agent mode selector', () => {
250
+ test('hydrates the agent list and moves it through set_mode', async () => {
251
+ const el = await mount(WITH_MODE);
252
+ expect(el.querySelector('#mode')?.textContent).toBe('ask');
253
+
254
+ await act(async () => {
255
+ (el.querySelector('#set-code') as HTMLButtonElement).click();
256
+ });
257
+ for (let i = 0; i < 10; i += 1) await act(async () => {});
258
+
259
+ expect(el.querySelector('#mode')?.textContent).toBe('code');
260
+ const post = requests.find((request) => request.method === 'POST' && request.url.includes(WITH_MODE));
261
+ expect(post?.body ? JSON.parse(post.body) : null).toMatchObject({ type: 'set_mode', mode: 'code' });
262
+ });
263
+
264
+ test('a refused mode change rolls back and names the reason', async () => {
265
+ postFailure = { status: 400, error: 'mode not supported' };
266
+ const el = await mount(WITH_MODE);
267
+ await act(async () => {
268
+ (el.querySelector('#set-code') as HTMLButtonElement).click();
269
+ });
270
+ for (let i = 0; i < 10; i += 1) await act(async () => {});
271
+
272
+ // Optimistic flip rolled back: the chip still names the mode the agent is in.
273
+ expect(el.querySelector('#mode')?.textContent).toBe('ask');
274
+ expect(el.querySelector('#error')?.textContent).toContain('mode not supported');
275
+ });
276
+ });
277
+
240
278
  describe('the Plan toggle', () => {
241
279
  test('a pending chat keeps the pick locally and never POSTs to a session that does not exist', async () => {
242
280
  const el = await mount(WITHOUT_FILE);
@@ -33,44 +33,20 @@ import {
33
33
  } from '@/shared/lib/omp/mode/types';
34
34
  import { goalMarkerPatch, useModeMarkers, type ModesResponse } from '@/client/hooks/chat/timeline/mode-markers';
35
35
  import { createGoalAction, type GoalActionResult } from '@/client/hooks/chat/timeline/goal-command';
36
- import { postModeCommand } from '@/client/hooks/chat/timeline/mode-post';
36
+ import { postModeCommand, postSessionMode } from '@/client/hooks/chat/timeline/mode-post';
37
+ import { subscribeClientSignal } from '@/client/lib/signals';
38
+ import type { SessionModeState } from '@/shared/lib/harness/session-modes';
37
39
  import { isGoalOpen } from '@/shared/lib/omp/mode/status';
38
40
  import { isPendingSessionId } from '@/shared/lib/omp/session/default-title';
39
41
  import { isModeMarker } from '@/shared/lib/omp/mode/constants';
40
42
  import type { ArmedGoal, GoalAction } from '@/shared/lib/omp/mode/actions';
43
+ import { modeAvailability, type ModeCapabilities } from '@/client/hooks/chat/timeline/mode-availability';
41
44
 
42
45
  import type { ChatTimelineModes } from '@/client/hooks/chat/timeline/modes-contract';
43
46
 
44
47
  export type { ChatTimelineModes };
45
48
  export type { ArmedGoal, GoalAction };
46
-
47
- /**
48
- * Which mode toggles a harness can actually honour.
49
- *
50
- * Pure, so the rule is testable without a render. Goal is available on every
51
- * harness: Kabmo owns the record and the loop for ACP (`acp-goal.server.ts`),
52
- * and omp carries the extension. Plan is different — it must be a real mode the
53
- * agent publishes (`claude` does, `opencode` does not), except on omp's own two
54
- * transports, which always expose the Plan toggle. An unknown harness keeps the
55
- * old surface: the row may simply not have arrived yet.
56
- */
57
- export function modeAvailability(capabilities: ModeCapabilities): { plan: boolean; goal: boolean } {
58
- // Goal is Kabmo-owned on every harness now: `acp-goal.server.ts` stores the
59
- // record and the driver opens the next turn after the audit, so an agent
60
- // without the `/kabmo-mode` extension can still run one.
61
- if (capabilities.harness === 'omp-rpc') return { plan: true, goal: true };
62
- if (!capabilities.harness) return { plan: true, goal: true };
63
- if (capabilities.harness === 'omp-acp') return { plan: true, goal: true };
64
- return { plan: capabilities.modeValues?.includes('plan') === true, goal: true };
65
- }
66
-
67
- export interface ModeCapabilities {
68
- /** The harness that owns this chat, when the tab knows it. */
69
- harness?: string | null;
70
- /** The harness's own `mode` values, from its probe: `plan` is a real mode on
71
- * the agents that publish one. */
72
- modeValues?: string[];
73
- }
49
+ export type { ModeCapabilities };
74
50
 
75
51
  export function useChatTimelineModes(
76
52
  sessionId: string | null,
@@ -88,6 +64,10 @@ export function useChatTimelineModes(
88
64
  const goalArmRef = useRef<ArmedGoal | null>(null);
89
65
  goalArmRef.current = goalArm;
90
66
  const [plan, setPlanState] = useState(false);
67
+ /** The agent's own mode selector (ACP), or null for omp and agents without one. */
68
+ const [sessionMode, setSessionMode] = useState<SessionModeState | null>(null);
69
+ const sessionModeRef = useRef<SessionModeState | null>(null);
70
+ sessionModeRef.current = sessionMode;
91
71
  const [goal, setGoalState] = useState(false);
92
72
  const [goalRecord, setGoalRecord] = useState<GoalRecord | null>(null);
93
73
  const [goalContinuation, setGoalContinuation] = useState<GoalContinuation | null>(null);
@@ -123,6 +103,7 @@ export function useChatTimelineModes(
123
103
  useEffect(() => {
124
104
  const current = sessionId;
125
105
  setPlanState(false);
106
+ setSessionMode(null);
126
107
  setGoalState(false);
127
108
  setGoalRecord(null);
128
109
  setGoalContinuation(null);
@@ -143,6 +124,7 @@ export function useChatTimelineModes(
143
124
  .then((data) => {
144
125
  if (cancelled || !data?.modes) return;
145
126
  setPlanState(data.modes.plan === true);
127
+ setSessionMode(data.modes.mode ?? null);
146
128
  setGoalState(data.modes.goal === true);
147
129
  setGoalRecord(data.modes.goalRecord ?? null);
148
130
  // The loop's last verdict rides the same record, so a reload shows
@@ -158,6 +140,18 @@ export function useChatTimelineModes(
158
140
  };
159
141
  }, [sessionId]);
160
142
 
143
+ // An agent can move its own mode/config (`mode_changed`/`config_changed`).
144
+ // The frame carries no full list, so re-read the authoritative selector.
145
+ useEffect(() => subscribeClientSignal('session-modes-changed', (payload) => {
146
+ if (!sessionId || payload.sessionId !== sessionId || isPendingSessionId(sessionId)) return;
147
+ fetch(`/api/sessions/${encodeURIComponent(sessionId)}/modes`)
148
+ .then((res) => (res.ok ? (res.json() as Promise<ModesResponse>) : null))
149
+ .then((data) => {
150
+ if (data?.modes) setSessionMode(data.modes.mode ?? null);
151
+ })
152
+ .catch(() => {});
153
+ }), [sessionId]);
154
+
161
155
  // Live transitions. omp's own `goal_updated` and the extension's markers both
162
156
  // arrive through this one channel, so the toggles follow the CHILD — including
163
157
  // a goal the model created itself during a guided interview, and one paused
@@ -239,6 +233,23 @@ export function useChatTimelineModes(
239
233
  [send],
240
234
  );
241
235
 
236
+ const onSelectSessionMode = useCallback(async (value: string) => {
237
+ const current = sessionModeRef.current;
238
+ const session = sessionRef.current;
239
+ if (!current || !session || current.currentValue === value || isPendingSessionId(session)) return;
240
+ setSessionMode({ ...current, currentValue: value });
241
+ setPlanState(value === 'plan');
242
+ setPending(true);
243
+ setError(null);
244
+ const result = await postSessionMode(session, value);
245
+ setPending(false);
246
+ if (!result.ok) {
247
+ setSessionMode(current);
248
+ setPlanState(current.currentValue === 'plan');
249
+ setError(result.error ?? 'Mode change failed');
250
+ }
251
+ }, []);
252
+
242
253
  const runGoalAction = useMemo(
243
254
  () => createGoalAction({
244
255
  send: (scope, action, payload) => send(scope, action, payload),
@@ -316,6 +327,8 @@ export function useChatTimelineModes(
316
327
  pending,
317
328
  planAvailable: available.plan && !goal,
318
329
  goalAvailable: available.goal,
330
+ sessionMode,
331
+ onSelectSessionMode,
319
332
  error,
320
333
  clearError,
321
334
  spawnSelectionRef,
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The pending chat's linked session: the parent it runs under, or the source it
8
+ * forks from.
9
+ *
10
+ * It lives in the pending store, not in component state, because the sidebar
11
+ * row and the send path both read it: the row nests under a parent from the
12
+ * first frame, and the first send decides between `/api/sessions/spawn`, a fork,
13
+ * and a top-level spawn. Choosing a linked session also moves the workspace to
14
+ * that session's folder.
15
+ *
16
+ * A URL twin (`?parentSessionId=` / `?forkFrom=` + `?forkAt=`) is folded back
17
+ * into the entry on mount: the store is in memory, and a reload recreates the
18
+ * row from the URL alone.
19
+ */
20
+
21
+ import { useCallback, useEffect } from 'preact/hooks';
22
+ import { patchPendingEntry, usePendingSessions } from '@/client/hooks/chat/omp/pending-sessions';
23
+ import { expandSessionBranch } from '@/client/hooks/workspace/expanded-sessions';
24
+ import { setHarnessPick } from '@/client/hooks/chat/timeline/session-harness';
25
+ import type { SessionHarness } from '@/client/hooks/chat/timeline/session-harness';
26
+ import type { SetSearchParams } from '@/client/lib/router/search-params';
27
+ import type { WorkspaceFolderData } from '@/shared/types';
28
+
29
+ export interface PendingBranchViewProps {
30
+ parentSessionId: string | null;
31
+ onParentSessionChange: (sessionId: string | null) => void;
32
+ branchLabel: string;
33
+ branchAllowNone: boolean;
34
+ }
35
+
36
+ export interface PendingBranchComposerProps {
37
+ harness?: string;
38
+ harnessEditable: boolean;
39
+ onSelectHarness?: (next: string) => void;
40
+ }
41
+
42
+ export interface PendingBranch {
43
+ /** The linked session id, under either meaning. */
44
+ parentSessionId: string | null;
45
+ /** The model the linked session runs on, so the composer starts on it. */
46
+ parentModel: { provider: string; modelId: string } | null;
47
+ viewProps: PendingBranchViewProps;
48
+ composerProps: PendingBranchComposerProps;
49
+ }
50
+
51
+ export function usePendingBranch(args: {
52
+ sessionId: string | null;
53
+ folders: WorkspaceFolderData[];
54
+ selectedFolderId: number | null;
55
+ setSelectedFolderId: (id: number | null) => void;
56
+ urlParentId: string | null;
57
+ urlForkFrom: string | null;
58
+ urlForkAt: string | null;
59
+ setSearchParams: SetSearchParams;
60
+ harnessPicker: SessionHarness['picker'];
61
+ pendingHarnessRef: { current: string | null };
62
+ }): PendingBranch {
63
+ const {
64
+ sessionId,
65
+ folders,
66
+ selectedFolderId,
67
+ setSelectedFolderId,
68
+ urlParentId,
69
+ urlForkFrom,
70
+ urlForkAt,
71
+ setSearchParams,
72
+ harnessPicker,
73
+ pendingHarnessRef,
74
+ } = args;
75
+ const entries = usePendingSessions();
76
+ const entry = entries.find((candidate) => candidate.id === sessionId);
77
+ const forkSourceId = entry?.forkSourceSessionId ?? urlForkFrom ?? null;
78
+ const isFork = Boolean(forkSourceId);
79
+ const parentSessionId = forkSourceId ?? entry?.parentSessionId ?? urlParentId ?? null;
80
+ const sessionOf = useCallback(
81
+ (id: string) => folders
82
+ .flatMap((folder) => folder.sessions ?? [])
83
+ .find((session) => String(session.id) === id),
84
+ [folders],
85
+ );
86
+ const linked = parentSessionId ? sessionOf(parentSessionId) : undefined;
87
+
88
+ // A reload recreates the row from the URL; fold its branch context into the
89
+ // store so the nesting and the SEND path read one value.
90
+ useEffect(() => {
91
+ if (!sessionId || !sessionId.startsWith('new-')) return;
92
+ if (urlForkFrom && !entry?.forkSourceSessionId) {
93
+ patchPendingEntry(sessionId, (current) => ({
94
+ ...current,
95
+ forkSourceSessionId: urlForkFrom,
96
+ ...(urlForkAt ? { forkAnchorEntryId: urlForkAt } : {}),
97
+ }));
98
+ return;
99
+ }
100
+ if (urlParentId && !entry?.parentSessionId) {
101
+ patchPendingEntry(sessionId, (current) => ({ ...current, parentSessionId: urlParentId }));
102
+ }
103
+ }, [sessionId, entry, urlParentId, urlForkFrom, urlForkAt]);
104
+
105
+ // The linked session decides the workspace and the agent before the operator
106
+ // touches either control: a child must run in its parent's folder, and a fork
107
+ // keeps the source's provider. This also covers a menu click whose row did
108
+ // not carry those fields.
109
+ useEffect(() => {
110
+ if (!sessionId || !sessionId.startsWith('new-') || !linked) return;
111
+ const folderId = Number(linked.folder_id);
112
+ if (Number.isFinite(folderId) && folderId !== selectedFolderId) setSelectedFolderId(folderId);
113
+ if (!entry?.harness && linked.harness) {
114
+ patchPendingEntry(sessionId, (current) => ({ ...current, harness: linked.harness! }));
115
+ setHarnessPick(sessionId, linked.harness);
116
+ }
117
+ }, [sessionId, linked, entry?.harness, selectedFolderId, setSelectedFolderId]);
118
+
119
+ const onParentSessionChange = useCallback(
120
+ (next: string | null) => {
121
+ if (!sessionId || !sessionId.startsWith('new-')) return;
122
+ // Re-picking the same source keeps the anchor; a different source has no
123
+ // such entry, so it branches at that source's tip.
124
+ if (isFork && next === parentSessionId) return;
125
+ const target = next ? sessionOf(next) : undefined;
126
+ patchPendingEntry(sessionId, (current) => ({
127
+ ...current,
128
+ ...(isFork
129
+ ? {
130
+ forkSourceSessionId: next ?? undefined,
131
+ forkAnchorEntryId: undefined,
132
+ }
133
+ : { parentSessionId: next ?? undefined }),
134
+ ...(target?.harness ? { harness: target.harness } : {}),
135
+ ...(target ? { folderId: target.folder_id } : {}),
136
+ }));
137
+ // The pick store is what the composer's tab strip reads; the entry's
138
+ // `harness` is what the sidebar row's mark reads.
139
+ if (next && target?.harness) setHarnessPick(sessionId, target.harness);
140
+ if (next) expandSessionBranch(next);
141
+ setSearchParams((prev) => {
142
+ const params = new URLSearchParams(prev);
143
+ if (isFork) {
144
+ if (next) {
145
+ params.set('forkFrom', next);
146
+ params.delete('forkAt');
147
+ } else {
148
+ params.delete('forkFrom');
149
+ params.delete('forkAt');
150
+ }
151
+ } else if (next) {
152
+ params.set('parentSessionId', next);
153
+ } else {
154
+ params.delete('parentSessionId');
155
+ }
156
+ return params;
157
+ }, { replace: true });
158
+ if (target) {
159
+ const id = Number(target.folder_id);
160
+ if (Number.isFinite(id)) setSelectedFolderId(id);
161
+ }
162
+ // A pick made for the previous linked session must not override the new
163
+ // one's own agent; the spawn inherits the session now chosen.
164
+ pendingHarnessRef.current = null;
165
+ },
166
+ [
167
+ sessionId,
168
+ isFork,
169
+ parentSessionId,
170
+ sessionOf,
171
+ setSearchParams,
172
+ setSelectedFolderId,
173
+ pendingHarnessRef,
174
+ ],
175
+ );
176
+
177
+ // The fork's provider OWNS the history being branched; switching it would
178
+ // ask an agent to fork a transcript it never wrote. A child may switch.
179
+ const composerProps: PendingBranchComposerProps = isFork
180
+ ? {
181
+ ...(harnessPicker.harness ? { harness: harnessPicker.harness } : {}),
182
+ harnessEditable: false,
183
+ }
184
+ : {
185
+ ...harnessPicker,
186
+ onSelectHarness: (next: string) => {
187
+ harnessPicker.onSelectHarness(next);
188
+ if (sessionId) {
189
+ patchPendingEntry(sessionId, (current) => ({ ...current, harness: next }));
190
+ }
191
+ },
192
+ };
193
+
194
+ return {
195
+ parentSessionId,
196
+ parentModel: linked?.runModel ?? null,
197
+ viewProps: {
198
+ parentSessionId,
199
+ onParentSessionChange,
200
+ branchLabel: isFork ? 'Fork from' : 'Parent',
201
+ branchAllowNone: !isFork,
202
+ },
203
+ composerProps,
204
+ };
205
+ }