moi-computer 0.10.1-next.6 → 0.11.1-dev.1c52199

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 (406) hide show
  1. package/README.md +2 -2
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/app-config.ts +2 -1
  4. package/client/app/AppRouter.tsx +2 -2
  5. package/client/app/routes/WorkspaceRoute.tsx +33 -27
  6. package/client/app/shell/SidebarLayout.tsx +18 -15
  7. package/client/components/shared/BottomPanel.tsx +26 -14
  8. package/client/components/shared/PanelHeader.tsx +1 -1
  9. package/client/components/shared/ReorderableList.tsx +7 -2
  10. package/client/components/shared/WorkspaceIcon.tsx +92 -0
  11. package/client/components/ui/alert-dialog.tsx +1 -0
  12. package/client/components/ui/button.tsx +1 -53
  13. package/client/components/ui/checkbox.tsx +1 -0
  14. package/client/components/ui/collapsible.tsx +1 -15
  15. package/client/components/ui/dialog.tsx +1 -58
  16. package/client/components/ui/dropdown-menu.tsx +1 -254
  17. package/client/components/ui/hover-card.tsx +1 -44
  18. package/client/components/ui/inline-input.tsx +84 -0
  19. package/client/components/ui/input.tsx +1 -21
  20. package/client/components/ui/popover.tsx +1 -88
  21. package/client/components/ui/resizable.tsx +1 -40
  22. package/client/components/ui/skeleton.tsx +1 -13
  23. package/client/components/ui/slider.tsx +1 -70
  24. package/client/components/ui/spinner.tsx +1 -18
  25. package/client/components/ui/switch.tsx +1 -23
  26. package/client/components/ui/tabs.tsx +1 -0
  27. package/client/components/ui/textarea.tsx +1 -18
  28. package/client/components/ui/toast.tsx +2 -2
  29. package/client/components/ui/tooltip.tsx +1 -51
  30. package/client/features/applets/AppletMount.tsx +5 -2
  31. package/client/features/applets/applet-cache.ts +3 -3
  32. package/client/features/applets/applet-runtime.ts +158 -108
  33. package/client/features/applets/applet-styles.ts +2 -2
  34. package/client/features/applets/applet-thumbnail.ts +6 -8
  35. package/client/features/applets/useApplet.ts +10 -9
  36. package/client/features/chat/ChatPanel.tsx +24 -15
  37. package/client/features/chat/ChatPopup.tsx +9 -5
  38. package/client/features/chat/applet-chat-intents.ts +179 -0
  39. package/client/features/chat/chat-send.ts +116 -64
  40. package/client/features/chat/chat-store.ts +51 -62
  41. package/client/features/chat/composer/ChatComposer.tsx +43 -128
  42. package/client/features/chat/composer/ModelPicker.tsx +47 -60
  43. package/client/features/chat/composer/attachments/AttachmentChip.tsx +99 -0
  44. package/client/features/chat/composer/attachments/DrawingAttachmentChip.tsx +37 -0
  45. package/client/features/chat/composer/attachments/FileAttachmentChip.tsx +22 -0
  46. package/client/features/chat/composer/attachments/TextAttachmentChip.tsx +11 -0
  47. package/client/features/chat/composer/attachments/draft-attachments.ts +168 -0
  48. package/client/features/chat/composer/attachments/types.ts +25 -0
  49. package/client/features/chat/composer/attachments/uploads.ts +26 -0
  50. package/client/features/chat/composer/banners/ErrorBanner.tsx +20 -12
  51. package/client/features/chat/composer/model-order.ts +15 -0
  52. package/client/features/chat/composer/useWorkspaceComposerState.tsx +15 -7
  53. package/client/features/chat/{chat-connection.ts → connection/chat-connection.ts} +1 -1
  54. package/client/features/chat/{chat-frames.ts → connection/chat-frames.ts} +10 -8
  55. package/client/features/chat/{ChatEmptyState.tsx → messages/ChatEmptyState.tsx} +16 -11
  56. package/client/features/chat/{MarkdownContent.tsx → messages/MarkdownContent.tsx} +16 -1
  57. package/client/features/chat/{TurnView.tsx → messages/TurnView.tsx} +27 -19
  58. package/client/features/chat/{group-turns.ts → messages/group-turns.ts} +12 -0
  59. package/client/features/chat/{interleave-notices.ts → messages/interleave-notices.ts} +7 -11
  60. package/client/features/chat/{tool-group → messages/tool-group}/SubagentCard.tsx +1 -1
  61. package/client/features/chat/{tool-group → messages/tool-group}/TimelineRow.tsx +2 -2
  62. package/client/features/chat/{tool-group → messages/tool-group}/ToolCallGroup.tsx +2 -5
  63. package/client/features/chat/{tool-group → messages/tool-group}/format/codex.ts +4 -1
  64. package/client/features/chat/{ChatSelector.tsx → sessions/ChatSelector.tsx} +3 -3
  65. package/client/features/chat/{api.ts → sessions/api.ts} +5 -14
  66. package/client/features/chat/sessions/session-view.ts +53 -0
  67. package/client/features/chat/{useSelectedSession.ts → sessions/useSelectedSession.ts} +64 -20
  68. package/client/features/chat/useChat.ts +46 -24
  69. package/client/features/collab/DevCollabIdentity.tsx +170 -0
  70. package/client/features/collab/DevCollabKit.tsx +501 -0
  71. package/client/features/collab/DevCollabPage.tsx +25 -0
  72. package/client/features/collab/WorkspaceCollabControls.tsx +313 -0
  73. package/client/features/collab/client.ts +146 -0
  74. package/client/features/collab/components.tsx +307 -0
  75. package/client/features/collab/dev-persona.ts +66 -0
  76. package/client/features/collab/engine.ts +96 -0
  77. package/client/features/collab/entry.tsx +35 -0
  78. package/client/features/collab/facehash-avatar.ts +132 -0
  79. package/client/features/collab/fake-engine.ts +130 -0
  80. package/client/features/collab/hooks.tsx +253 -0
  81. package/client/features/collab/identity.ts +305 -0
  82. package/client/features/collab/index.ts +45 -0
  83. package/client/features/collab/people.ts +102 -0
  84. package/client/features/collab/personal-state.ts +61 -0
  85. package/client/features/collab/presence-publisher.ts +29 -0
  86. package/client/features/collab/presence-target.ts +10 -0
  87. package/client/features/collab/primitives.tsx +398 -0
  88. package/client/features/collab/proxy-identity.ts +24 -0
  89. package/client/features/collab/store.ts +156 -0
  90. package/client/features/dev/ChatStatesPage.tsx +8 -7
  91. package/client/features/dev/DevIndexPage.tsx +10 -0
  92. package/client/features/dev/DevRoutes.tsx +16 -1
  93. package/client/features/dev/HarnessDebugPage.tsx +11 -8
  94. package/client/features/dev/ToolCallsPage.tsx +1 -1
  95. package/client/features/dev/UiComponentPreviews.tsx +855 -0
  96. package/client/features/dev/UiComponentsPage.tsx +60 -0
  97. package/client/features/dev/chat-states-fixtures.ts +13 -2
  98. package/client/features/drawings/capture-element.ts +13 -1
  99. package/client/features/drawings/useChatAnnotation.ts +17 -17
  100. package/client/features/drawings/useDrawingLayer.ts +7 -9
  101. package/client/features/drawings/useViewBuilderSketch.ts +18 -15
  102. package/client/features/home/HomePage.tsx +8 -7
  103. package/client/features/home/WorkspacePreview.tsx +2 -2
  104. package/client/features/home/workspace-presentation.tsx +1 -11
  105. package/client/features/home/workspace-setup/DemoDialog.tsx +3 -2
  106. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +5 -8
  107. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +2 -4
  108. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +7 -20
  109. package/client/features/overview/HiddenPanel.tsx +109 -0
  110. package/client/features/overview/Overview.tsx +302 -0
  111. package/client/features/overview/WidgetCanvas.tsx +164 -0
  112. package/client/features/{widgets → overview}/WidgetFrame.tsx +25 -17
  113. package/client/features/overview/WorkspaceName.tsx +60 -0
  114. package/client/features/overview/api.ts +30 -0
  115. package/client/features/overview/default/ViewsWidget.tsx +252 -0
  116. package/client/features/overview/default/registry.tsx +36 -0
  117. package/client/features/{widgets → overview}/grid.ts +36 -0
  118. package/client/features/overview/useGridReconcile.ts +94 -0
  119. package/client/features/scratchpad/Scratchpad.tsx +7 -8
  120. package/client/features/scratchpad/ScratchpadControls.tsx +0 -1
  121. package/client/features/scratchpad/useScratchpadSnapshot.tsx +23 -13
  122. package/client/features/settings/GeneralSettings.tsx +55 -58
  123. package/client/features/settings/SettingsLayout.tsx +2 -2
  124. package/client/features/settings/WorkspaceIconPicker.tsx +318 -0
  125. package/client/features/settings/WorkspaceSettingsDialog.tsx +65 -0
  126. package/client/features/settings/api.ts +48 -24
  127. package/client/features/views/ViewBuilder.tsx +5 -4
  128. package/client/features/views/ViewManager.tsx +28 -22
  129. package/client/features/views/api.ts +36 -2
  130. package/client/features/views/useViewBuilderActions.ts +11 -5
  131. package/client/features/views/useViewBuilderDrafts.ts +23 -21
  132. package/client/features/views/view-presentation.ts +13 -0
  133. package/client/features/workspace/{CustomizePanel.tsx → ThemePanel.tsx} +26 -31
  134. package/client/features/workspace/UnavailablePage.tsx +21 -0
  135. package/client/features/workspace/WorkspaceLayoutContext.tsx +22 -10
  136. package/client/features/workspace/WorkspaceScreen.tsx +228 -172
  137. package/client/features/workspace/WorkspaceSplitLayout.tsx +7 -2
  138. package/client/features/workspace/WorkspaceTabs.tsx +2 -0
  139. package/client/features/workspace/api.ts +5 -31
  140. package/client/features/workspace/layout-save.ts +13 -0
  141. package/client/features/workspace/moi-context.ts +15 -11
  142. package/client/features/workspace/tab-resolution.ts +10 -33
  143. package/client/features/workspace/useWorkspaceNavigation.ts +173 -101
  144. package/client/index.css +23 -30
  145. package/client/index.tsx +4 -3
  146. package/client/lib/app-icon-registry.ts +2 -0
  147. package/client/lib/use-latest-ref.ts +11 -0
  148. package/client/main.tsx +1 -1
  149. package/client/runtime/useWorkspaceEvents.ts +59 -14
  150. package/client/theme.css +5 -5
  151. package/dist/chunk-1ftessc8.js +2 -0
  152. package/dist/chunk-3802vh2p.js +2 -0
  153. package/dist/chunk-542a2m9m.js +1 -0
  154. package/dist/chunk-5745d83v.js +2 -0
  155. package/dist/chunk-5zxdsjym.js +1 -0
  156. package/dist/{chunk-tqd3pkg8.css → chunk-60q353jq.css} +1 -1
  157. package/dist/chunk-7r4z77ry.js +2 -0
  158. package/dist/chunk-9cm0wjah.js +79 -0
  159. package/dist/{chunk-11cab5dq.css → chunk-cq2r11fg.css} +1 -1
  160. package/dist/chunk-cvgdm1hq.js +2 -0
  161. package/dist/chunk-gptm4jpd.js +546 -0
  162. package/dist/chunk-nf2wkvf9.js +14 -0
  163. package/dist/chunk-wnmf38ta.js +5 -0
  164. package/dist/chunk-xaehhr1j.css +1 -0
  165. package/dist/chunk-xpt063fx.js +1 -0
  166. package/dist/index.html +1 -1
  167. package/lib/app-icons.ts +1 -0
  168. package/lib/applet-selector.ts +24 -0
  169. package/lib/chat-title.ts +6 -1
  170. package/lib/collab/colors.ts +24 -0
  171. package/lib/collab/protocol.ts +83 -0
  172. package/lib/collab/types.ts +63 -0
  173. package/lib/default-widgets.ts +32 -0
  174. package/lib/experimental.ts +14 -0
  175. package/lib/format.ts +67 -7
  176. package/lib/message-attachments.ts +40 -0
  177. package/lib/moi-attachments.ts +204 -0
  178. package/lib/moi-context.ts +27 -35
  179. package/lib/navigation.ts +84 -0
  180. package/lib/themes.ts +6 -6
  181. package/lib/types.ts +103 -40
  182. package/lib/workspace-icon.ts +20 -0
  183. package/lib/workspace-layout.ts +22 -2
  184. package/lib/workspace-tabs.ts +9 -33
  185. package/package.json +44 -32
  186. package/registry.json +656 -0
  187. package/server/AGENTS.md +2 -0
  188. package/server/agent.ts +1 -1
  189. package/server/api.ts +162 -68
  190. package/server/app-config.ts +127 -34
  191. package/server/applet-typecheck.ts +100 -0
  192. package/server/applets/applet-css.ts +55 -0
  193. package/server/{bundler → applets}/build-applet.ts +21 -240
  194. package/server/applets/build-worker.ts +178 -0
  195. package/server/applets/config.ts +226 -0
  196. package/server/applets/dependencies.ts +206 -0
  197. package/server/{applets.ts → applets/index.ts} +44 -189
  198. package/server/applets/runtime/base.ts +4 -0
  199. package/server/applets/runtime/moi.ts +42 -0
  200. package/server/applets/runtime/rpc.ts +17 -0
  201. package/server/applets/view-source.ts +67 -0
  202. package/server/attachment-message.ts +95 -0
  203. package/server/chat-selection.ts +23 -0
  204. package/server/cli-ui-components.ts +28 -33
  205. package/server/cli.ts +226 -120
  206. package/server/collab/applet-module.ts +50 -0
  207. package/server/collab/cloudflare-access.ts +77 -0
  208. package/server/collab/config.ts +18 -0
  209. package/server/collab/ipc.ts +10 -0
  210. package/server/collab/manager.ts +407 -0
  211. package/server/collab/service.ts +137 -0
  212. package/server/collab/skill/collab-env.d.ts +92 -0
  213. package/server/collab/skill/index.ts +59 -0
  214. package/server/collab/worker.ts +52 -0
  215. package/server/control.ts +63 -42
  216. package/server/data-dir.ts +1 -1
  217. package/server/harness/README.md +45 -50
  218. package/server/harness/acp/NOTES.md +426 -0
  219. package/server/harness/acp/adapter.ts +7 -21
  220. package/server/harness/acp/discovery.ts +27 -30
  221. package/server/harness/acp/model-state.ts +57 -0
  222. package/server/harness/acp/session.ts +49 -56
  223. package/server/harness/claude-code/NOTES.md +54 -13
  224. package/server/harness/claude-code/adapter.ts +8 -25
  225. package/server/harness/claude-code/cli.ts +40 -0
  226. package/server/harness/claude-code/index.ts +13 -5
  227. package/server/harness/claude-code/models.ts +72 -19
  228. package/server/harness/claude-code/session.ts +447 -343
  229. package/server/harness/claude-code/sessions.ts +9 -4
  230. package/server/harness/codex/NOTES.md +222 -350
  231. package/server/harness/codex/adapter.ts +102 -52
  232. package/server/harness/codex/auth.ts +1 -3
  233. package/server/harness/codex/client.ts +169 -249
  234. package/server/harness/codex/discovery.ts +9 -17
  235. package/server/harness/codex/index.ts +3 -1
  236. package/server/harness/codex/pagination.ts +24 -0
  237. package/server/harness/codex/permissions.ts +32 -8
  238. package/server/harness/codex/probe.ts +10 -13
  239. package/server/harness/codex/session.ts +567 -181
  240. package/server/harness/codex/transport.ts +184 -0
  241. package/server/harness/debug.ts +1 -1
  242. package/server/harness/hermes/NOTES.md +19 -1
  243. package/server/harness/hermes/discovery.ts +20 -0
  244. package/server/harness/hermes/index.ts +13 -0
  245. package/server/harness/hermes/models.ts +28 -8
  246. package/server/harness/openclaw/NOTES.md +1 -1
  247. package/server/harness/openclaw/adapter.ts +22 -4
  248. package/server/harness/openclaw/gateway.ts +5 -3
  249. package/server/harness/openclaw/session.ts +27 -27
  250. package/server/harness/types.ts +9 -5
  251. package/server/layout.ts +24 -16
  252. package/server/moi-scaffold.ts +22 -14
  253. package/server/navigation-relay.ts +110 -0
  254. package/server/preview.ts +3 -1
  255. package/server/registry.ts +71 -41
  256. package/server/scratchpad-executor.ts +79 -56
  257. package/server/scratchpad-shape-defaults.ts +82 -0
  258. package/server/selected-session.ts +24 -4
  259. package/server/skill-update.ts +5 -3
  260. package/server/skill-version.ts +4 -7
  261. package/server/skills-template.ts +60 -9
  262. package/server/tabs.ts +19 -33
  263. package/server/tldraw-package.d.ts +4 -0
  264. package/server/ui-components.ts +101 -434
  265. package/server/uploads.ts +0 -0
  266. package/server/view-builders.ts +20 -2
  267. package/server/views.ts +126 -6
  268. package/server/web.ts +108 -30
  269. package/server/widgets.ts +12 -5
  270. package/server/workspace-config.ts +13 -9
  271. package/server/workspace-env.ts +3 -2
  272. package/tsconfig.json +0 -1
  273. package/ui-components/accordion.tsx +71 -0
  274. package/ui-components/alert-dialog.tsx +165 -0
  275. package/ui-components/alert.tsx +68 -0
  276. package/ui-components/attachment.tsx +195 -0
  277. package/ui-components/avatar.tsx +91 -0
  278. package/ui-components/badge.tsx +49 -0
  279. package/ui-components/button-group.tsx +78 -0
  280. package/ui-components/button.tsx +55 -0
  281. package/ui-components/calendar.tsx +180 -0
  282. package/ui-components/card.tsx +84 -0
  283. package/ui-components/carousel.tsx +235 -0
  284. package/ui-components/chart.tsx +338 -0
  285. package/ui-components/checkbox.tsx +28 -0
  286. package/ui-components/collapsible.tsx +15 -0
  287. package/ui-components/combobox.tsx +267 -0
  288. package/ui-components/context-menu.tsx +244 -0
  289. package/ui-components/dialog.tsx +138 -0
  290. package/ui-components/docs/accordion.md +463 -0
  291. package/ui-components/docs/alert-dialog.md +481 -0
  292. package/ui-components/docs/alert.md +301 -0
  293. package/ui-components/docs/attachment.md +689 -0
  294. package/ui-components/docs/avatar.md +495 -0
  295. package/ui-components/docs/badge.md +258 -0
  296. package/ui-components/docs/button-group.md +879 -0
  297. package/ui-components/docs/button.md +26 -0
  298. package/ui-components/docs/calendar.md +862 -0
  299. package/ui-components/docs/card.md +265 -0
  300. package/ui-components/docs/carousel.md +627 -0
  301. package/ui-components/docs/chart.md +1256 -0
  302. package/ui-components/docs/checkbox.md +477 -0
  303. package/ui-components/docs/collapsible.md +446 -0
  304. package/ui-components/docs/combobox.md +1003 -0
  305. package/ui-components/docs/context-menu.md +860 -0
  306. package/ui-components/docs/data-table.md +1580 -0
  307. package/ui-components/docs/date-picker.md +614 -0
  308. package/ui-components/docs/dialog.md +414 -0
  309. package/ui-components/docs/drawer.md +51 -0
  310. package/ui-components/docs/dropdown-menu.md +1000 -0
  311. package/ui-components/docs/field.md +1192 -0
  312. package/ui-components/docs/hover-card.md +275 -0
  313. package/ui-components/docs/input-group.md +866 -0
  314. package/ui-components/docs/input.md +456 -0
  315. package/ui-components/docs/kbd.md +191 -0
  316. package/ui-components/docs/label.md +295 -0
  317. package/ui-components/docs/pagination.md +416 -0
  318. package/ui-components/docs/popover.md +348 -0
  319. package/ui-components/docs/progress.md +214 -0
  320. package/ui-components/docs/radio-group.md +389 -0
  321. package/ui-components/docs/resizable.md +265 -0
  322. package/ui-components/docs/select.md +616 -0
  323. package/ui-components/docs/separator.md +216 -0
  324. package/ui-components/docs/skeleton.md +205 -0
  325. package/ui-components/docs/slider.md +226 -0
  326. package/ui-components/docs/spinner.md +332 -0
  327. package/ui-components/docs/switch.md +236 -0
  328. package/ui-components/docs/table.md +551 -0
  329. package/ui-components/docs/tabs.md +379 -0
  330. package/ui-components/docs/textarea.md +187 -0
  331. package/ui-components/docs/toggle-group.md +370 -0
  332. package/ui-components/docs/toggle.md +91 -0
  333. package/ui-components/docs/tooltip.md +290 -0
  334. package/ui-components/drawer.tsx +213 -0
  335. package/ui-components/dropdown-menu.tsx +263 -0
  336. package/ui-components/field.tsx +224 -0
  337. package/ui-components/hover-card.tsx +46 -0
  338. package/ui-components/input-group.tsx +146 -0
  339. package/ui-components/input.tsx +20 -0
  340. package/ui-components/kbd.tsx +32 -0
  341. package/ui-components/label.tsx +17 -0
  342. package/ui-components/pagination.tsx +124 -0
  343. package/ui-components/popover.tsx +81 -0
  344. package/ui-components/progress.tsx +63 -0
  345. package/ui-components/radio-group.tsx +38 -0
  346. package/ui-components/resizable.tsx +40 -0
  347. package/ui-components/scoped-portal.tsx +31 -0
  348. package/ui-components/select.tsx +195 -0
  349. package/ui-components/separator.tsx +18 -0
  350. package/ui-components/skeleton.tsx +15 -0
  351. package/ui-components/slider.tsx +75 -0
  352. package/ui-components/spinner.tsx +20 -0
  353. package/ui-components/switch.tsx +27 -0
  354. package/ui-components/table.tsx +86 -0
  355. package/ui-components/tabs.tsx +75 -0
  356. package/ui-components/textarea.tsx +17 -0
  357. package/ui-components/toggle-group.tsx +85 -0
  358. package/ui-components/toggle.tsx +42 -0
  359. package/ui-components/tooltip.tsx +61 -0
  360. package/ui-components/utils.ts +8 -0
  361. package/workspace/.claude/skills/moi-workspace/SKILL.md +295 -248
  362. package/workspace/.claude/skills/moi-workspace/references/COLLABORATIVE.md +151 -0
  363. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +100 -152
  364. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +156 -0
  365. package/workspace/.claude/skills/moi-workspace/references/UI-COMPONENTS.md +67 -203
  366. package/client/features/chat/attachment-staging.ts +0 -153
  367. package/client/features/chat/uploads.ts +0 -18
  368. package/client/features/chat/useAppletChatMessage.ts +0 -68
  369. package/client/features/settings/IconPicker.tsx +0 -442
  370. package/client/features/settings/WorkspaceSettings.tsx +0 -92
  371. package/client/features/settings/render-icon.ts +0 -173
  372. package/client/features/widgets/HiddenPanel.tsx +0 -80
  373. package/client/features/widgets/WidgetGrid.tsx +0 -123
  374. package/client/features/widgets/Widgets.tsx +0 -260
  375. package/client/features/widgets/useGridReconcile.ts +0 -73
  376. package/dist/chunk-104m57qw.js +0 -2
  377. package/dist/chunk-7paadv61.js +0 -1
  378. package/dist/chunk-bj3akjs2.js +0 -1
  379. package/dist/chunk-c9pjqx9m.js +0 -14
  380. package/dist/chunk-j2w2vak4.js +0 -546
  381. package/dist/chunk-k2r9c95m.js +0 -10
  382. package/dist/chunk-kmbxhgwv.js +0 -1
  383. package/dist/chunk-pcnahct1.js +0 -5
  384. package/dist/chunk-r8s1b672.css +0 -1
  385. package/dist/chunk-tny85yt2.js +0 -2
  386. package/dist/chunk-v7wr1df4.js +0 -2
  387. package/dist/chunk-vwzshv0d.js +0 -83
  388. package/server/bundler/applet-css.ts +0 -155
  389. /package/client/features/chat/{ChatPromptBubbles.tsx → messages/ChatPromptBubbles.tsx} +0 -0
  390. /package/client/features/chat/{ShimmerText.tsx → messages/ShimmerText.tsx} +0 -0
  391. /package/client/features/chat/{preview-turn.ts → messages/preview-turn.ts} +0 -0
  392. /package/client/features/chat/{tool-group → messages/tool-group}/CodeBlock.tsx +0 -0
  393. /package/client/features/chat/{tool-group → messages/tool-group}/Collapse.tsx +0 -0
  394. /package/client/features/chat/{tool-group → messages/tool-group}/ReadImagePreview.tsx +0 -0
  395. /package/client/features/chat/{tool-group → messages/tool-group}/ToolOutput.tsx +0 -0
  396. /package/client/features/chat/{tool-group → messages/tool-group}/detect.ts +0 -0
  397. /package/client/features/chat/{tool-group → messages/tool-group}/fixtures.ts +0 -0
  398. /package/client/features/chat/{tool-group → messages/tool-group}/format/claude.ts +0 -0
  399. /package/client/features/chat/{tool-group → messages/tool-group}/format/hermes.ts +0 -0
  400. /package/client/features/chat/{tool-group → messages/tool-group}/format/index.ts +0 -0
  401. /package/client/features/chat/{tool-group → messages/tool-group}/format/mcp.ts +0 -0
  402. /package/client/features/chat/{tool-group → messages/tool-group}/format/openclaw.ts +0 -0
  403. /package/client/features/chat/{tool-group → messages/tool-group}/format/shared.ts +0 -0
  404. /package/client/features/chat/{tool-group → messages/tool-group}/format/shell.ts +0 -0
  405. /package/client/features/chat/{tool-group → messages/tool-group}/index.ts +0 -0
  406. /package/client/features/chat/{useStickToBottom.ts → messages/useStickToBottom.ts} +0 -0
