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,21 +1,9 @@
1
- // Per-(workspaceId, sessionId) live Codex session adapter.
2
- //
3
- // One `codex app-server` process per workspace (see codex.ts) serves every
4
- // thread in it; this module owns the per-thread state: the durable in-memory
5
- // view, turn accounting for the processing spinner, and the mapping of
6
- // `item/*` notifications onto our `StreamEvent`s.
7
- //
8
- // Lifecycle notes:
9
- // - A brand-new thread is created under the client's temporary uuid, then
10
- // renamed to the Codex thread id (`session_renamed`) — same flow as the
11
- // Claude Code and OpenClaw paths.
12
- // - The app-server persists threads in ~/.codex/sessions and unloads idle
13
- // ones itself, so there is no eviction machinery here; a cold send
14
- // re-seeds via `thread/resume`.
15
- // - Codex natively echoes the user message back with our
16
- // `clientUserMessageId` as `clientId`, so the optimistic-id rendezvous is
17
- // first-class (no text matching like OpenClaw needs).
18
- import { appendAttachmentNote } from '@/lib/attachment-note'
1
+ import type { MessageAttachment } from '@/lib/types'
2
+ import { attachmentLabel } from '@/lib/moi-attachments'
3
+ // Live state per (workspaceId, sessionId): display history, native lifecycle,
4
+ // and previews. client.ts owns the shared workspace process;
5
+ // Codex owns durable history. See NOTES.md for ordering and recovery rules.
6
+ import { prepareAttachmentMessage, type PreparedAttachmentMessage } from '../../attachment-message'
19
7
  import { buildSessionTitleSource } from '../session-title'