@@ -1,16 +1,13 @@
1
- // Live Claude Code sessions held open in the server process.
1
+ // One long-lived SDK query per session, with follow-ups queued in moi.
2
2
  //
3
- // Each (workspaceId, sessionId) gets ONE long-lived `query()` running in
4
- // streaming-input mode: a single agent session that consumes user messages from
5
- // an in-memory queue and streams output to all connected clients. Follow-up
6
- // messages (and messages from multiple browser tabs) are pushed into the same
7
- // queue — so they're *queued* instead of rejected, and there's no cold `resume`
8
- // between turns.
3
+ // Dispatch waits for the preceding user turn to finish before applying the next
4
+ // message's settings. Pending messages survive subprocess replacement; running
5
+ // background tasks retain their process until they finish.
9
6
  //
10
- // Disk stays the source of truth: the SDK persists each block to the session
11
- // `.jsonl` incrementally, so a (re)connecting client reads /events then folds
12
- // live deltas. If a session is idle-evicted (or lost on a server restart), the
13
- // next message recreates it with `resume` — transparently.
7
+ // The SDK persists history to disk. After eviction or a server restart, the
8
+ // next message resumes that history in a new process.
9
+ import { prepareAttachmentMessage, type PreparedAttachmentMessage } from '../../attachment-message'
10
+ import { attachmentLabel } from '@/lib/moi-attachments'
14
11
  import {
15
12
  type Options,
16
13
  type Query,
@@ -18,7 +15,6 @@ import {
18
15
  query
19
16
  } from '@anthropic-ai/claude-agent-sdk'
20
17
 
21
- import { appendAttachmentNote, attachmentOnlyPlaceholder } from '@/lib/attachment-note'
22
18
  import { buildSessionTitleSource } from '../session-title'
23
19
  import { ClaudeAdapter } from './adapter'
24
20
  import { CLAUDE_APPROVAL_HOOKS } from './permissions'
@@ -26,14 +22,13 @@ import { claudeSessionExists } from './sessions'
26
22
  import { generateClaudeSessionTitle, renameClaudeSessionIfUnchanged } from './session-title'
27
23
  import type { Part } from '@/lib/format'
28
24
  import type { SessionActivity } from '@/lib/types'
29
- import { type MoiContext, moiContextSystemReminder, renderMoiContext } from '@/lib/moi-context'
25
+ import { moiContextSystemReminder, renderMoiContext } from '@/lib/moi-context'
30
26
 
31
27
  import { debug } from '../../debug'
32
28
  import { tapWire } from '../debug'
33
29
  import { broadcast } from '../../state'
34
30
  import { renameSelectedSession } from '../../selected-session'
35
31
  import { hasSessionConfig, renameSessionConfig, saveSessionConfig } from '../../session-config'
36
- import { type StoredUpload, resolveUploads, uploadToDisplayPart } from '../../uploads'
37
32
  import {
38
33
  markViewBuilderBuildingBySession,
39
34
  markViewBuilderWaitingBySession,
@@ -41,77 +36,80 @@ import {
41
36
  } from '../../view-builders'
42
37
  import { resolveWorkspaceEnv } from '../../workspace-env'
43
38
  import { requireHarnessExecutable } from '../executable'
39
+ import type { SendMessageInput } from '../types'
44
40
 
45
41
  // Media types Claude vision accepts; uploads.ts guarantees every image upload is
46
42
  // normalized to one of these, so the cast on `media_type` below is sound.
47
43
  type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'
48
44
 
49
- // What the SDK's streaming-input prompt accepts for one message's content:
50
- // a plain string or an array of Anthropic content blocks (text/image/…).
51
45
  type MessageContent = SDKUserMessage['message']['content']
52
46
 
53
- // Turn a typed text + resolved uploads into (a) the content the agent receives
54
- // and (b) the display parts we broadcast for the user's bubble. Images become
55
- // base64 vision blocks; other files are referenced by their temp path so the
56
- // agent can Read them. Display text stays the user's text (no path note).
57
- // Exported for unit tests.
58
- export function buildUserMessage(
59
- text: string,
60
- uploads: StoredUpload[],
61
- displayText = text
62
- ): { content: MessageContent; parts: Part[] } {
63
- const parts: Part[] = []
64
- for (const u of uploads) {
65
- const part = uploadToDisplayPart(u)
66
- if (part) parts.push(part)
67
- }
68
- if (displayText) parts.push({ type: 'text', text: displayText })
69
-
70
- if (uploads.length === 0) return { content: text, parts }
71
-
72
- const blocks: Exclude<MessageContent, string> = []
73
- for (const u of uploads) {
74
- if (u.kind === 'image' && u.data) {
75
- blocks.push({
76
- type: 'image',
77
- source: {
78
- type: 'base64',
79
- media_type: u.mediaType as ImageMediaType,
80
- data: u.data.toString('base64')
81
- }
82
- })
83
- }
84
- }
85
-
86
- const files = uploads.filter(u => u.kind === 'file' && u.path)
87
- const agentText = appendAttachmentNote(
88
- text || attachmentOnlyPlaceholder(uploads.map(upload => upload.filename)),
89
- files.map(f => ({ filename: f.filename, path: f.path! }))
47
+ // Only the native SDK block shape belongs to this harness.
48
+ export function buildUserMessage(message: PreparedAttachmentMessage): {
49
+ content: MessageContent
50
+ parts: Part[]
51
+ } {
52
+ const images = message.attachments.filter(
53
+ attachment => attachment.type === 'image' && 'data' in attachment
90
54
  )
91
- // Always end with a text block so an image-only message still has a prompt.
92
- blocks.push({ type: 'text', text: agentText })
93
- return { content: blocks, parts }
55
+ if (!images.length) return { content: message.text, parts: message.parts }
56
+ const blocks: Exclude<MessageContent, string> = images.map(image => ({
57
+ type: 'image',
58
+ source: {
59
+ type: 'base64',
60
+ media_type: image.mediaType as ImageMediaType,
61
+ data: image.data.toString('base64')
62
+ }
63
+ }))
64
+ blocks.push({ type: 'text', text: message.text })
65
+ return { content: blocks, parts: message.parts }
94
66
  }
95
67
 
96
- // Cap on concurrently-held live sessions (each = one claude subprocess). When
97
- // exceeded, the least-recently-active IDLE session is closed; a busy session is
98
- // never evicted. Idle sessions are also closed after this TTL.
68
+ // Each live session owns a subprocess. Only idle sessions can be evicted.
99
69
  const MAX_LIVE_SESSIONS = 8
100
70
  const IDLE_TTL_MS = 5 * 60_000
101
71
 
102
- // SDK task types that keep running after the turn ends (background Bash,
103
- // workflow runs). Subagent Tasks complete within their turn, so they are
104
- // deliberately excluded — a leaked entry would keep the session alive forever.
105
- const BG_TASK_TYPES = new Set(['local_bash', 'local_workflow'])
72
+ // Older CLIs lack background-task snapshots. These task types outlive the turn;
73
+ // other types count only when their event explicitly marks them backgrounded.
74
+ const LEGACY_BG_TASK_TYPES = new Set(['local_bash', 'local_workflow'])
106
75
 
107
76
  type InputQueue = {
108
77
  iterator: AsyncGenerator<SDKUserMessage>
109
- push: (content: MessageContent) => void
78
+ push: (content: MessageContent, uuid: NonNullable<SDKUserMessage['uuid']>) => void
110
79
  clear: () => void
111
80
  close: () => void
112
81
  }
113
82
 
83
+ type PendingMessage = {
84
+ input: SendMessageInput
85
+ content: MessageContent
86
+ titleSource: string
87
+ turnId: string
88
+ wireId: NonNullable<SDKUserMessage['uuid']>
89
+ label: string
90
+ resolve: () => void
91
+ reject: (error: Error) => void
92
+ completed: Promise<void>
93
+ complete: () => void
94
+ }
95
+
96
+ // This queue outlives its subprocess. Register it before any async setup so
97
+ // concurrent first sends share one session, including across temp-id renames.
98
+ type SessionMessages = {
99
+ workspaceId: string
100
+ workspacePath: string
101
+ sessionId: string
102
+ isNew: boolean
103
+ pending: PendingMessage[]
104
+ active: PendingMessage | null
105
+ dispatching: boolean
106
+ stopping: boolean
107
+ publishedActivity: SessionActivity
108
+ live?: LiveSession
109
+ }
110
+
114
111
  type LiveSession = {
112
+ messages: SessionMessages
115
113
  workspaceId: string
116
114
  workspacePath: string
117
115
  workspaceEnv: Record<string, string>
@@ -120,41 +118,28 @@ type LiveSession = {
120
118
  adapter: ClaudeAdapter
121
119
  input: InputQueue
122
120
  abort: AbortController
123
- // Session activity, mirrored from the SDK's `session_state_changed` events
124
- // (authoritative — it fires `idle` only after the CLI's input queue drains,
125
- // so queued messages merged into one model turn can't wedge it, unlike the
126
- // old send/result counter). `sendCCMessage` flips it to 'running'
127
- // optimistically so the loader doesn't wait a subprocess round-trip.
121
+ // SDK activity, set optimistically to running when a prompt is dispatched.
128
122
  activity: SessionActivity
129
- // Whether this query has emitted `session_state_changed` at all. When it
130
- // never does (older CLI), the `result` handler falls back to declaring idle.
123
+ // Without state events, the matching result is the turn-completion signal.
131
124
  sawStateEvents: boolean
132
- // Live background tasks (background Bash, workflows) keyed by task id, fed by
133
- // the SDK's typed task events. Non-empty keeps the session alive past the
134
- // idle TTL — tearing down the subprocess would kill its background children.
125
+ turnEnded: boolean
126
+ // The SDK's full set of background tasks, including subagents and ambient
127
+ // watchers. All retain their process; none alone makes the chat busy.
135
128
  bgTasks: Set<string>
129
+ // Once this process emits a snapshot, task edges must never mutate its set:
130
+ // the SDK does not guarantee their ordering relative to snapshots.
131
+ sawBackgroundSnapshot: boolean
136
132
  model: string | undefined
137
- // Fast mode is a live flag setting. Undefined clears moi's override and
138
- // inherits the provider configuration.
133
+ // Live flag settings; undefined inherits provider defaults.
139
134
  fastMode: boolean | undefined
140
- // Reasoning effort the query was created with. The SDK has no live setter for
141
- // it (unlike setModel), so a change tears the session down and resumes.
142
135
  effort: string | undefined
143
- // Effort the latest message asked for. When it diverges from `effort` while a
144
- // turn is in flight (can't rebuild mid-turn), the session is torn down once it
145
- // drains so the next message resumes with the requested effort.
146
- desiredEffort: string | undefined
147
- // Whether this query was built with `includePartialMessages` (live token
148
- // streaming). Like effort, it's a construct-time option with no live setter,
149
- // so a change tears the session down and resumes.
136
+ // `includePartialMessages` is fixed at creation, so changes require resume.
150
137
  stream: boolean
151
- // Streaming mode the latest message asked for; drives the same drain-then-
152
- // rebuild path as `desiredEffort` when it diverges mid-turn.
153
- desiredStream: boolean
138
+ // Rebuild before the next send, once this turn and background tasks finish.
139
+ staleCli: boolean
154
140
  idleTimer: ReturnType<typeof setTimeout> | null
155
141
  closed: boolean
156
- // Last turn's error text (result subtype), consumed by the view-builder
157
- // status update on the idle transition.
142
+ // Passed to the view builder when the session becomes idle.
158
143
  lastBuilderError: string | undefined
159
144
  // Introspection only (surfaced by /status) — not load-bearing.
160
145
  createdAt: number
@@ -166,11 +151,9 @@ type LiveSession = {
166
151
  }
167
152
 
168
153
  const sessions = new Map<string, LiveSession>()
169
- // `${workspaceId}:${tempId}` -> real session id. A new thread is created under
170
- // the client's temporary id, then renamed to the SDK's real id on init. A
171
- // follow-up queued in the window before the client learns the new id still
172
- // carries the temp id; this alias re-routes it to the live session instead of
173
- // spawning a duplicate. Temp ids are UUIDs, so stale entries never collide.
154
+ const messageQueues = new Map<string, SessionMessages>()
155
+ // `${workspaceId}:${tempId}` -> real session id. Follow-ups may still use the
156
+ // client's temporary id after the SDK has assigned the real one.
174
157
  const aliases = new Map<string, string>()
175
158
 
176
159
  function recKey(workspaceId: string, sessionId: string): string {
@@ -193,9 +176,10 @@ export function getCCActiveSessions(): {
193
176
  activity: SessionActivity
194
177
  }[] {
195
178
  const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
196
- for (const s of sessions.values()) {
197
- if (s.activity !== 'idle') {
198
- out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId, activity: s.activity })
179
+ for (const messages of messageQueues.values()) {
180
+ const activity = messageActivity(messages)
181
+ if (activity !== 'idle') {
182
+ out.push({ workspaceId: messages.workspaceId, sessionId: messages.sessionId, activity })
199
183
  }
200
184
  }
201
185
  return out
@@ -210,9 +194,9 @@ export type CCDebugSession = {
210
194
  model: string | undefined
211
195
  fastMode: boolean | undefined
212
196
  effort: string | undefined
213
- desiredEffort: string | undefined
214
197
  stream: boolean
215
- desiredStream: boolean
198
+ queuedMessages: number
199
+ staleCli: boolean
216
200
  activity: SessionActivity
217
201
  bgTasks: number
218
202
  closed: boolean
@@ -222,8 +206,7 @@ export type CCDebugSession = {
222
206
  lastUserText: string | undefined
223
207
  }
224
208
 
225
- // A full snapshot of the in-memory live-session registry, for the /status page.
226
- // Read-only — never mutate the returned objects.
209
+ // Session diagnostics for /status.
227
210
  export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: number } {
228
211
  return {
229
212
  sessions: [...sessions.values()].map(s => ({
@@ -232,9 +215,9 @@ export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: num
232
215
  model: s.model,
233
216
  fastMode: s.fastMode,
234
217
  effort: s.effort,
235
- desiredEffort: s.desiredEffort,
236
218
  stream: s.stream,
237
- desiredStream: s.desiredStream,
219
+ queuedMessages: s.messages.pending.length,
220
+ staleCli: s.staleCli,
238
221
  activity: s.activity,
239
222
  bgTasks: s.bgTasks.size,
240
223
  closed: s.closed,
@@ -247,9 +230,7 @@ export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: num
247
230
  }
248
231
  }
249
232
 
250
- // A push-able async generator used as the streaming-input prompt: it yields
251
- // queued user messages and awaits when empty, so the session stays open between
252
- // turns instead of ending when the current input is consumed.
233
+ // Waiting when empty keeps the SDK session open between prompts.
253
234
  function createInputQueue(): InputQueue {
254
235
  const buffer: SDKUserMessage[] = []
255
236
  let wake: (() => void) | null = null
@@ -270,9 +251,10 @@ function createInputQueue(): InputQueue {
270
251
 
271
252
  return {
272
253
  iterator: gen(),
273
- push(content: MessageContent) {
254
+ push(content: MessageContent, uuid: NonNullable<SDKUserMessage['uuid']>) {
274
255
  buffer.push({
275
256
  type: 'user',
257
+ uuid,
276
258
  message: { role: 'user', content },
277
259
  parent_tool_use_id: null
278
260
  })
@@ -290,12 +272,22 @@ function createInputQueue(): InputQueue {
290
272
  }
291
273
  }
292
274
 
293
- // Set the session's activity and broadcast the transition (deduped — repeated
294
- // same-value events from the SDK don't re-broadcast).
295
275
  function setActivity(s: LiveSession, activity: SessionActivity) {
296
- if (s.activity === activity) return
297
276
  s.activity = activity
298
- broadcast(s.workspaceId, { type: 'status', sessionId: s.sessionId, activity })
277
+ publishMessageActivity(s.messages)
278
+ }
279
+
280
+ function messageActivity(messages: SessionMessages): SessionActivity {
281
+ const activity = messages.live?.activity ?? 'idle'
282
+ if (activity !== 'idle') return activity
283
+ return messages.active || messages.pending.length || messages.dispatching ? 'running' : 'idle'
284
+ }
285
+
286
+ function publishMessageActivity(messages: SessionMessages) {
287
+ const activity = messageActivity(messages)
288
+ if (messages.publishedActivity === activity) return
289
+ messages.publishedActivity = activity
290
+ broadcast(messages.workspaceId, { type: 'status', sessionId: messages.sessionId, activity })
299
291
  }
300
292
 
301
293
  function clearIdle(s: LiveSession) {
@@ -308,10 +300,9 @@ function clearIdle(s: LiveSession) {
308
300
  function armIdle(s: LiveSession) {
309
301
  clearIdle(s)
310
302
  s.idleTimer = setTimeout(() => {
311
- if (s.activity === 'running') return
303
+ if (s.activity !== 'idle' || s.messages.active || s.messages.dispatching) return
312
304
  if (s.bgTasks.size > 0) {
313
- // Tearing down would kill the subprocess and its background children
314
- // (renders, watch loops). Keep the session alive until they finish.
305
+ // Eviction would kill the background tasks too.
315
306
  debug(
316
307
  `cc idle-keepalive ws=${s.workspaceId} session=${s.sessionId} bgTasks=${s.bgTasks.size}`
317
308
  )
@@ -342,6 +333,15 @@ function teardown(s: LiveSession) {
342
333
  if (sessions.get(recKey(s.workspaceId, s.sessionId)) === s) {
343
334
  sessions.delete(recKey(s.workspaceId, s.sessionId))
344
335
  }
336
+ if (s.messages.live === s) s.messages.live = undefined
337
+ publishMessageActivity(s.messages)
338
+ forgetEmptyQueue(s.messages)
339
+ }
340
+
341
+ function forgetEmptyQueue(messages: SessionMessages) {
342
+ if (messages.live || messages.dispatching || messages.active || messages.pending.length) return
343
+ const key = recKey(messages.workspaceId, messages.sessionId)
344
+ if (messageQueues.get(key) === messages) messageQueues.delete(key)
345
345
  }
346
346
 
347
347
  function isCurrentLiveSession(s: LiveSession, abort: AbortController): boolean {
@@ -386,39 +386,46 @@ function startClaudeSessionTitleJob(s: LiveSession) {
386
386
  })()
387
387
  }
388
388
 
389
- // On `system/init` the SDK reports the real session id. For a brand-new session
390
- // that differs from the client's temporary id, so we rekey the registry and
391
- // tell the client to move its optimistic state. Subsequent inits report the
392
- // same id and no-op.
389
+ // Move both registries to the SDK's real id, preserving the temporary alias.
393
390
  function renameSession(s: LiveSession, realId: string): string {
394
391
  const from = s.sessionId
395
392
  sessions.delete(recKey(s.workspaceId, from))
396
393
  s.sessionId = realId
397
394
  sessions.set(recKey(s.workspaceId, realId), s)
398
395
  aliases.set(recKey(s.workspaceId, from), realId)
396
+ messageQueues.delete(recKey(s.workspaceId, from))
397
+ s.messages.sessionId = realId
398
+ s.messages.isNew = false
399
+ messageQueues.set(recKey(s.workspaceId, realId), s.messages)
399
400
  return from
400
401
  }
401
402
 
402
- // The session just went idle (state event, or `result` on a CLI without state
403
- // events): settle the view builder, then either rebuild for a deferred
404
- // effort/streaming change or arm the idle timer.
403
+ // Keep the active message reserved across async bookkeeping. Sends arriving
404
+ // here join moi's queue; they cannot race a teardown or change the live model.
405
405
  async function onSessionIdle(s: LiveSession) {
406
+ const active = s.messages.active
407
+ if (s.messages.dispatching || (active && !s.turnEnded)) return
406
408
  await markViewBuilderWaitingBySession(
407
409
  s.workspaceId,
408
410
  s.workspacePath,
409
411
  s.sessionId,
410
412
  s.lastBuilderError
411
413
  )
412
- if (s.desiredEffort !== s.effort || s.desiredStream !== s.stream) teardown(s)
413
- else armIdle(s)
414
+ if (s.closed || s.messages.dispatching || s.messages.active !== active) return
415
+ active?.complete()
416
+ s.messages.active = null
417
+ setActivity(s, 'idle')
418
+ armIdle(s)
419
+ void dispatchNextMessage(s.messages)
414
420
  }
415
421
 
416
422
  async function consume(s: LiveSession) {
417
423
  try {
418
424
  for await (const msg of s.q) {
419
- // Raw SDK message into the debug wire ring (/playground/harness).
425
+ if (s.closed) break
420
426
  tapWire(s.workspaceId, 'recv', msg)
421
427
  if (msg.type === 'system' && msg.subtype === 'init') {
428
+ s.messages.isNew = false
422
429
  const realId = msg.session_id
423
430
  if (realId && realId !== s.sessionId) {
424
431
  const from = renameSession(s, realId)
@@ -433,10 +440,7 @@ async function consume(s: LiveSession) {
433
440
  })
434
441
  }
435
442
  startClaudeSessionTitleJob(s)
436
- // Seed the session's config from what it actually ran with — but only if
437
- // it has none yet, so an explicit user PUT (or a migrated temp-id edit)
438
- // always wins. A default run leaves no file and falls back to the
439
- // workspace defaults.
443
+ // Seed explicit startup settings only when no saved picker choice exists.
440
444
  if (
441
445
  (s.model || s.effort || s.fastMode !== undefined) &&
442
446
  !(await hasSessionConfig(s.workspacePath, s.sessionId))
@@ -450,8 +454,7 @@ async function consume(s: LiveSession) {
450
454
  }
451
455
  for (const ev of s.adapter.ingest(msg)) {
452
456
  if (ev.kind === 'preview') {
453
- // Live-only token preview — a sibling frame, never a StreamEvent, so
454
- // it never enters the persisted/replayable transcript path.
457
+ // Token previews are transient and stay outside transcript history.
455
458
  broadcast(s.workspaceId, {
456
459
  type: 'preview',
457
460
  sessionId: s.sessionId,
@@ -466,18 +469,12 @@ async function consume(s: LiveSession) {
466
469
  if (msg.type === 'system' && msg.subtype === 'init') {
467
470
  debug(`cc init ws=${s.workspaceId} session=${s.sessionId}`)
468
471
  }
469
- // A turn is producing output while we think the session is idle: a
470
- // queued message the CLI ran as its own turn after the previous result,
471
- // or an SDK-initiated turn (e.g. a background-task notification waking
472
- // the model). Re-assert running so the spinner tracks real activity.
472
+ // Background notifications can start an SDK turn without a user send.
473
473
  if ((msg.type === 'assistant' || msg.type === 'stream_event') && s.activity === 'idle') {
474
474
  setActivity(s, 'running')
475
475
  }
476
- // Authoritative activity mirror. The CLI emits `idle` only once its own
477
- // input queue drains, so queued messages the model merged into one turn
478
- // (one `result` for N sends) still end in a clean idle here. Observed
479
- // empirically: current CLIs don't emit this in streaming-input mode, so
480
- // the `result` fallback below is the everyday path.
476
+ // Prefer explicit idle events when available; otherwise use the result
477
+ // fallback below. Some CLIs omit these events in streaming-input mode.
481
478
  if (msg.type === 'system' && msg.subtype === 'session_state_changed') {
482
479
  s.sawStateEvents = true
483
480
  s.lastActivityAt = Date.now()
@@ -485,35 +482,54 @@ async function consume(s: LiveSession) {
485
482
  if (msg.state === 'running') setActivity(s, 'running')
486
483
  else if (msg.state === 'requires_action') setActivity(s, 'requires-action')
487
484
  else if (msg.state === 'idle') {
488
- setActivity(s, 'idle')
489
485
  await onSessionIdle(s)
490
486
  }
491
487
  }
492
- // Background-task lifecycle (typed SDK events): track live background
493
- // work so idle eviction doesn't kill it (armIdle keep-alive). Only task
494
- // types that outlive the turn count; subagent Tasks end within it.
495
- if (msg.type === 'system' && msg.subtype === 'task_started') {
496
- if (BG_TASK_TYPES.has(msg.task_type ?? '')) {
497
- s.bgTasks.add(msg.task_id)
498
- debug(
499
- `cc bg-task start ws=${s.workspaceId} session=${s.sessionId} task=${msg.task_id} type=${msg.task_type} live=${s.bgTasks.size}`
500
- )
488
+ // Snapshots replace the entire set, healing missed starts/completions.
489
+ // Keep the edge-based fallback only until this process sends a snapshot.
490
+ if (msg.type === 'system') {
491
+ let tasksChanged = false
492
+ if (msg.subtype === 'background_tasks_changed') {
493
+ s.sawBackgroundSnapshot = true
494
+ s.bgTasks = new Set(msg.tasks.map(task => task.task_id))
495
+ tasksChanged = true
496
+ } else if (!s.sawBackgroundSnapshot) {
497
+ if (
498
+ msg.subtype === 'task_started' &&
499
+ (msg.is_backgrounded || LEGACY_BG_TASK_TYPES.has(msg.task_type ?? ''))
500
+ ) {
501
+ s.bgTasks.add(msg.task_id)
502
+ } else if (msg.subtype === 'task_notification') {
503
+ tasksChanged = s.bgTasks.delete(msg.task_id)
504
+ } else if (msg.subtype === 'task_updated') {
505
+ const status = msg.patch.status
506
+ if (
507
+ status === 'completed' ||
508
+ status === 'failed' ||
509
+ status === 'killed' ||
510
+ msg.patch.is_backgrounded === false
511
+ ) {
512
+ tasksChanged = s.bgTasks.delete(msg.task_id)
513
+ } else if (msg.patch.is_backgrounded) {
514
+ s.bgTasks.add(msg.task_id)
515
+ }
516
+ }
501
517
  }
502
- }
503
- if (msg.type === 'system' && msg.subtype === 'task_notification') {
504
- if (s.bgTasks.delete(msg.task_id)) {
505
- debug(
506
- `cc bg-task end ws=${s.workspaceId} session=${s.sessionId} task=${msg.task_id} status=${msg.status} live=${s.bgTasks.size}`
507
- )
508
- }
509
- }
510
- if (msg.type === 'system' && msg.subtype === 'task_updated') {
511
- const status = msg.patch?.status
512
- if (status === 'completed' || status === 'failed' || status === 'killed') {
513
- s.bgTasks.delete(msg.task_id)
518
+ if (tasksChanged) {
519
+ debug(`cc bg-tasks ws=${s.workspaceId} session=${s.sessionId} live=${s.bgTasks.size}`)
520
+ void dispatchNextMessage(s.messages)
514
521
  }
515
522
  }
516
523
  if (msg.type === 'result') {
524
+ // Newer CLIs identify the user messages consumed by a result. An
525
+ // autonomous background turn can finish while our prompt is still
526
+ // waiting inside the CLI; its result must not release that prompt.
527
+ const active = s.messages.active
528
+ const consumed =
529
+ msg.user_message_uuids ?? (msg.user_message_uuid ? [msg.user_message_uuid] : undefined)
530
+ const turnFinished =
531
+ !active || (!msg.queued_turn_count && (!consumed || consumed.includes(active.wireId)))
532
+ if (turnFinished) s.turnEnded = true
517
533
  s.lastActivityAt = Date.now()
518
534
  // Remembered for the idle transition — the view builder shows the last
519
535
  // turn's error once the queue drains.
@@ -526,11 +542,9 @@ async function consume(s: LiveSession) {
526
542
  s.refreshSessionsOnResult = false
527
543
  broadcast(s.workspaceId, { type: 'sessions_changed', sessionId: s.sessionId })
528
544
  }
529
- // Fallback for CLIs that never emit `session_state_changed`: treat
530
- // every result as turn-over. With state events, `idle` follows the
531
- // result and drives the same path.
532
- if (!s.sawStateEvents) {
533
- setActivity(s, 'idle')
545
+ // Without state events, only a result that finishes the active prompt
546
+ // (or an autonomous turn when none is active) can release the queue.
547
+ if (!s.sawStateEvents && turnFinished) {
534
548
  await onSessionIdle(s)
535
549
  }
536
550
  }
@@ -549,18 +563,40 @@ async function consume(s: LiveSession) {
549
563
  await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId, message)
550
564
  }
551
565
  } finally {
552
- // teardown broadcasts the terminal idle status itself (deduped).
566
+ // An expected restart only replaces the subprocess. An unexpected exit
567
+ // cancels pending sends visibly rather than leaving their promises hanging.
568
+ if (!s.closed) {
569
+ const error = new Error('Agent session closed before queued messages were sent')
570
+ if (s.messages.pending.length)
571
+ broadcast(s.workspaceId, { kind: 'error', sessionId: s.sessionId, content: error.message })
572
+ cancelPendingMessages(s.messages, error)
573
+ s.messages.active?.complete()
574
+ s.messages.active = null
575
+ }
553
576
  teardown(s)
554
577
  }
555
578
  }
556
579
 
580
+ function cancelPendingMessages(messages: SessionMessages, error: Error) {
581
+ for (const message of messages.pending.splice(0)) {
582
+ message.reject(error)
583
+ message.complete()
584
+ }
585
+ }
586
+
557
587
  // Close one idle session to stay under the cap. A running session — or one
558
588
  // with live background tasks — is never evicted; if everything is busy we allow
559
589
  // a temporary overflow rather than killing a run.
560
590
  function evictIfNeeded() {
561
591
  if (sessions.size < MAX_LIVE_SESSIONS) return
562
592
  for (const s of sessions.values()) {
563
- if (s.activity === 'idle' && s.bgTasks.size === 0) {
593
+ if (
594
+ s.activity === 'idle' &&
595
+ s.bgTasks.size === 0 &&
596
+ !s.messages.dispatching &&
597
+ !s.messages.active &&
598
+ s.messages.pending.length === 0
599
+ ) {
564
600
  teardown(s)
565
601
  return
566
602
  }
@@ -568,6 +604,7 @@ function evictIfNeeded() {
568
604
  }
569
605
 
570
606
  function createLiveSession(input: {
607
+ messages: SessionMessages
571
608
  workspaceId: string
572
609
  workspacePath: string
573
610
  sessionId: string
@@ -575,11 +612,8 @@ function createLiveSession(input: {
575
612
  model: string | undefined
576
613
  effort: string | undefined
577
614
  fastMode: boolean | undefined
578
- // Live token streaming (`includePartialMessages`). Only enabled when the
579
- // client opts in; off leaves the query byte-for-byte as before.
580
615
  stream: boolean
581
- // Resolved workspace env (.env + UI custom overrides), injected so the agent's
582
- // Bash tool can use workspace secrets. Frozen at spawn — see restartWorkspaceSessions.
616
+ // Resolved workspace env, fixed for the lifetime of the subprocess.
583
617
  workspaceEnv: Record<string, string>
584
618
  sessionTitleSource: string | undefined
585
619
  }): LiveSession {
@@ -590,25 +624,17 @@ function createLiveSession(input: {
590
624
  const options: Options = {
591
625
  abortController: abort,
592
626
  pathToClaudeCodeExecutable: requireHarnessExecutable('claude-code'),
593
- // Generous: one query() spans the whole live session (many turns). On end
594
- // (limit hit / closed / error) the session is torn down and the next
595
- // message recreates it via resume.
627
+ // One query spans many user messages.
596
628
  maxTurns: 1000,
597
629
  cwd: input.workspacePath,
598
- // Current-gen models (Sonnet 5, Opus 4.7/4.8, Fable 5) default thinking
599
- // display to 'omitted' — the API still emits a `thinking` block but with
600
- // empty text, which the adapter drops (`if (b.thinking)`), so no
601
- // "Thinking" row ever reaches the timeline. Request the summary
602
- // explicitly so reasoning stays visible.
630
+ // Request summaries explicitly; some models otherwise omit thinking text.
603
631
  thinking: { type: 'adaptive', display: 'summarized' },
604
632
  ...(input.model ? { model: input.model } : {}),
605
- // The picker only offers a model's own `supportedEffortLevels`, so the value
606
- // is valid for the model; the SDK silently downgrades otherwise. Cast because
607
- // the SDK under-types the union (no 'xhigh') vs our pass-through string.
633
+ // Harness-neutral settings are strings; the picker supplies this model's
634
+ // supported effort levels from the SDK catalog.
608
635
  ...(input.effort ? { effort: input.effort as Options['effort'] } : {}),
609
636
  ...(input.fastMode !== undefined ? { settings: { fastMode: input.fastMode } } : {}),
610
- // Emit `stream_event` partial-message frames so the adapter can surface a
611
- // live token-by-token preview. Off = unchanged behavior (whole blocks only).
637
+ // Partial frames enable the opt-in live preview.
612
638
  includePartialMessages: input.stream,
613
639
  permissionMode: 'auto',
614
640
  // Every tool call is approved before the permission system runs — see
@@ -625,6 +651,7 @@ function createLiveSession(input: {
625
651
  if (!input.isNew) options.resume = input.sessionId
626
652
 
627
653
  const session: LiveSession = {
654
+ messages: input.messages,
628
655
  workspaceId: input.workspaceId,
629
656
  workspacePath: input.workspacePath,
630
657
  workspaceEnv: input.workspaceEnv,
@@ -635,13 +662,14 @@ function createLiveSession(input: {
635
662
  abort,
636
663
  activity: 'idle',
637
664
  sawStateEvents: false,
665
+ turnEnded: false,
638
666
  bgTasks: new Set(),
667
+ sawBackgroundSnapshot: false,
639
668
  model: input.model,
640
669
  fastMode: input.fastMode,
641
670
  effort: input.effort,
642
- desiredEffort: input.effort,
643
671
  stream: input.stream,
644
- desiredStream: input.stream,
672
+ staleCli: false,
645
673
  idleTimer: null,
646
674
  closed: false,
647
675
  lastBuilderError: undefined,
@@ -653,6 +681,7 @@ function createLiveSession(input: {
653
681
  sessionTitleAbort: null
654
682
  }
655
683
  sessions.set(recKey(session.workspaceId, session.sessionId), session)
684
+ input.messages.live = session
656
685
  debug(
657
686
  `cc create ${input.isNew ? 'new' : 'resume'} ws=${input.workspaceId} session=${input.sessionId} model=${input.model ?? 'default'} effort=${input.effort ?? 'default'} fast=${input.fastMode ?? 'default'} live=${sessions.size}`
658
687
  )
@@ -660,38 +689,14 @@ function createLiveSession(input: {
660
689
  return session
661
690
  }
662
691
 
663
- // Enqueue a user message into the thread's live session, creating it on first
664
- // use. Safe to call while a turn is in flight — the message is queued.
665
- export async function sendCCMessage(input: {
666
- workspaceId: string
667
- workspacePath: string
668
- sessionId: string
669
- isNew: boolean
670
- content: string
671
- // Upload ids attached to this turn (resolved from the upload store here).
672
- attachments?: string[]
673
- optimisticId?: string
674
- model?: string
675
- effort?: string
676
- fastMode?: boolean
677
- stream?: boolean
678
- // Structured moi context (lib/moi-context.ts), rendered here and injected
679
- // as a leading system-reminder text block; the display parts never see it.
680
- context?: MoiContext
681
- }): Promise<void> {
682
- // Resolve any attachments into agent content blocks + display parts. Unknown
683
- // or expired ids are silently dropped (resolveUploads filters them) — if that
684
- // leaves nothing to say at all, don't spin up a session for an empty turn.
685
- const uploads = input.attachments?.length
686
- ? resolveUploads(input.workspaceId, input.attachments)
687
- : []
688
- if (!input.content && uploads.length === 0) return
689
- const { content: userContent, parts } = buildUserMessage(input.content, uploads)
690
- // The envelope goes in as its OWN leading text block, never merged into the
691
- // user's string: the SDK's first-prompt extraction (session titles,
692
- // home-card previews) skips tag-leading text, so a prefixed string would
693
- // hide every moi message from it. On replay the adapter strips the block to
694
- // empty and drops it.
692
+ // Accept immediately, but keep the prompt and its settings in moi until its
693
+ // turn starts. The returned promise settles when the message reaches the SDK.
694
+ export async function sendCCMessage(input: SendMessageInput): Promise<void> {
695
+ const prepared = prepareAttachmentMessage(input.workspaceId, input.content, input.attachments)
696
+ if (!prepared.text) return
697
+ const { content: userContent, parts } = buildUserMessage(prepared)
698
+ // Keep context in its own block: the SDK skips tag-leading blocks when
699
+ // extracting titles and previews, and the adapter strips them on replay.
695
700
  const content: MessageContent = input.context
696
701
  ? [
697
702
  { type: 'text', text: moiContextSystemReminder(renderMoiContext(input.context)) },
@@ -701,95 +706,26 @@ export async function sendCCMessage(input: {
701
706
  ]
702
707
  : userContent
703
708
 
704
- const wantStream = input.stream === true
705
- let s = sessions.get(liveKey(input.workspaceId, input.sessionId))
706
- // Neither effort nor streaming can be changed on a running query (both are
707
- // construct-time, no SDK setter), so when either differs we tear the idle
708
- // session down and recreate it via resume — the change lands on this very
709
- // turn. A busy session keeps its settings until the in-flight turn ends.
710
- if (s && (input.effort !== s.effort || wantStream !== s.stream) && s.activity === 'idle') {
711
- teardown(s)
712
- s = undefined
713
- }
714
- if (s) {
715
- clearIdle(s)
716
- if (input.model !== s.model) {
717
- try {
718
- await s.q.setModel(input.model)
719
- s.model = input.model
720
- } catch (err) {
721
- console.error('[cc-session] setModel failed', err)
722
- }
723
- // setModel is a control round-trip to the subprocess. During that await a
724
- // concurrent turn `result` can drain this session to idle and — if effort
725
- // or streaming diverged — tear it down (see the `result` handler). If that
726
- // happened, drop the dead handle and fall through to recreate a fresh
727
- // session below, rather than enqueue onto a closed input queue (which would
728
- // silently lose the message and hang the spinner).
729
- if (s.closed) s = undefined
730
- }
731
- if (s && input.fastMode !== s.fastMode) {
732
- try {
733
- await s.q.applyFlagSettings({ fastMode: input.fastMode ?? null })
734
- s.fastMode = input.fastMode
735
- } catch (err) {
736
- console.error('[cc-session] applyFlagSettings failed', err)
737
- }
738
- if (s.closed) s = undefined
739
- }
740
- if (s) {
741
- // Effort/streaming can't change on a running query; record the request so
742
- // the session rebuilds once its turns drain (see the `result` handler).
743
- // Reaching here with a divergent value means the session is busy — an idle
744
- // one was torn down above.
745
- s.desiredEffort = input.effort
746
- s.desiredStream = wantStream
747
- }
748
- }
749
- if (!s) {
750
- // The agent only sees secrets scoped to the 'agent' sink (plus .env).
751
- // Resolved before the probe below so both see the same env.
752
- const workspaceEnv = await resolveWorkspaceEnv(input.workspacePath)
753
- // Resuming a session with no file on disk hard-fails the CLI with "No
754
- // conversation found" — and a dangling id can be selected forever (a
755
- // brand-new chat whose first turn died before init persisted anything,
756
- // or session files cleaned up externally), wedging the chat. Start fresh
757
- // instead: the init rename then migrates this id to the real one
758
- // everywhere (selected session, session config, view builders, client).
759
- const isNew =
760
- input.isNew ||
761
- !(await claudeSessionExists(input.sessionId, input.workspacePath, workspaceEnv))
762
- if (isNew !== input.isNew) {
763
- debug(`cc resume-missing ws=${input.workspaceId} session=${input.sessionId} — starting fresh`)
764
- }
765
- s = createLiveSession({
709
+ const key = liveKey(input.workspaceId, input.sessionId)
710
+ let messages = messageQueues.get(key)
711
+ if (!messages) {
712
+ messages = {
766
713
  workspaceId: input.workspaceId,
767
714
  workspacePath: input.workspacePath,
768
- sessionId: input.sessionId,
769
- isNew,
770
- model: input.model,
771
- effort: input.effort,
772
- fastMode: input.fastMode,
773
- stream: wantStream,
774
- sessionTitleSource: isNew
775
- ? buildSessionTitleSource(
776
- input.content,
777
- uploads.map(upload => upload.filename)
778
- )
779
- : undefined,
780
- workspaceEnv
781
- })
715
+ sessionId: aliases.get(recKey(input.workspaceId, input.sessionId)) ?? input.sessionId,
716
+ isNew: input.isNew && !aliases.has(recKey(input.workspaceId, input.sessionId)),
717
+ pending: [],
718
+ active: null,
719
+ dispatching: false,
720
+ stopping: false,
721
+ publishedActivity: 'idle'
722
+ }
723
+ messageQueues.set(key, messages)
782
724
  }
783
- // Streaming-input mode does NOT echo the pushed user message back in the
784
- // output stream (string-prompt mode did — that's what expectUserEcho was
785
- // for), so the adapter never emits a user turn. Synthesize and broadcast it
786
- // ourselves so EVERY connected tab shows the user's bubble — not just the
787
- // sender (which inserts it optimistically). Keyed by optimisticId, so the
788
- // sender's optimistic turn upserts in place rather than duplicating.
789
725
  const turnId = input.optimisticId ?? crypto.randomUUID()
790
- broadcast(s.workspaceId, {
726
+ broadcast(messages.workspaceId, {
791
727
  kind: 'turn',
792
- sessionId: s.sessionId,
728
+ sessionId: messages.sessionId,
793
729
  turn: {
794
730
  id: turnId,
795
731
  role: 'user',
@@ -798,50 +734,177 @@ export async function sendCCMessage(input: {
798
734
  timestamp: new Date().toISOString()
799
735
  }
800
736
  })
801
- // Safety net: if a future SDK does echo the user message, the adapter re-ids
802
- // that echo to the same optimisticId so it collapses onto the turn above
803
- // instead of duplicating.
804
- if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, input.content)
805
-
806
- s.lastActivityAt = Date.now()
807
- // For an attachment-only message, fall back to the filenames so the thread
808
- // list / status view don't show a blank label.
809
- const label = input.content || uploads.map(u => u.filename).join(', ')
810
- s.lastUserText = label.replace(/\s+/g, ' ').slice(0, 120)
811
-
812
- // Optimistic flip — the authoritative `session_state_changed: running` from
813
- // the subprocess confirms it moments later (setActivity dedupes).
814
- if (s.activity !== 'running') {
737
+ const label = input.content || prepared.attachments.map(attachmentLabel).join(', ')
738
+ const completion = Promise.withResolvers<void>()
739
+ const accepted = new Promise<void>((resolve, reject) => {
740
+ messages.pending.push({
741
+ input,
742
+ content,
743
+ titleSource: buildSessionTitleSource(
744
+ input.content,
745
+ prepared.attachments.map(attachmentLabel)
746
+ ),
747
+ turnId,
748
+ wireId: crypto.randomUUID(),
749
+ label: label.replace(/\s+/g, ' ').slice(0, 120),
750
+ resolve,
751
+ reject,
752
+ completed: completion.promise,
753
+ complete: completion.resolve
754
+ })
755
+ })
756
+ publishMessageActivity(messages)
757
+ void dispatchNextMessage(messages)
758
+ return accepted
759
+ }
760
+
761
+ // Serialize session creation, per-message settings, and prompt writes.
762
+ // Recheck cancellation and replacement after awaits before sending the prompt.
763
+ async function dispatchNextMessage(messages: SessionMessages): Promise<void> {
764
+ if (messages.dispatching || messages.stopping || messages.active) return
765
+ const message = messages.pending[0]
766
+ if (!message) {
767
+ forgetEmptyQueue(messages)
768
+ return
769
+ }
770
+ let s = messages.live
771
+ if (s && s.activity !== 'idle') return
772
+ const { input } = message
773
+ const stream = input.stream === true
774
+ const rebuild = s && (s.staleCli || stream !== s.stream)
775
+ // Background jobs belong to their subprocess. Retain both the job and the
776
+ // queued prompt until it is safe to resume with the requested configuration.
777
+ if (s && rebuild && s.bgTasks.size > 0) return
778
+
779
+ messages.dispatching = true
780
+ const cancelled = () => messages.stopping || messages.pending[0] !== message
781
+ try {
782
+ if (s && rebuild) {
783
+ teardown(s)
784
+ s = undefined
785
+ }
786
+ if (!s) {
787
+ const workspaceEnv = await resolveWorkspaceEnv(messages.workspacePath)
788
+ if (cancelled()) return
789
+ const isNew =
790
+ messages.isNew ||
791
+ !(await claudeSessionExists(messages.sessionId, messages.workspacePath, workspaceEnv))
792
+ if (cancelled()) return
793
+ s = createLiveSession({
794
+ messages,
795
+ workspaceId: messages.workspaceId,
796
+ workspacePath: messages.workspacePath,
797
+ sessionId: messages.sessionId,
798
+ isNew,
799
+ model: input.model,
800
+ effort: input.effort,
801
+ fastMode: input.fastMode,
802
+ stream,
803
+ workspaceEnv,
804
+ sessionTitleSource: isNew ? message.titleSource : undefined
805
+ })
806
+ } else {
807
+ clearIdle(s)
808
+ // A failed setter must reject this send, never silently use the previous
809
+ // model or flags. Later queued messages can still use the healthy query.
810
+ if (input.model !== s.model) {
811
+ await s.q.setModel(input.model)
812
+ // Stop cancels the prompt, not a control request already acknowledged
813
+ // by the CLI. Remember the applied value so the next send can reset it.
814
+ if (!s.closed) s.model = input.model
815
+ if (cancelled()) return
816
+ if (s.closed) throw new Error('Agent session closed before the message was sent')
817
+ }
818
+ if (input.effort !== s.effort || input.fastMode !== s.fastMode) {
819
+ await s.q.applyFlagSettings({
820
+ ...(input.effort !== s.effort
821
+ ? { effortLevel: (input.effort as Options['effort']) ?? null }
822
+ : {}),
823
+ ...(input.fastMode !== s.fastMode ? { fastMode: input.fastMode ?? null } : {})
824
+ })
825
+ if (!s.closed) {
826
+ s.effort = input.effort
827
+ s.fastMode = input.fastMode
828
+ }
829
+ if (cancelled()) return
830
+ if (s.closed) throw new Error('Agent session closed before the message was sent')
831
+ }
832
+ }
815
833
  await markViewBuilderBuildingBySession(s.workspaceId, s.workspacePath, s.sessionId)
834
+ if (cancelled()) return
835
+ if (s.closed) throw new Error('Agent session closed before the message was sent')
836
+ // A catalog refresh can arrive during any of the awaits above. Retry
837
+ // before handing off the prompt; the queue still owns it at this point.
838
+ if (s.staleCli) {
839
+ if (s.bgTasks.size === 0) teardown(s)
840
+ return
841
+ }
842
+ messages.pending.shift()
843
+ messages.active = message
844
+ s.turnEnded = false
845
+ s.lastActivityAt = Date.now()
846
+ s.lastUserText = message.label
847
+ s.adapter.expectUserEcho(message.turnId, input.content)
816
848
  setActivity(s, 'running')
849
+ clearIdle(s)
850
+ s.input.push(message.content, message.wireId)
851
+ tapWire(s.workspaceId, 'send', { type: 'user', content: message.content })
852
+ message.resolve()
853
+ } catch (error) {
854
+ if (!cancelled() && s?.staleCli) {
855
+ if (!s.closed && s.bgTasks.size === 0) teardown(s)
856
+ return
857
+ }
858
+ if (!cancelled()) {
859
+ messages.pending.shift()
860
+ const err = error instanceof Error ? error : new Error(String(error))
861
+ broadcast(messages.workspaceId, {
862
+ kind: 'error',
863
+ sessionId: messages.sessionId,
864
+ content: err.message
865
+ })
866
+ message.reject(err)
867
+ message.complete()
868
+ }
869
+ } finally {
870
+ messages.dispatching = false
871
+ publishMessageActivity(messages)
872
+ if (s && !s.closed && s.activity === 'idle') armIdle(s)
873
+ void dispatchNextMessage(messages)
817
874
  }
818
- clearIdle(s)
819
- s.input.push(content)
820
- tapWire(s.workspaceId, 'send', { type: 'user', content })
821
- debug(
822
- `cc enqueue ws=${s.workspaceId} session=${s.sessionId} activity=${s.activity} text=${JSON.stringify(s.lastUserText)}`
823
- )
824
875
  }
825
876
 
826
- // How long Stop waits for the SDK's interrupt round-trip before declaring the
827
- // subprocess wedged and tearing it down. A hung subprocess never answers, and
828
- // without this cap the whole interrupt path (and the user's only escape hatch
829
- // from a stuck spinner) hangs with it.
877
+ // Bound both interrupt acknowledgement and turn completion.
830
878
  const INTERRUPT_TIMEOUT_MS = 5_000
831
879
 
832
- // Interrupt the current turn and drop any queued messages, keeping the session
833
- // alive for the next message. If the subprocess doesn't acknowledge in time it
834
- // is torn down instead — the next message respawns via resume.
880
+ // Cancel queued sends and interrupt the active turn. A failed or timed-out
881
+ // interrupt closes the process so the next send can resume in a fresh one.
835
882
  export async function interruptCCSession(workspaceId: string, sessionId: string): Promise<void> {
836
- const s = sessions.get(liveKey(workspaceId, sessionId))
837
- if (!s) return
883
+ const messages = messageQueues.get(liveKey(workspaceId, sessionId))
884
+ if (!messages) return
885
+ messages.stopping = true
886
+ cancelPendingMessages(messages, new Error('Message cancelled'))
887
+ const s = messages.live
888
+ if (!s) {
889
+ messages.stopping = false
890
+ publishMessageActivity(messages)
891
+ forgetEmptyQueue(messages)
892
+ broadcast(workspaceId, { kind: 'stopped', sessionId: messages.sessionId })
893
+ return
894
+ }
838
895
  debug(`cc interrupt ws=${workspaceId} session=${sessionId} activity=${s.activity}`)
839
896
  s.input.clear()
840
897
  let timer: ReturnType<typeof setTimeout> | undefined
841
898
  const timedOut = Symbol('interrupt-timeout')
899
+ const active = messages.active
842
900
  try {
843
901
  const outcome = await Promise.race([
844
- s.q.interrupt(),
902
+ (async () => {
903
+ await s.q.interrupt()
904
+ // Receipt and result are separate protocol messages. Bound both so a
905
+ // CLI that acknowledges Stop but never finishes cannot wedge the chat.
906
+ await active?.completed
907
+ })(),
845
908
  new Promise(resolve => {
846
909
  timer = setTimeout(() => resolve(timedOut), INTERRUPT_TIMEOUT_MS)
847
910
  })
@@ -855,25 +918,66 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
855
918
  teardown(s)
856
919
  } finally {
857
920
  clearTimeout(timer)
921
+ if (s.closed) {
922
+ active?.complete()
923
+ messages.active = null
924
+ }
925
+ messages.stopping = false
858
926
  }
859
927
  broadcast(s.workspaceId, { kind: 'stopped', sessionId: s.sessionId })
860
- setActivity(s, 'idle')
928
+ if (!messages.active) setActivity(s, 'idle')
861
929
  await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId)
862
- if (!s.closed) armIdle(s)
930
+ if (!s.closed && !messages.active) armIdle(s)
931
+ void dispatchNextMessage(messages)
863
932
  }
864
933
 
865
- // Tear down a workspace's IDLE sessions so the next message respawns the agent
866
- // with fresh env. A running claude subprocess can't pick up new env vars, and
867
- // mid-turn reload isn't supported — busy sessions keep their snapshot until the
868
- // turn ends (then idle-evict or get recreated on the next message via resume).
934
+ // Evict idle sessions so their next send picks up fresh workspace env. Busy
935
+ // sessions retain their environment until a later teardown.
869
936
  export function restartWorkspaceSessions(workspacePath: string): void {
870
937
  for (const s of [...sessions.values()]) {
871
- if (s.workspacePath === workspacePath && s.activity === 'idle') teardown(s)
938
+ if (
939
+ s.workspacePath === workspacePath &&
940
+ s.activity === 'idle' &&
941
+ s.bgTasks.size === 0 &&
942
+ !s.messages.dispatching &&
943
+ !s.messages.active &&
944
+ s.messages.pending.length === 0
945
+ )
946
+ teardown(s)
872
947
  }
873
948
  }
874
949
 
875
- // Close every live session — called on server shutdown so no claude subprocess
876
- // is orphaned.
950
+ // Stop every queued message and subprocess for a workspace being removed.
951
+ export function killWorkspaceSessions(workspacePath: string): void {
952
+ for (const messages of messageQueues.values()) {
953
+ if (messages.workspacePath !== workspacePath) continue
954
+ messages.stopping = true
955
+ cancelPendingMessages(messages, new Error('Workspace removed'))
956
+ messages.active?.complete()
957
+ messages.active = null
958
+ }
959
+ for (const s of [...sessions.values()]) {
960
+ if (s.workspacePath === workspacePath) teardown(s)
961
+ }
962
+ for (const [key, messages] of messageQueues) {
963
+ if (messages.workspacePath === workspacePath) messageQueues.delete(key)
964
+ }
965
+ }
966
+
967
+ // A CLI update may introduce models the current process cannot use. Mark it
968
+ // for replacement at the next safe dispatch boundary.
969
+ export function retireCCSessionsOnCliChange(): void {
970
+ for (const s of sessions.values()) s.staleCli = true
971
+ }
972
+
973
+ // Server shutdown must settle pending sends and close every subprocess.
877
974
  export function killAllCCSessions(): void {
975
+ for (const messages of messageQueues.values()) {
976
+ messages.stopping = true
977
+ cancelPendingMessages(messages, new Error('Agent sessions stopped'))
978
+ messages.active?.complete()
979
+ messages.active = null
980
+ }
878
981
  for (const s of [...sessions.values()]) teardown(s)
982
+ messageQueues.clear()
879
983
  }