20
8
  import {
21
9
  type MoiContext,
@@ -23,7 +11,7 @@ import {
23
11
  renderMoiContext,
24
12
  renderMoiContextBody
25
13
  } from '@/lib/moi-context'
26
- import { type Part, type SubagentRecord, type Turn, applyEvent, emptyViewState } from '@/lib/format'
14
+ import { type SubagentRecord, type Turn, applyEvent, emptyViewState } from '@/lib/format'
27
15
  import type { SessionActivity, StreamEvent, ViewState } from '@/lib/types'
28
16
 
29
17
  import {
@@ -38,7 +26,14 @@ import {
38
26
  codexThreadToEvents,
39
27
  withCodexTurnDuration
40
28
  } from './adapter'
41
- import { type CodexClient, getCodexClient, interruptCodexTurn, readSubagentRecords } from './client'
29
+ import {
30
+ type CodexClient,
31
+ getCodexClient,
32
+ getCodexModelCatalog,
33
+ interruptCodexTurn,
34
+ readSubagentRecords
35
+ } from './client'
36
+ import { CodexRpcError } from './transport'
42
37
  import {
43
38
  CODEX_LOCAL_CONTROL_CONTEXT,
44
39
  CODEX_LOCAL_CONTROL_FALLBACK,
@@ -52,12 +47,6 @@ import { broadcast } from '../../state'
52
47
  import { renameSelectedSession } from '../../selected-session'
53
48
  import { hasSessionConfig, renameSessionConfig, saveSessionConfig } from '../../session-config'
54
49
  import { renameViewBuilderSession } from '../../view-builders'
55
- import {
56
- type StoredUpload,
57
- materializeToPath,
58
- resolveUploads,
59
- uploadToDisplayPart
60
- } from '../../uploads'
61
50
 
62
51
  type CodexUserInputItem = { type: 'text'; text: string } | { type: 'image'; url: string }
63
52
 
@@ -70,12 +59,17 @@ type ChildThread = {
70
59
  }
71
60
 
72
61
  type SessionRecord = {
62
+ client: CodexClient
63
+ lastTouched: number
73
64
  workspaceId: string
74
65
  workspacePath: string
75
66
  sessionId: string // real Codex thread id once known (rekeyed on rename)
76
67
  view: ViewState
77
68
  activeTurnId: string | null
78
69
  processing: boolean
70
+ waiting: boolean
71
+ activity: SessionActivity
72
+ model?: string
79
73
  // Live token streaming opt-in from the latest chat frame. Codex always
80
74
  // streams deltas; this gates whether we forward them as preview frames.
81
75
  stream: boolean
@@ -84,6 +78,13 @@ type SessionRecord = {
84
78
  // Usage from `thread/tokenUsage/updated`, folded into the last assistant
85
79
  // turn when the turn completes.
86
80
  lastUsage: CodexTokenUsage | null
81
+ usageTurnId: string | null
82
+ completedTurns: Set<string>
83
+ bufferedNotifications: [string, Record<string, unknown>][] | null
84
+ previewTimer: Timer | null
85
+ dirtyPreviews: Set<string>
86
+ commandOutput: Map<string, string>
87
+ commandOutputTimer: Timer | null
87
88
  // Child agent threads keyed by their thread id (see ChildThread).
88
89
  children: Map<string, ChildThread>
89
90
  refreshSessionsOnTurnComplete: boolean
@@ -93,8 +94,50 @@ type SessionRecord = {
93
94
  }
94
95
 
95
96
  const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
96
- // `${workspaceId}:${tempId}` -> real thread id (see cc-session.ts aliases).
97
+ // `${workspaceId}:${tempId}` -> native thread id after session_renamed.
97
98
  const aliases = new Map<string, string>()
99
+ const resumes = new Map<string, Promise<SessionRecord>>()
100
+ type SendLane = { tail: Promise<void>; generation: number }
101
+ const sendLanes = new Map<string, SendLane>()
102
+ const SESSION_IDLE_TTL_MS = 30 * 60_000
103
+
104
+ // The provider keeps durable history. Release transcript copies and listeners
105
+ // from chats that nobody has used recently; opening one subscribes again.
106
+ const evictionTimer = setInterval(() => {
107
+ const cutoff = Date.now() - SESSION_IDLE_TTL_MS
108
+ for (const [key, rec] of sessions) {
109
+ if (
110
+ rec.lastTouched > cutoff ||
111
+ rec.processing ||
112
+ rec.bufferedNotifications ||
113
+ rec.sessionTitleAbort
114
+ )
115
+ continue
116
+ rec.unsubscribe?.()
117
+ clearPreviews(rec)
118
+ sessions.delete(key)
119
+ const lane = sendLanes.get(key)
120
+ for (const [laneKey, candidate] of sendLanes) {
121
+ if (candidate === lane) sendLanes.delete(laneKey)
122
+ }
123
+ for (const [alias, sessionId] of aliases) {
124
+ if (recKey(rec.workspaceId, sessionId) === key && alias.startsWith(`${rec.workspaceId}:`))
125
+ aliases.delete(alias)
126
+ }
127
+ void rec.client.rpc('thread/unsubscribe', { threadId: rec.sessionId }).catch(() => {})
128
+ }
129
+ }, 60_000)
130
+ evictionTimer.unref()
131
+
132
+ function sendLane(workspaceId: string, sessionId: string): SendLane {
133
+ const key = liveKey(workspaceId, sessionId)
134
+ let lane = sendLanes.get(key)
135
+ if (!lane) {
136
+ lane = { tail: Promise.resolve(), generation: 0 }
137
+ sendLanes.set(key, lane)
138
+ }
139
+ return lane
140
+ }
98
141
 
99
142
  function recKey(workspaceId: string, sessionId: string): string {
100
143
  return `${workspaceId}:${sessionId}`
@@ -117,31 +160,78 @@ export type CodexActiveSession = {
117
160
  export function getCodexActiveSessions(): CodexActiveSession[] {
118
161
  const out: CodexActiveSession[] = []
119
162
  for (const s of sessions.values()) {
120
- // moi auto-accepts provider approval requests at the transport, so a
121
- // session never blocks on approvals; requires-action is not surfaced.
122
163
  if (s.processing) {
123
164
  out.push({
124
165
  workspaceId: s.workspaceId,
125
166
  workspacePath: s.workspacePath,
126
167
  sessionId: s.sessionId,
127
- activity: 'running'
168
+ activity: sessionActivity(s)
128
169
  })
129
170
  }
130
171
  }
131
172
  return out
132
173
  }
133
174
 
175
+ // The workspace connector panel has no selected-chat parameter. Use the most
176
+ // recently observed loaded chat to obtain runtime health instead of auth alone.
177
+ export function getLatestCodexSessionId(workspaceId: string): string | undefined {
178
+ let latest: SessionRecord | undefined
179
+ for (const rec of sessions.values()) {
180
+ if (
181
+ rec.workspaceId === workspaceId &&
182
+ !rec.bufferedNotifications &&
183
+ (!latest || rec.lastTouched >= latest.lastTouched)
184
+ )
185
+ latest = rec
186
+ }
187
+ return latest?.sessionId
188
+ }
189
+
134
190
  function setProcessing(rec: SessionRecord, processing: boolean, turnId: string | null) {
135
191
  rec.activeTurnId = turnId
136
- if (rec.processing === processing) return
137
192
  rec.processing = processing
193
+ if (!processing) rec.waiting = false
194
+ publishActivity(rec)
195
+ }
196
+
197
+ function sessionActivity(rec: SessionRecord): SessionActivity {
198
+ return rec.waiting ? 'requires-action' : rec.processing ? 'running' : 'idle'
199
+ }
200
+
201
+ function publishActivity(rec: SessionRecord) {
202
+ const activity = sessionActivity(rec)
203
+ if (rec.activity === activity) return
204
+ rec.activity = activity
138
205
  broadcast(rec.workspaceId, {
139
206
  type: 'status',
140
207
  sessionId: rec.sessionId,
141
- activity: processing ? 'running' : 'idle'
208
+ activity
142
209
  })
143
210
  }
144
211
 
212
+ function waitingOnInput(status: CodexThread['status']): boolean {
213
+ return (
214
+ status?.type === 'active' &&
215
+ Boolean(
216
+ status.activeFlags?.some(
217
+ flag => flag === 'waitingOnApproval' || flag === 'waitingOnUserInput'
218
+ )
219
+ )
220
+ )
221
+ }
222
+
223
+ function releaseSession(rec: SessionRecord, reason: string) {
224
+ flushCommandOutput(rec)
225
+ clearPreviews(rec)
226
+ settleTools(rec, reason)
227
+ setProcessing(rec, false, null)
228
+ rec.sessionTitleAbort?.abort()
229
+ rec.sessionTitleAbort = null
230
+ rec.unsubscribe?.()
231
+ const key = recKey(rec.workspaceId, rec.sessionId)
232
+ if (sessions.get(key) === rec) sessions.delete(key)
233
+ }
234
+
145
235
  function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
146
236
  rec.view = applyEvent(rec.view, ev)
147
237
  broadcast(rec.workspaceId, { ...ev, sessionId: rec.sessionId })
@@ -150,6 +240,9 @@ function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
150
240
  function ingestItem(rec: SessionRecord, item: CodexThreadItem) {
151
241
  const turn = codexItemToTurn(item, rec.sessionId)
152
242
  if (turn) {
243
+ turn.timestamp =
244
+ rec.view.turns.find(existing => existing.id === turn.id)?.timestamp ??
245
+ new Date().toISOString()
153
246
  // subAgentActivity announces a child agent thread: register it so its
154
247
  // item stream (arriving under `agentThreadId`) nests into this card's
155
248
  // SubagentRecord, CC-style.
@@ -241,19 +334,105 @@ function forwardPreview(
241
334
  const entry = rec.previews.get(itemId) ?? { kind, text: '' }
242
335
  entry.text += delta
243
336
  rec.previews.set(itemId, entry)
244
- broadcast(rec.workspaceId, {
245
- type: 'preview',
246
- sessionId: rec.sessionId,
247
- messageId: itemId,
248
- parentToolUseId: null,
249
- blocks: [{ index: 0, kind, text: entry.text }]
250
- })
337
+ rec.dirtyPreviews.add(itemId)
338
+ // Coalesce tokens to reduce repeated cumulative payloads and client updates.
339
+ rec.previewTimer ??= setTimeout(() => flushPreviews(rec), 40)
340
+ }
341
+
342
+ function flushPreviews(rec: SessionRecord) {
343
+ if (rec.previewTimer) clearTimeout(rec.previewTimer)
344
+ rec.previewTimer = null
345
+ for (const itemId of rec.dirtyPreviews) {
346
+ const entry = rec.previews.get(itemId)
347
+ if (!entry) continue
348
+ broadcast(rec.workspaceId, {
349
+ type: 'preview',
350
+ sessionId: rec.sessionId,
351
+ messageId: itemId,
352
+ parentToolUseId: null,
353
+ blocks: [{ index: 0, kind: entry.kind, text: entry.text }]
354
+ })
355
+ }
356
+ rec.dirtyPreviews.clear()
357
+ }
358
+
359
+ function clearPreviews(rec: SessionRecord) {
360
+ if (rec.previewTimer) clearTimeout(rec.previewTimer)
361
+ rec.previewTimer = null
362
+ rec.dirtyPreviews.clear()
363
+ rec.previews.clear()
364
+ }
365
+
366
+ const LIVE_OUTPUT_LIMIT = 64 * 1024
367
+
368
+ function flushCommandOutput(rec: SessionRecord) {
369
+ if (rec.commandOutputTimer) clearTimeout(rec.commandOutputTimer)
370
+ rec.commandOutputTimer = null
371
+ for (const [itemId, delta] of rec.commandOutput) {
372
+ const owner = rec.view.turns.find(turn =>
373
+ turn.parts.some(
374
+ part =>
375
+ part.type === 'tool-call' &&
376
+ part.call.toolCallId === itemId &&
377
+ part.call.name === 'exec' &&
378
+ part.call.state === 'running'
379
+ )
380
+ )
381
+ if (!owner) continue
382
+ const parts = owner.parts.map(part => {
383
+ if (
384
+ part.type !== 'tool-call' ||
385
+ part.call.toolCallId !== itemId ||
386
+ part.call.state !== 'running'
387
+ )
388
+ return part
389
+ const output = `${typeof part.call.output === 'string' ? part.call.output : ''}${delta}`
390
+ return {
391
+ ...part,
392
+ call: {
393
+ ...part.call,
394
+ output:
395
+ output.length > LIVE_OUTPUT_LIMIT
396
+ ? `[Earlier live output omitted]\n${output.slice(-LIVE_OUTPUT_LIMIT)}`
397
+ : output
398
+ }
399
+ }
400
+ })
401
+ emitTurnEvent(rec, { kind: 'turn', turn: { ...owner, parts } })
402
+ }
403
+ rec.commandOutput.clear()
404
+ }
405
+
406
+ function clearCommandOutput(rec: SessionRecord) {
407
+ if (rec.commandOutputTimer) clearTimeout(rec.commandOutputTimer)
408
+ rec.commandOutputTimer = null
409
+ rec.commandOutput.clear()
410
+ }
411
+
412
+ function settleTools(rec: SessionRecord, reason: string) {
413
+ for (const turn of rec.view.turns) {
414
+ let changed = false
415
+ const parts = turn.parts.map(part => {
416
+ if (
417
+ part.type !== 'tool-call' ||
418
+ !['running', 'pending', 'approval-pending'].includes(part.call.state)
419
+ )
420
+ return part
421
+ changed = true
422
+ return { ...part, call: { ...part.call, state: 'error' as const, errorText: reason } }
423
+ })
424
+ if (changed) emitTurnEvent(rec, { kind: 'turn', turn: { ...turn, parts } })
425
+ }
251
426
  }
252
427
 
253
428
  // Fold native completion metadata into the newest assistant turn so replay and
254
429
  // live rendering use the same display shape. Re-emits that turn (upsert-by-id).
255
- function applyCompletionMeta(rec: SessionRecord, durationMs: number | null | undefined) {
256
- const last = rec.lastUsage?.last
430
+ function applyCompletionMeta(
431
+ rec: SessionRecord,
432
+ turnId: string | undefined,
433
+ durationMs: number | null | undefined
434
+ ) {
435
+ const last = rec.usageTurnId === turnId ? rec.lastUsage?.last : undefined
257
436
  for (let i = rec.view.turns.length - 1; i >= 0; i--) {
258
437
  const t = rec.view.turns[i]
259
438
  if (t.role === 'user' && t.origin.kind === 'user-input') return
@@ -278,11 +457,7 @@ function applyCompletionMeta(rec: SessionRecord, durationMs: number | null | und
278
457
  }
279
458
  }
280
459
 
281
- // A send/turn failure can mean the account was signed out from outside moi —
282
- // a `codex logout` in a terminal, say — which the cached availability
283
- // snapshot won't reflect until its TTL expires. Force a fresh probe so the
284
- // composer's availability banner flips right away instead of the next send
285
- // failing the same way.
460
+ // A failed send may reflect an external logout. Refresh the cached banner now.
286
461
  function refreshAvailability(workspaceId: string, workspacePath: string) {
287
462
  void agentStore.refresh({ id: workspaceId, path: workspacePath, type: 'codex' })
288
463
  }
@@ -291,11 +466,42 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
291
466
  if (method === '__exit') {
292
467
  // The app-server died (crash or env-change restart). Drop the record so
293
468
  // the next message re-resumes against a fresh process.
294
- setProcessing(rec, false, null)
295
- rec.sessionTitleAbort?.abort()
296
- rec.sessionTitleAbort = null
297
- rec.unsubscribe?.()
298
- sessions.delete(recKey(rec.workspaceId, rec.sessionId))
469
+ if (rec.processing)
470
+ broadcast(rec.workspaceId, {
471
+ kind: 'error',
472
+ sessionId: rec.sessionId,
473
+ content:
474
+ typeof params.message === 'string'
475
+ ? params.message
476
+ : 'Codex disconnected. Send another message to resume this chat.'
477
+ })
478
+ releaseSession(rec, 'Codex disconnected before this tool returned a result')
479
+ return
480
+ }
481
+ if (rec.bufferedNotifications) {
482
+ rec.bufferedNotifications.push([method, params])
483
+ return
484
+ }
485
+ const mcpFailure = method === 'mcpServer/startupStatus/updated' && params.status === 'failed'
486
+ if (
487
+ (method === 'warning' || method === 'configWarning' || mcpFailure) &&
488
+ (params.threadId == null || params.threadId === rec.sessionId)
489
+ ) {
490
+ const message = mcpFailure
491
+ ? `MCP ${String(params.name ?? 'server')} failed to start${typeof params.error === 'string' ? `: ${params.error}` : ''}`
492
+ : method === 'warning'
493
+ ? params.message
494
+ : params.summary
495
+ if (typeof message === 'string')
496
+ emitTurnEvent(rec, {
497
+ kind: 'notice',
498
+ notice: {
499
+ id: `codex:${rec.sessionId}:warning:${message}`,
500
+ kind: 'warning',
501
+ at: new Date().toISOString(),
502
+ message
503
+ }
504
+ })
299
505
  return
300
506
  }
301
507
  // Child agent threads stream on the same connection under their own ids —
@@ -306,16 +512,67 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
306
512
  return
307
513
  }
308
514
  if (params.threadId !== rec.sessionId) return
515
+ rec.lastTouched = Date.now()
309
516
 
310
517
  switch (method) {
518
+ case 'model/rerouted': {
519
+ if (typeof params.toModel !== 'string') return
520
+ rec.model = params.toModel
521
+ emitTurnEvent(rec, {
522
+ kind: 'notice',
523
+ notice: {
524
+ id: `codex:${rec.sessionId}:model:${String(params.turnId)}`,
525
+ kind: 'model-change',
526
+ at: new Date().toISOString(),
527
+ model: params.toModel,
528
+ ...(typeof params.fromModel === 'string' ? { prev: params.fromModel } : {})
529
+ }
530
+ })
531
+ return
532
+ }
533
+ case 'turn/plan/updated': {
534
+ if (!Array.isArray(params.plan) || typeof params.turnId !== 'string') return
535
+ const steps = params.plan.flatMap((step: unknown) => {
536
+ if (!step || typeof step !== 'object' || !('step' in step) || typeof step.step !== 'string')
537
+ return []
538
+ const status = 'status' in step ? step.status : undefined
539
+ return [
540
+ `${status === 'completed' ? '[x]' : status === 'inProgress' ? '[→]' : '[ ]'} ${step.step}`
541
+ ]
542
+ })
543
+ ingestItem(rec, {
544
+ type: 'plan',
545
+ id: `${params.turnId}:plan`,
546
+ text: [typeof params.explanation === 'string' ? params.explanation : '', ...steps]
547
+ .filter(Boolean)
548
+ .join('\n')
549
+ })
550
+ return
551
+ }
311
552
  case 'item/started':
312
553
  case 'item/completed': {
313
554
  const item = params.item as CodexThreadItem | undefined
314
555
  if (!item) return
315
- if (method === 'item/completed') rec.previews.delete(item.id)
556
+ if (method === 'item/completed') {
557
+ rec.commandOutput.delete(item.id)
558
+ rec.previews.delete(item.id)
559
+ rec.dirtyPreviews.delete(item.id)
560
+ }
316
561
  ingestItem(rec, item)
317
562
  return
318
563
  }
564
+ case 'item/commandExecution/outputDelta': {
565
+ if (typeof params.itemId !== 'string' || typeof params.delta !== 'string') return
566
+ const output = (rec.commandOutput.get(params.itemId) ?? '') + params.delta
567
+ rec.commandOutput.set(
568
+ params.itemId,
569
+ output.length > LIVE_OUTPUT_LIMIT
570
+ ? `[Earlier live output omitted]\n${output.slice(-LIVE_OUTPUT_LIMIT)}`
571
+ : output
572
+ )
573
+ rec.commandOutputTimer ??= setTimeout(() => flushCommandOutput(rec), 40)
574
+ return
575
+ }
319
576
  case 'item/agentMessage/delta': {
320
577
  forwardPreview(rec, params.itemId as string, 'text', String(params.delta ?? ''))
321
578
  return
@@ -325,9 +582,7 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
325
582
  return
326
583
  }
327
584
  case 'item/reasoning/summaryPartAdded': {
328
- // Each part is a new summary section; without a break the sections
329
- // concatenate into one run-on paragraph. Skip the first part (no
330
- // preview text yet) so the reasoning doesn't open with a blank line.
585
+ // Match replay's summary separator without adding a leading blank line.
331
586
  if (rec.previews.has(params.itemId as string)) {
332
587
  forwardPreview(rec, params.itemId as string, 'reasoning', '\n')
333
588
  }
@@ -335,17 +590,39 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
335
590
  }
336
591
  case 'thread/tokenUsage/updated': {
337
592
  rec.lastUsage = (params.tokenUsage ?? null) as CodexTokenUsage | null
593
+ rec.usageTurnId = typeof params.turnId === 'string' ? params.turnId : rec.activeTurnId
338
594
  return
339
595
  }
340
596
  case 'turn/started': {
341
597
  const turn = params.turn as CodexTurn | undefined
598
+ if (turn?.id && rec.completedTurns.has(turn.id)) return
599
+ if (rec.activeTurnId !== turn?.id) {
600
+ rec.lastUsage = null
601
+ rec.usageTurnId = null
602
+ }
342
603
  setProcessing(rec, true, turn?.id ?? rec.activeTurnId)
343
604
  return
344
605
  }
345
606
  case 'turn/completed': {
346
607
  const turn = params.turn as CodexTurn | undefined
347
- rec.previews.clear()
348
- applyCompletionMeta(rec, turn?.durationMs)
608
+ if (turn?.id && rec.completedTurns.has(turn.id)) return
609
+ if (turn?.id) {
610
+ rec.completedTurns.add(turn.id)
611
+ if (rec.completedTurns.size > 64)
612
+ rec.completedTurns.delete(rec.completedTurns.values().next().value!)
613
+ }
614
+ // A delayed completion from an older turn must not stop a newer one.
615
+ if (rec.activeTurnId && turn?.id && rec.activeTurnId !== turn.id) return
616
+ flushCommandOutput(rec)
617
+ for (const item of turn?.items ?? []) ingestItem(rec, item)
618
+ settleTools(
619
+ rec,
620
+ turn?.status === 'interrupted'
621
+ ? 'Stopped'
622
+ : 'Codex ended the turn before this tool returned a result'
623
+ )
624
+ clearPreviews(rec)
625
+ applyCompletionMeta(rec, turn?.id, turn?.durationMs)
349
626
  setProcessing(rec, false, null)
350
627
  if (rec.refreshSessionsOnTurnComplete) {
351
628
  rec.refreshSessionsOnTurnComplete = false
@@ -369,6 +646,21 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
369
646
  case 'error': {
370
647
  const err = params.error as { message?: string } | undefined
371
648
  const message = err?.message ?? (typeof params.message === 'string' ? params.message : '')
649
+ if (params.willRetry === true) {
650
+ // The provider still owns a running turn and will retry it. Do not
651
+ // expose a Retry button that would submit the user's message again.
652
+ emitTurnEvent(rec, {
653
+ kind: 'notice',
654
+ notice: {
655
+ id: `codex:${rec.sessionId}:retry:${String(params.turnId ?? rec.activeTurnId)}`,
656
+ kind: 'api-retry',
657
+ at: new Date().toISOString(),
658
+ error: message
659
+ }
660
+ })
661
+ return
662
+ }
663
+ if (params.turnId && rec.activeTurnId && params.turnId !== rec.activeTurnId) return
372
664
  if (message) {
373
665
  broadcast(rec.workspaceId, { kind: 'error', sessionId: rec.sessionId, content: message })
374
666
  refreshAvailability(rec.workspaceId, rec.workspacePath)
@@ -376,11 +668,38 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
376
668
  // A top-level error without a following turn/completed would otherwise
377
669
  // leave the session busy forever — the error is terminal for the turn.
378
670
  setProcessing(rec, false, null)
671
+ clearPreviews(rec)
672
+ flushCommandOutput(rec)
673
+ settleTools(rec, message || 'Codex ended the turn before this tool returned a result')
674
+ return
675
+ }
676
+ case 'thread/status/changed': {
677
+ const status = params.status as CodexThread['status']
678
+ rec.waiting = waitingOnInput(status)
679
+ if (status?.type === 'active') setProcessing(rec, true, rec.activeTurnId)
680
+ else if (status?.type === 'notLoaded') {
681
+ releaseSession(rec, 'Codex unloaded this chat')
682
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
683
+ } else if (status?.type === 'idle' || status?.type === 'systemError') {
684
+ flushCommandOutput(rec)
685
+ setProcessing(rec, false, null)
686
+ clearPreviews(rec)
687
+ }
379
688
  return
380
689
  }
381
- // Codex hooks (~/.codex/hooks.json) — surface as hook notices, parity
382
- // with Claude Code's. started/completed share a notice id so the row
383
- // upserts from "started" to its outcome.
690
+ case 'thread/closed':
691
+ case 'thread/archived':
692
+ case 'thread/deleted': {
693
+ releaseSession(rec, 'Codex closed this chat')
694
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
695
+ return
696
+ }
697
+ case 'thread/unarchived':
698
+ case 'thread/name/updated': {
699
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
700
+ return
701
+ }
702
+ // Reuse the notice id so completion updates the hook's started row.
384
703
  case 'hook/started':
385
704
  case 'hook/completed': {
386
705
  const run = params.run as
@@ -414,28 +733,6 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
414
733
  })
415
734
  return
416
735
  }
417
- // A per-thread MCP server that failed to start — surface it instead of
418
- // silently dropping (reuses the hook notice shape; a dedicated notice
419
- // kind isn't worth a lib/format extension yet).
420
- case 'mcpServer/startupStatus/updated': {
421
- if (params.status !== 'failed') return
422
- const name = typeof params.name === 'string' ? params.name : 'mcp'
423
- emitTurnEvent(rec, {
424
- kind: 'notice',
425
- notice: {
426
- id: `codex:${rec.sessionId}:mcp:${name}`,
427
- kind: 'hook',
428
- at: new Date().toISOString(),
429
- hookId: `mcp:${name}`,
430
- hookName: `MCP ${name}`,
431
- event: 'mcpServerStartup',
432
- status: 'response',
433
- outcome: 'error',
434
- ...(typeof params.error === 'string' ? { output: params.error } : {})
435
- }
436
- })
437
- return
438
- }
439
736
  }
440
737
  }
441
738
 
@@ -488,16 +785,27 @@ function createRecord(input: {
488
785
  sessionTitleSource?: string
489
786
  }): SessionRecord {
490
787
  const rec: SessionRecord = {
788
+ client: input.client,
789
+ lastTouched: Date.now(),
491
790
  workspaceId: input.workspaceId,
492
791
  workspacePath: input.workspacePath,
493
792
  sessionId: input.sessionId,
494
793
  view: emptyViewState(),
495
794
  activeTurnId: null,
496
795
  processing: false,
796
+ waiting: false,
797
+ activity: 'idle',
497
798
  stream: false,
498
799
  previews: new Map(),
499
800
  children: new Map(),
500
801
  lastUsage: null,
802
+ usageTurnId: null,
803
+ completedTurns: new Set(),
804
+ bufferedNotifications: null,
805
+ previewTimer: null,
806
+ dirtyPreviews: new Set(),
807
+ commandOutput: new Map(),
808
+ commandOutputTimer: null,
501
809
  refreshSessionsOnTurnComplete: input.refreshSessionsOnTurnComplete === true,
502
810
  sessionTitleSource: input.sessionTitleSource,
503
811
  sessionTitleAbort: null
@@ -517,100 +825,124 @@ function seedFromThread(
517
825
  ) {
518
826
  let view = emptyViewState()
519
827
  for (const ev of codexThreadToEvents(thread, subagents)) view = applyEvent(view, ev)
828
+ for (const notice of rec.view.notices) view = applyEvent(view, { kind: 'notice', notice })
520
829
  rec.view = view
521
830
  }
522
831
 
523
- async function resumeSession(input: {
524
- workspaceId: string
525
- workspacePath: string
526
- sessionId: string
527
- }): Promise<SessionRecord> {
528
- const existing = sessions.get(liveKey(input.workspaceId, input.sessionId))
529
- if (existing) return existing
530
- const client = await getCodexClient(input.workspacePath)
531
- const resumed = await client.rpc<{ thread: CodexThread }>('thread/resume', {
532
- threadId: input.sessionId,
533
- ...CODEX_THREAD_ACCESS
534
- })
535
- const rec = createRecord({ ...input, sessionId: resumed.thread.id, client })
536
- // Rebuild child-agent transcripts from their own threads and register them
537
- // as live children, so a mid-run resume keeps routing child frames into
538
- // the same records the replay attached.
539
- const subagents = await readSubagentRecords(client, resumed.thread)
540
- for (const [childId, sub] of subagents) rec.children.set(childId, sub)
541
- seedFromThread(rec, resumed.thread, subagents)
542
- return rec
543
- }
544
-
545
- // Turn a typed text + resolved uploads into Codex input items and the display
546
- // parts for the user's bubble. Images ride inline as data URLs (a documented
547
- // Codex input mode); other files are materialized to a temp path and
548
- // referenced in an attachment note the agent can read.
549
- async function buildUserInput(
550
- text: string,
551
- uploads: StoredUpload[]
552
- ): Promise<{ input: CodexUserInputItem[]; parts: Part[] }> {
553
- const parts: Part[] = []
554
- for (const u of uploads) {
555
- const part = uploadToDisplayPart(u)
556
- if (part) parts.push(part)
557
- }
558
- if (text) parts.push({ type: 'text', text })
832
+ type ResumeInput = { workspaceId: string; workspacePath: string; sessionId: string }
559
833
 
560
- const input: CodexUserInputItem[] = []
561
- for (const u of uploads) {
562
- if (u.kind === 'image' && u.data) {
563
- input.push({ type: 'image', url: `data:${u.mediaType};base64,${u.data.toString('base64')}` })
834
+ async function resumeSession(input: ResumeInput): Promise<SessionRecord> {
835
+ const key = liveKey(input.workspaceId, input.sessionId)
836
+ const pending = resumes.get(key)
837
+ if (pending) return pending
838
+ const existing = sessions.get(key)
839
+ if (existing) return existing
840
+ const loading = (async () => {
841
+ const client = await getCodexClient(input.workspacePath)
842
+ // Subscribe before resuming. Live frames may arrive before the RPC reply,
843
+ // or while child transcripts are loading; replay them after the snapshot.
844
+ const rec = createRecord({ ...input, client })
845
+ rec.bufferedNotifications = []
846
+ try {
847
+ const resumed = await client.rpc<{ thread: CodexThread; model?: string }>('thread/resume', {
848
+ threadId: input.sessionId,
849
+ ...CODEX_THREAD_ACCESS
850
+ })
851
+ const subagents = await readSubagentRecords(client, resumed.thread)
852
+ rec.model = resumed.model
853
+ if (!client.isAlive()) throw new Error('Codex disconnected while resuming this chat')
854
+ for (const [childId, sub] of subagents) rec.children.set(childId, sub)
855
+ seedFromThread(rec, resumed.thread, subagents)
856
+ const active = resumed.thread.turns?.findLast(turn => turn.status === 'inProgress')
857
+ rec.waiting = waitingOnInput(resumed.thread.status)
858
+ setProcessing(
859
+ rec,
860
+ Boolean(active) || resumed.thread.status?.type === 'active',
861
+ active?.id ?? null
862
+ )
863
+ const buffered = rec.bufferedNotifications
864
+ rec.bufferedNotifications = null
865
+ for (const [method, params] of buffered) handleNotification(rec, method, params)
866
+ if (sessions.get(key) !== rec) throw new Error('Codex closed this chat while resuming it')
867
+ return rec
868
+ } catch (error) {
869
+ clearPreviews(rec)
870
+ clearCommandOutput(rec)
871
+ rec.unsubscribe?.()
872
+ if (sessions.get(key) === rec) sessions.delete(key)
873
+ throw error
564
874
  }
875
+ })()
876
+ resumes.set(key, loading)
877
+ try {
878
+ return await loading
879
+ } finally {
880
+ if (resumes.get(key) === loading) resumes.delete(key)
565
881
  }
566
- const files: { filename: string; path: string }[] = []
567
- for (const u of uploads) {
568
- if (u.kind !== 'file') continue
569
- const p = await materializeToPath(u)
570
- if (p) files.push({ filename: u.filename, path: p })
571
- }
572
- const agentText = appendAttachmentNote(text, files)
573
- if (agentText) input.push({ type: 'text', text: agentText })
574
- return { input, parts }
575
882
  }
576
883
 
577
- export async function sendCodexMessage(input: {
884
+ function buildUserInput(message: PreparedAttachmentMessage): CodexUserInputItem[] {
885
+ const images = message.attachments.filter(
886
+ attachment => attachment.type === 'image' && 'data' in attachment
887
+ )
888
+ const input: CodexUserInputItem[] = images.map(image => ({
889
+ type: 'image',
890
+ url: `data:${image.mediaType};base64,${image.data.toString('base64')}`
891
+ }))
892
+ if (message.text) input.push({ type: 'text', text: message.text })
893
+ return input
894
+ }
895
+
896
+ type CodexSendInput = {
578
897
  workspaceId: string
579
898
  workspacePath: string
580
899
  sessionId: string
581
900
  isNew: boolean
582
901
  content: string
583
- attachments?: string[]
902
+ attachments?: MessageAttachment[]
584
903
  optimisticId?: string
585
904
  model?: string
586
905
  effort?: string
587
906
  fastMode?: boolean
588
907
  stream?: boolean
589
- // Structured moi context (lib/moi-context.ts), rendered here. Servers
590
- // >= 0.135 take it via `additionalContext` (never enters userMessage
591
- // items); older ones get it appended to the text item, stripped from
592
- // echoes by the adapter.
908
+ // Rendered through native additionalContext or the legacy text envelope.
593
909
  context?: MoiContext
594
- }): Promise<void> {
595
- const uploads = input.attachments?.length
596
- ? resolveUploads(input.workspaceId, input.attachments)
597
- : []
598
- if (!input.content && uploads.length === 0) return
910
+ }
911
+
912
+ export function sendCodexMessage(input: CodexSendInput): Promise<void> {
913
+ const lane = sendLane(input.workspaceId, input.sessionId)
914
+ const generation = lane.generation
915
+ const sent = lane.tail.then(async () => {
916
+ if (lane.generation !== generation) return
917
+ await sendMessage(input, lane, generation)
918
+ })
919
+ // Serialise acceptance, not entire model turns. A second send can steer as
920
+ // soon as the first start is acknowledged, and failures never poison a lane.
921
+ lane.tail = sent.catch(() => {})
922
+ return sent
923
+ }
924
+
925
+ async function sendMessage(
926
+ input: CodexSendInput,
927
+ lane: SendLane,
928
+ generation: number
929
+ ): Promise<void> {
930
+ const prepared = prepareAttachmentMessage(input.workspaceId, input.content, input.attachments)
931
+ if (!prepared.text) return
599
932
  const sessionTitleSource = input.isNew
600
- ? buildSessionTitleSource(
601
- input.content,
602
- uploads.map(upload => upload.filename)
603
- )
933
+ ? buildSessionTitleSource(input.content, prepared.attachments.map(attachmentLabel))
604
934
  : undefined
605
- const { input: userInput, parts } = await buildUserInput(input.content, uploads)
606
- if (userInput.length === 0) return
935
+ const userInput = buildUserInput(prepared)
936
+ const { parts } = prepared
607
937
  const serviceTier = codexServiceTierForFastMode(input.fastMode)
608
938
 
609
939
  let rec: SessionRecord
610
940
  try {
611
- if (input.isNew) {
941
+ const existing = sessions.get(liveKey(input.workspaceId, input.sessionId))
942
+ if (existing && !existing.bufferedNotifications) rec = existing
943
+ else if (input.isNew && !aliases.has(recKey(input.workspaceId, input.sessionId))) {
612
944
  const client = await getCodexClient(input.workspacePath)
613
- const started = await client.rpc<{ thread: CodexThread }>('thread/start', {
945
+ const started = await client.rpc<{ thread: CodexThread; model?: string }>('thread/start', {
614
946
  cwd: input.workspacePath,
615
947
  ...CODEX_THREAD_ACCESS,
616
948
  ...(input.model ? { model: input.model } : {}),
@@ -619,6 +951,7 @@ export async function sendCodexMessage(input: {
619
951
  const realId = started.thread.id
620
952
  if (realId !== input.sessionId) {
621
953
  aliases.set(recKey(input.workspaceId, input.sessionId), realId)
954
+ sendLanes.set(recKey(input.workspaceId, realId), lane)
622
955
  await renameSessionConfig(input.workspacePath, input.sessionId, realId)
623
956
  await renameSelectedSession(input.workspacePath, input.sessionId, realId)
624
957
  // Builder tabs follow the same temporary-to-real session rename.
@@ -642,6 +975,7 @@ export async function sendCodexMessage(input: {
642
975
  refreshSessionsOnTurnComplete: true,
643
976
  sessionTitleSource
644
977
  })
978
+ rec.model = started.model ?? input.model
645
979
  if (
646
980
  (input.model || input.effort || input.fastMode !== undefined) &&
647
981
  !(await hasSessionConfig(input.workspacePath, realId))
@@ -653,7 +987,10 @@ export async function sendCodexMessage(input: {
653
987
  })
654
988
  }
655
989
  } else {
656
- rec = await resumeSession(input)
990
+ rec = await resumeSession({
991
+ ...input,
992
+ sessionId: aliases.get(recKey(input.workspaceId, input.sessionId)) ?? input.sessionId
993
+ })
657
994
  }
658
995
  } catch (err) {
659
996
  // No session record exists to run setProcessing through — clear the
@@ -668,7 +1005,34 @@ export async function sendCodexMessage(input: {
668
1005
  return
669
1006
  }
670
1007
 
1008
+ if (lane.generation !== generation) return
1009
+ rec.lastTouched = Date.now()
671
1010
  rec.stream = input.stream === true
1011
+ if (!rec.stream) clearPreviews(rec)
1012
+
1013
+ if (userInput.some(item => item.type === 'image')) {
1014
+ try {
1015
+ // Steering keeps the running turn's model, regardless of picker changes.
1016
+ const models = await getCodexModelCatalog(input.workspacePath)
1017
+ const modelId = rec.activeTurnId ? rec.model : (input.model ?? rec.model)
1018
+ const model = models.find(model => model.model === modelId || model.id === modelId)
1019
+ if (model?.inputModalities && !model.inputModalities.includes('image')) {
1020
+ throw new Error(
1021
+ `${model.displayName} does not accept images. Choose a model that supports images.`
1022
+ )
1023
+ }
1024
+ } catch (error) {
1025
+ broadcast(rec.workspaceId, {
1026
+ kind: 'error',
1027
+ sessionId: rec.sessionId,
1028
+ content: error instanceof Error ? error.message : 'Could not check image support',
1029
+ terminal: !rec.activeTurnId
1030
+ })
1031
+ if (!rec.activeTurnId) setProcessing(rec, false, null)
1032
+ return
1033
+ }
1034
+ if (lane.generation !== generation) return
1035
+ }
672
1036
 
673
1037
  // Broadcast the user's bubble immediately so every connected tab shows it;
674
1038
  // the Codex echo (`userMessage` item) reuses this id via `clientId` and
@@ -687,11 +1051,9 @@ export async function sendCodexMessage(input: {
687
1051
 
688
1052
  setProcessing(rec, true, rec.activeTurnId)
689
1053
  try {
690
- const client = await getCodexClient(input.workspacePath)
691
- // Native context channel: diffed per key server-side (unchanged values
692
- // inject nothing) and never echoed back in userMessage items. The entry
693
- // key becomes the tag, so ship the unwrapped body. Older servers silently
694
- // drop the field, so append to the text item there instead.
1054
+ const client = rec.client
1055
+ // Native context keys become tags, so pass unwrapped bodies. The fallback
1056
+ // envelope is stripped from user echoes by adapter.ts.
695
1057
  const additionalContext = client.supportsAdditionalContext
696
1058
  ? {
697
1059
  ...CODEX_LOCAL_CONTROL_CONTEXT,
@@ -715,20 +1077,13 @@ export async function sendCodexMessage(input: {
715
1077
  input: userInput,
716
1078
  ...CODEX_TURN_ACCESS,
717
1079
  ...(additionalContext ? { additionalContext } : {}),
718
- // Without an explicit summary mode Codex still reasons but emits the
719
- // reasoning item with EMPTY summary/content (verified on the wire —
720
- // scripts/codex-probe.ts), so no thinking ever reaches the UI. 'detailed'
721
- // (vs 'auto') makes the summaries longer and stream in more frequent
722
- // item/reasoning/summaryTextDelta bursts while the model is still
723
- // thinking — 'auto' tends to emit one short blob near the end.
1080
+ // Request visible reasoning summaries instead of relying on CLI defaults.
724
1081
  summary: 'detailed',
725
1082
  ...(input.model ? { model: input.model } : {}),
726
1083
  ...(input.effort ? { effort: input.effort } : {}),
727
1084
  ...(serviceTier !== undefined ? { serviceTier } : {})
728
1085
  }
729
1086
  if (rec.activeTurnId) {
730
- // A turn is running — steer the new input into it. If the turn ended
731
- // in the race window, fall back to starting a fresh turn.
732
1087
  try {
733
1088
  await client.rpc('turn/steer', {
734
1089
  threadId: rec.sessionId,
@@ -737,45 +1092,76 @@ export async function sendCodexMessage(input: {
737
1092
  ...(additionalContext ? { additionalContext } : {}),
738
1093
  expectedTurnId: rec.activeTurnId
739
1094
  })
740
- } catch {
1095
+ } catch (error) {
1096
+ // Only a definitive no-active-turn rejection makes a fresh start safe.
1097
+ // Timeouts, auth failures and turn-id mismatches may have accepted the
1098
+ // input already, or refer to another active turn.
1099
+ if (
1100
+ !(error instanceof CodexRpcError) ||
1101
+ !/no active turn|not running|no turn in progress/i.test(error.message)
1102
+ )
1103
+ throw error
1104
+ if (lane.generation !== generation) return
1105
+ setProcessing(rec, true, null)
1106
+ rec.model = input.model ?? rec.model
741
1107
  const res = await client.rpc<{ turn: CodexTurn }>('turn/start', turnParams)
742
- setProcessing(rec, true, res.turn.id)
1108
+ acceptStartedTurn(rec, res.turn)
743
1109
  }
744
1110
  } else {
1111
+ rec.model = input.model ?? rec.model
745
1112
  const res = await client.rpc<{ turn: CodexTurn }>('turn/start', turnParams)
746
- setProcessing(rec, true, res.turn.id)
1113
+ acceptStartedTurn(rec, res.turn)
747
1114
  }
748
- if (input.isNew) startCodexSessionTitleJob(rec, client)
1115
+ if (lane.generation !== generation && rec.activeTurnId) {
1116
+ await interruptCodexTurn(client, rec.sessionId, rec.activeTurnId)
1117
+ }
1118
+ if (input.isNew && lane.generation === generation) startCodexSessionTitleJob(rec, client)
749
1119
  debug(`codex send ws=${rec.workspaceId} thread=${rec.sessionId} turn=${rec.activeTurnId}`)
750
1120
  } catch (err) {
751
- setProcessing(rec, false, null)
1121
+ // A failed steer does not terminate the turn it was trying to modify.
1122
+ // Likewise, a timed-out start can still produce authoritative lifecycle
1123
+ // notifications later. Keep a known active turn stoppable.
1124
+ if (!rec.activeTurnId) setProcessing(rec, false, null)
752
1125
  broadcast(rec.workspaceId, {
753
1126
  kind: 'error',
754
1127
  sessionId: rec.sessionId,
755
- content: err instanceof Error ? err.message : 'send failed'
1128
+ content: err instanceof Error ? err.message : 'send failed',
1129
+ terminal: !rec.activeTurnId
756
1130
  })
757
1131
  refreshAvailability(rec.workspaceId, rec.workspacePath)
758
1132
  }
759
1133
  }
760
1134
 
1135
+ function acceptStartedTurn(rec: SessionRecord, turn: CodexTurn) {
1136
+ if (rec.completedTurns.has(turn.id)) return
1137
+ if (turn.status === 'inProgress') setProcessing(rec, true, turn.id)
1138
+ else handleNotification(rec, 'turn/completed', { threadId: rec.sessionId, turn })
1139
+ }
1140
+
761
1141
  export async function interruptCodexRun(input: {
762
1142
  workspaceId: string
763
1143
  sessionId: string
764
1144
  }): Promise<void> {
1145
+ const lane = sendLane(input.workspaceId, input.sessionId)
1146
+ lane.generation++ // cancels queued sends, including a start still initializing
765
1147
  const rec = sessions.get(liveKey(input.workspaceId, input.sessionId))
766
- if (!rec) return
1148
+ if (!rec?.activeTurnId) {
1149
+ broadcast(input.workspaceId, { kind: 'stopped', sessionId: rec?.sessionId ?? input.sessionId })
1150
+ if (rec) setProcessing(rec, false, null)
1151
+ else
1152
+ broadcast(input.workspaceId, { type: 'status', sessionId: input.sessionId, activity: 'idle' })
1153
+ return
1154
+ }
767
1155
  try {
768
- if (rec.activeTurnId) {
769
- const client = await getCodexClient(rec.workspacePath)
770
- await interruptCodexTurn(client, rec.sessionId, rec.activeTurnId)
771
- }
772
- broadcast(rec.workspaceId, { kind: 'stopped', sessionId: rec.sessionId })
773
- setProcessing(rec, false, null)
1156
+ await interruptCodexTurn(rec.client, rec.sessionId, rec.activeTurnId)
1157
+ // turn/completed is authoritative. In particular, don't emit a second
1158
+ // stopped frame or claim idle while the command is still shutting down.
774
1159
  } catch (err) {
775
1160
  broadcast(rec.workspaceId, {
776
1161
  kind: 'error',
777
1162
  sessionId: rec.sessionId,
778
- content: err instanceof Error ? err.message : 'interrupt failed'
1163
+ content: err instanceof Error ? err.message : 'Interrupt failed',
1164
+ terminal: !rec.activeTurnId
779
1165
  })
780
1166
  throw err
781
1167
  }
@@ -788,11 +1174,11 @@ export function viewAsEvents(rec: SessionRecord): StreamEvent[] {
788
1174
  return evs
789
1175
  }
790
1176
 
791
- // Read-side hook for the REST events endpoint (mirrors the OpenClaw path):
792
- // return the live view when we hold one so REST + WS stay in agreement.
1177
+ // Serve the live display copy so REST and WebSocket events stay consistent.
793
1178
  export function getLiveCodexEvents(workspaceId: string, sessionId: string): StreamEvent[] | null {
794
1179
  const rec = sessions.get(liveKey(workspaceId, sessionId))
795
- return rec ? viewAsEvents(rec) : null
1180
+ if (rec) rec.lastTouched = Date.now()
1181
+ return rec && !rec.bufferedNotifications ? viewAsEvents(rec) : null
796
1182
  }
797
1183
 
798
1184
  // Cold-load: resume the thread (also subscribing it on our connection) and