moi-computer 0.13.1-next.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (666) hide show
  1. package/README.md +1 -1
  2. package/bin/moi.mjs +10 -6
  3. package/dist/{chunk-k32585ne.js → chunk-828s864r.js} +61 -61
  4. package/dist/chunk-9ffaaaw3.css +1 -0
  5. package/dist/chunk-gh11h6dc.js +2 -0
  6. package/dist/chunk-hhgsmxsq.js +1 -0
  7. package/dist/chunk-ht9zmff2.js +5 -0
  8. package/dist/{chunk-0t8m1ehd.js → chunk-jqa4c92z.js} +2 -2
  9. package/dist/{chunk-qtkv7hp8.js → chunk-kkhswjz8.js} +2 -2
  10. package/dist/{chunk-wjbejzek.js → chunk-nqh3kx2x.js} +1 -1
  11. package/dist/chunk-rb2vsqvb.js +1 -0
  12. package/dist/{chunk-c8g5x288.js → chunk-t22yw8s6.js} +1 -1
  13. package/dist/chunk-yv6n9e3z.js +72 -0
  14. package/dist/dot-2bdkpg3k.png +0 -0
  15. package/dist/duet-3ab8xyzd.png +0 -0
  16. package/dist/grok-bot-yv07qj9f.png +0 -0
  17. package/dist/index.html +1 -1
  18. package/dist/instinct-ypmq6t0w.png +0 -0
  19. package/dist/muse-qr7zwsvf.png +0 -0
  20. package/package.json +39 -40
  21. package/runtime/applets/chunk-bzxakh65.js +2 -0
  22. package/runtime/applets/chunk-qhjskz2m.js +2 -0
  23. package/runtime/applets/collab.js +1 -0
  24. package/runtime/applets/moi.js +1 -0
  25. package/runtime/applets/rpc.js +2 -0
  26. package/runtime/assets/shadcn.css +629 -0
  27. package/runtime/assets/tw-animate.css +1 -0
  28. package/runtime/build-worker-entry.js +2 -0
  29. package/runtime/chunk-00rk365r.js +83 -0
  30. package/runtime/chunk-4wj1jzhr.js +3 -0
  31. package/runtime/chunk-5egvk1rz.js +3 -0
  32. package/runtime/chunk-7c0zbz74.js +3 -0
  33. package/runtime/chunk-8fvgvm56.js +2 -0
  34. package/runtime/chunk-c3qyet60.js +128 -0
  35. package/runtime/chunk-ewc55jga.js +32623 -0
  36. package/runtime/chunk-gbkjshyt.js +26 -0
  37. package/runtime/chunk-ggphq7nk.js +66 -0
  38. package/runtime/chunk-h2bwhk81.js +3 -0
  39. package/runtime/chunk-hjzfk1cr.js +3 -0
  40. package/runtime/chunk-j0nd7kw0.js +52 -0
  41. package/runtime/chunk-jb63ns1z.js +2 -0
  42. package/runtime/chunk-k049dtaq.js +3 -0
  43. package/runtime/chunk-kjp60rqs.js +3 -0
  44. package/runtime/chunk-q06m17nb.js +3 -0
  45. package/runtime/chunk-r5s8rm8n.js +3 -0
  46. package/runtime/chunk-sdyqhxe1.js +10 -0
  47. package/runtime/chunk-w1fx9tsc.js +3 -0
  48. package/runtime/chunk-w6ksnv8y.js +2 -0
  49. package/runtime/chunk-wvarpvem.js +78 -0
  50. package/runtime/chunk-zm7k0v1c.js +3 -0
  51. package/runtime/chunk-zwvtkb81.js +139 -0
  52. package/runtime/cli.js +246 -0
  53. package/runtime/functions-worker.js +2 -0
  54. package/runtime/gateway-client.js +2 -0
  55. package/runtime/third-party-notices.txt +6830 -0
  56. package/runtime/worker.js +2 -0
  57. package/runtime/xdg-open +1267 -0
  58. package/bunfig.toml +0 -7
  59. package/client/AGENTS.md +0 -40
  60. package/client/api/app-config.ts +0 -58
  61. package/client/api/http.ts +0 -44
  62. package/client/api/query-client.ts +0 -5
  63. package/client/api/query-options.ts +0 -6
  64. package/client/api/workspace-keys.ts +0 -18
  65. package/client/app/app-provider.tsx +0 -39
  66. package/client/app/app-router.tsx +0 -57
  67. package/client/app/routes/home-route.tsx +0 -27
  68. package/client/app/routes/onboarding-route.tsx +0 -11
  69. package/client/app/routes/settings-route.tsx +0 -10
  70. package/client/app/routes/workspace-registration.tsx +0 -68
  71. package/client/app/routes/workspace-route.tsx +0 -127
  72. package/client/app/shell/sidebar-layout.tsx +0 -247
  73. package/client/assets/claude.svg +0 -3
  74. package/client/assets/favicon.png +0 -0
  75. package/client/assets/floppy-disk.webp +0 -0
  76. package/client/assets/hermes.png +0 -0
  77. package/client/assets/mcp/.gitkeep +0 -0
  78. package/client/assets/mcp/airtable.png +0 -0
  79. package/client/assets/mcp/apollo.png +0 -0
  80. package/client/assets/mcp/asana.png +0 -0
  81. package/client/assets/mcp/atlassian.png +0 -0
  82. package/client/assets/mcp/box.png +0 -0
  83. package/client/assets/mcp/chrome.svg +0 -33
  84. package/client/assets/mcp/clickup.png +0 -0
  85. package/client/assets/mcp/cloudflare.png +0 -0
  86. package/client/assets/mcp/context7.png +0 -0
  87. package/client/assets/mcp/datadog.png +0 -0
  88. package/client/assets/mcp/discord.png +0 -0
  89. package/client/assets/mcp/dropbox.png +0 -0
  90. package/client/assets/mcp/elevenlabs.png +0 -0
  91. package/client/assets/mcp/exa.png +0 -0
  92. package/client/assets/mcp/figma.png +0 -0
  93. package/client/assets/mcp/firecrawl.png +0 -0
  94. package/client/assets/mcp/github.png +0 -0
  95. package/client/assets/mcp/gitlab.png +0 -0
  96. package/client/assets/mcp/gmail.png +0 -0
  97. package/client/assets/mcp/googlecalendar.png +0 -0
  98. package/client/assets/mcp/googledrive.png +0 -0
  99. package/client/assets/mcp/grafana.png +0 -0
  100. package/client/assets/mcp/granola.png +0 -0
  101. package/client/assets/mcp/hubspot.png +0 -0
  102. package/client/assets/mcp/huggingface.png +0 -0
  103. package/client/assets/mcp/intercom.png +0 -0
  104. package/client/assets/mcp/linear.png +0 -0
  105. package/client/assets/mcp/monday.png +0 -0
  106. package/client/assets/mcp/mongodb.png +0 -0
  107. package/client/assets/mcp/neon.png +0 -0
  108. package/client/assets/mcp/notion.png +0 -0
  109. package/client/assets/mcp/paper.png +0 -0
  110. package/client/assets/mcp/paypal.png +0 -0
  111. package/client/assets/mcp/perplexity.png +0 -0
  112. package/client/assets/mcp/postgresql.png +0 -0
  113. package/client/assets/mcp/posthog.png +0 -0
  114. package/client/assets/mcp/puppeteer.png +0 -0
  115. package/client/assets/mcp/railway.png +0 -0
  116. package/client/assets/mcp/redis.png +0 -0
  117. package/client/assets/mcp/salesforce.png +0 -0
  118. package/client/assets/mcp/sentry.png +0 -0
  119. package/client/assets/mcp/shopify.png +0 -0
  120. package/client/assets/mcp/slack.png +0 -0
  121. package/client/assets/mcp/snowflake.png +0 -0
  122. package/client/assets/mcp/stripe.png +0 -0
  123. package/client/assets/mcp/supabase.png +0 -0
  124. package/client/assets/mcp/telegram.png +0 -0
  125. package/client/assets/mcp/twilio.png +0 -0
  126. package/client/assets/mcp/vercel.png +0 -0
  127. package/client/assets/mcp/zapier.png +0 -0
  128. package/client/assets/moi-logo.svg +0 -11
  129. package/client/assets/openai.svg +0 -1
  130. package/client/assets/openclaw.svg +0 -22
  131. package/client/assets.d.ts +0 -14
  132. package/client/components/shared/agent-blobatar.tsx +0 -93
  133. package/client/components/shared/bottom-panel.tsx +0 -65
  134. package/client/components/shared/composer.tsx +0 -125
  135. package/client/components/shared/led-logo.tsx +0 -181
  136. package/client/components/shared/panel-header.tsx +0 -16
  137. package/client/components/shared/reorderable-list.tsx +0 -204
  138. package/client/components/shared/screen-shell.tsx +0 -23
  139. package/client/components/shared/ultrafast-icon.tsx +0 -61
  140. package/client/components/shared/workspace-icon.tsx +0 -83
  141. package/client/components/ui/alert-dialog.tsx +0 -1
  142. package/client/components/ui/button.tsx +0 -1
  143. package/client/components/ui/checkbox.tsx +0 -1
  144. package/client/components/ui/collapsible.tsx +0 -1
  145. package/client/components/ui/dialog.tsx +0 -1
  146. package/client/components/ui/dropdown-menu.tsx +0 -1
  147. package/client/components/ui/hover-card.tsx +0 -1
  148. package/client/components/ui/inline-input.tsx +0 -84
  149. package/client/components/ui/input.tsx +0 -1
  150. package/client/components/ui/popover.tsx +0 -1
  151. package/client/components/ui/resizable.tsx +0 -1
  152. package/client/components/ui/skeleton.tsx +0 -1
  153. package/client/components/ui/slider.tsx +0 -1
  154. package/client/components/ui/spinner.tsx +0 -1
  155. package/client/components/ui/switch.tsx +0 -1
  156. package/client/components/ui/tabs.tsx +0 -1
  157. package/client/components/ui/textarea.tsx +0 -1
  158. package/client/components/ui/toast.tsx +0 -220
  159. package/client/components/ui/tooltip.tsx +0 -1
  160. package/client/dev/index.html +0 -43
  161. package/client/dev/index.ts +0 -15
  162. package/client/externalize-react.ts +0 -41
  163. package/client/features/account/account-menu.tsx +0 -96
  164. package/client/features/account/account-provider.tsx +0 -93
  165. package/client/features/account/account-test-utils.tsx +0 -310
  166. package/client/features/account/api.ts +0 -67
  167. package/client/features/account/profile-actions.ts +0 -29
  168. package/client/features/app-settings/api.ts +0 -33
  169. package/client/features/app-settings/avatar-upload.tsx +0 -62
  170. package/client/features/app-settings/general-settings.tsx +0 -39
  171. package/client/features/app-settings/profile-settings.tsx +0 -105
  172. package/client/features/app-settings/settings-page.tsx +0 -45
  173. package/client/features/app-settings/settings-section.tsx +0 -26
  174. package/client/features/applets/api.ts +0 -38
  175. package/client/features/applets/applet-cache.ts +0 -95
  176. package/client/features/applets/applet-container.tsx +0 -33
  177. package/client/features/applets/applet-log.ts +0 -81
  178. package/client/features/applets/applet-runtime.ts +0 -325
  179. package/client/features/applets/applet-styles.ts +0 -81
  180. package/client/features/applets/applet-thumbnail.ts +0 -294
  181. package/client/features/applets/use-applet.ts +0 -210
  182. package/client/features/applets/widget-error-boundary.tsx +0 -62
  183. package/client/features/applets/widget-shell.tsx +0 -56
  184. package/client/features/chat/applet-chat-intents.ts +0 -173
  185. package/client/features/chat/chat-panel.tsx +0 -326
  186. package/client/features/chat/chat-popup.tsx +0 -175
  187. package/client/features/chat/chat-send.ts +0 -259
  188. package/client/features/chat/chat-store.ts +0 -328
  189. package/client/features/chat/composer/attachments/attachment-chip.tsx +0 -99
  190. package/client/features/chat/composer/attachments/draft-attachments.ts +0 -185
  191. package/client/features/chat/composer/attachments/drawing-attachment-chip.tsx +0 -37
  192. package/client/features/chat/composer/attachments/file-attachment-chip.tsx +0 -22
  193. package/client/features/chat/composer/attachments/text-attachment-chip.tsx +0 -11
  194. package/client/features/chat/composer/attachments/types.ts +0 -25
  195. package/client/features/chat/composer/attachments/uploads.ts +0 -26
  196. package/client/features/chat/composer/banners/composer-banner.tsx +0 -16
  197. package/client/features/chat/composer/banners/error-banner.tsx +0 -36
  198. package/client/features/chat/composer/banners/skill-update-banner.tsx +0 -93
  199. package/client/features/chat/composer/chat-composer.tsx +0 -290
  200. package/client/features/chat/composer/model-order.ts +0 -110
  201. package/client/features/chat/composer/model-picker.tsx +0 -408
  202. package/client/features/chat/composer/use-workspace-composer-state.tsx +0 -69
  203. package/client/features/chat/composer/use-workspace-skill-updates.ts +0 -160
  204. package/client/features/chat/connection/chat-connection.ts +0 -64
  205. package/client/features/chat/connection/chat-frames.ts +0 -153
  206. package/client/features/chat/messages/chat-empty-state.tsx +0 -294
  207. package/client/features/chat/messages/chat-prompt-bubbles.tsx +0 -72
  208. package/client/features/chat/messages/fork-history.ts +0 -14
  209. package/client/features/chat/messages/group-turns.ts +0 -74
  210. package/client/features/chat/messages/interleave-notices.ts +0 -80
  211. package/client/features/chat/messages/markdown-content.tsx +0 -89
  212. package/client/features/chat/messages/preview-turn.ts +0 -37
  213. package/client/features/chat/messages/shimmer-text.tsx +0 -20
  214. package/client/features/chat/messages/tool-group/code-block.tsx +0 -41
  215. package/client/features/chat/messages/tool-group/collapse.tsx +0 -28
  216. package/client/features/chat/messages/tool-group/detect.ts +0 -93
  217. package/client/features/chat/messages/tool-group/fixtures.ts +0 -309
  218. package/client/features/chat/messages/tool-group/format/claude.ts +0 -49
  219. package/client/features/chat/messages/tool-group/format/codex.ts +0 -130
  220. package/client/features/chat/messages/tool-group/format/hermes.ts +0 -69
  221. package/client/features/chat/messages/tool-group/format/index.ts +0 -34
  222. package/client/features/chat/messages/tool-group/format/mcp.ts +0 -68
  223. package/client/features/chat/messages/tool-group/format/openclaw.ts +0 -120
  224. package/client/features/chat/messages/tool-group/format/shared.ts +0 -49
  225. package/client/features/chat/messages/tool-group/format/shell.ts +0 -162
  226. package/client/features/chat/messages/tool-group/index.ts +0 -9
  227. package/client/features/chat/messages/tool-group/read-image-preview.tsx +0 -46
  228. package/client/features/chat/messages/tool-group/subagent-card.tsx +0 -138
  229. package/client/features/chat/messages/tool-group/timeline-row.tsx +0 -159
  230. package/client/features/chat/messages/tool-group/tool-call-group.tsx +0 -279
  231. package/client/features/chat/messages/tool-group/tool-output.tsx +0 -125
  232. package/client/features/chat/messages/turn-view.tsx +0 -270
  233. package/client/features/chat/messages/use-stick-to-bottom.ts +0 -96
  234. package/client/features/chat/messages/user-message-bubble.tsx +0 -63
  235. package/client/features/chat/sessions/api.ts +0 -193
  236. package/client/features/chat/sessions/chat-selector.tsx +0 -399
  237. package/client/features/chat/sessions/session-view.ts +0 -53
  238. package/client/features/chat/sessions/use-selected-session.ts +0 -171
  239. package/client/features/chat/use-chat.ts +0 -229
  240. package/client/features/collab/applet-api.ts +0 -35
  241. package/client/features/collab/components/cursors.tsx +0 -241
  242. package/client/features/collab/components/presence-avatars.tsx +0 -74
  243. package/client/features/collab/components/presence-frame.tsx +0 -122
  244. package/client/features/collab/components/presence-group.tsx +0 -31
  245. package/client/features/collab/components/presence-helpers.ts +0 -50
  246. package/client/features/collab/components/user-avatar-group.tsx +0 -35
  247. package/client/features/collab/components/user-avatar.tsx +0 -65
  248. package/client/features/collab/components/user.tsx +0 -69
  249. package/client/features/collab/host-state.ts +0 -160
  250. package/client/features/collab/index.ts +0 -5
  251. package/client/features/collab/local-user.ts +0 -46
  252. package/client/features/collab/members/api.ts +0 -17
  253. package/client/features/collab/members/hooks.ts +0 -97
  254. package/client/features/collab/members/store.ts +0 -148
  255. package/client/features/collab/members/types.ts +0 -55
  256. package/client/features/collab/presence/client.ts +0 -242
  257. package/client/features/collab/presence/hooks.tsx +0 -160
  258. package/client/features/collab/presence/presence-publisher.ts +0 -30
  259. package/client/features/collab/presence/presence-target.ts +0 -8
  260. package/client/features/collab/presence/provider.tsx +0 -74
  261. package/client/features/collab/presence/store.ts +0 -156
  262. package/client/features/collab/presence/users.ts +0 -87
  263. package/client/features/collab/proxy-user.ts +0 -28
  264. package/client/features/collab/sharing/agent-invite.tsx +0 -30
  265. package/client/features/collab/sharing/workspace-members.tsx +0 -269
  266. package/client/features/collab/sharing/workspace-sharing-menu.tsx +0 -179
  267. package/client/features/collab/testing/component-fixtures.tsx +0 -54
  268. package/client/features/collab/testing/fake-engine.ts +0 -120
  269. package/client/features/connectors/api.ts +0 -25
  270. package/client/features/connectors/icon-mcp.tsx +0 -21
  271. package/client/features/connectors/mcp-icons.ts +0 -183
  272. package/client/features/connectors/mcp-server-cards.tsx +0 -105
  273. package/client/features/connectors/read-connectors.ts +0 -35
  274. package/client/features/demo/demo-dialog.tsx +0 -194
  275. package/client/features/dev/blobatar-shapes-page.tsx +0 -344
  276. package/client/features/dev/chat-states-fixtures.ts +0 -755
  277. package/client/features/dev/chat-states-page.tsx +0 -476
  278. package/client/features/dev/collab/collab-page.tsx +0 -24
  279. package/client/features/dev/collab/collab-playground.tsx +0 -614
  280. package/client/features/dev/collab/local-user-settings.tsx +0 -120
  281. package/client/features/dev/collab/playground-room.ts +0 -33
  282. package/client/features/dev/dev-index-page.tsx +0 -83
  283. package/client/features/dev/dev-routes.tsx +0 -43
  284. package/client/features/dev/harness-debug-page.tsx +0 -607
  285. package/client/features/dev/onboarding-preview-page.tsx +0 -76
  286. package/client/features/dev/texture-lab-page.tsx +0 -149
  287. package/client/features/dev/tool-calls-page.tsx +0 -79
  288. package/client/features/dev/ui-components/ui-component-previews.tsx +0 -855
  289. package/client/features/dev/ui-components/ui-components-page.tsx +0 -60
  290. package/client/features/dev/workspace-setup-mocks.ts +0 -103
  291. package/client/features/dev/workspace-setup-page.tsx +0 -11
  292. package/client/features/dev/workspace-setup-preview.tsx +0 -249
  293. package/client/features/drawings/capture-element.ts +0 -57
  294. package/client/features/drawings/drawing-layer.tsx +0 -49
  295. package/client/features/drawings/drawing-toolbar.tsx +0 -95
  296. package/client/features/drawings/use-chat-annotation.ts +0 -228
  297. package/client/features/drawings/use-drawing-layer.ts +0 -756
  298. package/client/features/drawings/use-view-sketch.ts +0 -154
  299. package/client/features/harness/api.ts +0 -69
  300. package/client/features/harness/device-login-steps.tsx +0 -103
  301. package/client/features/harness/harness-login-panel.tsx +0 -232
  302. package/client/features/harness/harness-presentation.ts +0 -15
  303. package/client/features/harness/harness-selector.tsx +0 -119
  304. package/client/features/harness/use-harness-login.ts +0 -77
  305. package/client/features/home/api.ts +0 -135
  306. package/client/features/home/home-logo.tsx +0 -344
  307. package/client/features/home/home-page.tsx +0 -305
  308. package/client/features/home/shared-workspaces.tsx +0 -70
  309. package/client/features/home/workspace-invitations.tsx +0 -101
  310. package/client/features/home/workspace-preview.tsx +0 -213
  311. package/client/features/identity/host-api.ts +0 -35
  312. package/client/features/identity/store.ts +0 -26
  313. package/client/features/identity/types.ts +0 -41
  314. package/client/features/identity/use-identity.ts +0 -6
  315. package/client/features/onboarding/agent-setup-step.tsx +0 -57
  316. package/client/features/onboarding/api.ts +0 -42
  317. package/client/features/onboarding/onboarding-idea-disk.tsx +0 -129
  318. package/client/features/onboarding/onboarding-page.tsx +0 -33
  319. package/client/features/onboarding/onboarding-screen.tsx +0 -20
  320. package/client/features/onboarding/onboarding-status.tsx +0 -24
  321. package/client/features/onboarding/workspace-setup-step.tsx +0 -239
  322. package/client/features/overview/api.ts +0 -28
  323. package/client/features/overview/default/registry.tsx +0 -34
  324. package/client/features/overview/default/views-widget.tsx +0 -246
  325. package/client/features/overview/grid.ts +0 -77
  326. package/client/features/overview/hidden-panel.tsx +0 -111
  327. package/client/features/overview/overview.tsx +0 -299
  328. package/client/features/overview/use-grid-reconcile.ts +0 -94
  329. package/client/features/overview/widget-canvas.tsx +0 -166
  330. package/client/features/overview/widget-frame.tsx +0 -77
  331. package/client/features/overview/workspace-name.tsx +0 -55
  332. package/client/features/scratchpad/scratch-session.ts +0 -71
  333. package/client/features/scratchpad/scratchpad-controls.tsx +0 -516
  334. package/client/features/scratchpad/scratchpad.tsx +0 -360
  335. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +0 -133
  336. package/client/features/update/api.ts +0 -35
  337. package/client/features/update/update-control.tsx +0 -102
  338. package/client/features/views/api.ts +0 -188
  339. package/client/features/views/pending-view-screen.tsx +0 -303
  340. package/client/features/views/use-view-actions.ts +0 -119
  341. package/client/features/views/use-view-drafts.ts +0 -88
  342. package/client/features/views/view-manager.tsx +0 -293
  343. package/client/features/views/view-presentation.ts +0 -12
  344. package/client/features/views/view-residency.ts +0 -77
  345. package/client/features/views/view-submission.ts +0 -56
  346. package/client/features/workspace/add/api.ts +0 -61
  347. package/client/features/workspace/add/create-workspace-dialog.tsx +0 -230
  348. package/client/features/workspace/add/import-workspace-dialog.tsx +0 -81
  349. package/client/features/workspace/add/use-workspace-import.ts +0 -61
  350. package/client/features/workspace/add/workspace-agent-options.ts +0 -53
  351. package/client/features/workspace/add/workspace-agent-selector.tsx +0 -96
  352. package/client/features/workspace/add/workspace-dialog-content.tsx +0 -22
  353. package/client/features/workspace/api.ts +0 -180
  354. package/client/features/workspace/harness-transition.ts +0 -81
  355. package/client/features/workspace/moi-context.ts +0 -129
  356. package/client/features/workspace/remote.ts +0 -34
  357. package/client/features/workspace/settings/api.ts +0 -112
  358. package/client/features/workspace/settings/connectors-settings.tsx +0 -110
  359. package/client/features/workspace/settings/environment-settings.tsx +0 -149
  360. package/client/features/workspace/settings/general-settings.tsx +0 -180
  361. package/client/features/workspace/settings/icon-picker-options.ts +0 -30
  362. package/client/features/workspace/settings/settings-layout.tsx +0 -53
  363. package/client/features/workspace/settings/use-env-vars.ts +0 -20
  364. package/client/features/workspace/settings/workspace-icon-picker.tsx +0 -318
  365. package/client/features/workspace/settings/workspace-settings-dialog.tsx +0 -65
  366. package/client/features/workspace/setup/workspace-login-state.tsx +0 -56
  367. package/client/features/workspace/setup/workspace-recovery-states.tsx +0 -142
  368. package/client/features/workspace/setup/workspace-setup.tsx +0 -98
  369. package/client/features/workspace/setup/workspace-welcome-state.tsx +0 -81
  370. package/client/features/workspace/tab-resolution.ts +0 -32
  371. package/client/features/workspace/theme-panel.tsx +0 -191
  372. package/client/features/workspace/unavailable-page.tsx +0 -21
  373. package/client/features/workspace/use-fits-split-layout.ts +0 -69
  374. package/client/features/workspace/use-workspace-navigation.ts +0 -265
  375. package/client/features/workspace/use-workspace-socket.ts +0 -51
  376. package/client/features/workspace/workspace-content.tsx +0 -597
  377. package/client/features/workspace/workspace-context.tsx +0 -21
  378. package/client/features/workspace/workspace-frame.tsx +0 -64
  379. package/client/features/workspace/workspace-identity.tsx +0 -40
  380. package/client/features/workspace/workspace-layout-context.tsx +0 -156
  381. package/client/features/workspace/workspace-menu.tsx +0 -67
  382. package/client/features/workspace/workspace-pane.tsx +0 -22
  383. package/client/features/workspace/workspace-pending-screen.tsx +0 -26
  384. package/client/features/workspace/workspace-preferences.ts +0 -91
  385. package/client/features/workspace/workspace-presentation.tsx +0 -35
  386. package/client/features/workspace/workspace-screen.tsx +0 -28
  387. package/client/features/workspace/workspace-split-layout.tsx +0 -116
  388. package/client/features/workspace/workspace-state.ts +0 -206
  389. package/client/features/workspace/workspace-tabs.tsx +0 -233
  390. package/client/features/workspace/workspace-test-utils.ts +0 -23
  391. package/client/global.d.ts +0 -5
  392. package/client/index.css +0 -247
  393. package/client/index.html +0 -81
  394. package/client/index.tsx +0 -45
  395. package/client/lib/agent-availability.ts +0 -14
  396. package/client/lib/browser-tab-id.ts +0 -4
  397. package/client/lib/cn.ts +0 -6
  398. package/client/lib/flags.ts +0 -11
  399. package/client/lib/identity-icon-registry.ts +0 -150
  400. package/client/lib/rate-limit.ts +0 -77
  401. package/client/lib/use-latest-ref.ts +0 -11
  402. package/client/lib/user-display-name.ts +0 -6
  403. package/client/lib/ws-url.ts +0 -10
  404. package/client/main.tsx +0 -43
  405. package/client/runtime/app-context.ts +0 -20
  406. package/client/runtime/app-events.ts +0 -75
  407. package/client/runtime/hmr-watchdog.ts +0 -39
  408. package/client/runtime/reconnecting-socket.ts +0 -115
  409. package/client/runtime/use-client-events.ts +0 -69
  410. package/client/runtime/workspace-theme.ts +0 -175
  411. package/client/store/ui.ts +0 -94
  412. package/client/store/workspace-session.ts +0 -30
  413. package/client/structured-clone-shim.ts +0 -14
  414. package/client/tailwind-config.ts +0 -43
  415. package/dist/chunk-851bx8ss.js +0 -72
  416. package/dist/chunk-cty37f3v.js +0 -1
  417. package/dist/chunk-dy6f6h3e.js +0 -5
  418. package/dist/chunk-j6928pwm.js +0 -1
  419. package/dist/chunk-kffcah9w.css +0 -1
  420. package/dist/chunk-rh58dc0y.js +0 -2
  421. package/lib/applet-selector.ts +0 -24
  422. package/lib/attachment-note.ts +0 -66
  423. package/lib/chat-title.ts +0 -11
  424. package/lib/collab/colors.ts +0 -30
  425. package/lib/collab/protocol.ts +0 -84
  426. package/lib/collab/types.ts +0 -52
  427. package/lib/default-widgets.ts +0 -32
  428. package/lib/events.ts +0 -61
  429. package/lib/format.ts +0 -348
  430. package/lib/harness-instructions.ts +0 -30
  431. package/lib/harness-types.ts +0 -13
  432. package/lib/identity-icons.ts +0 -73
  433. package/lib/ids.ts +0 -33
  434. package/lib/message-attachments.ts +0 -40
  435. package/lib/moi-attachments.ts +0 -204
  436. package/lib/moi-context.ts +0 -305
  437. package/lib/navigation.ts +0 -65
  438. package/lib/onboarding.ts +0 -41
  439. package/lib/scratchpad-skew.ts +0 -64
  440. package/lib/session-drafts.ts +0 -10
  441. package/lib/speed-mode.ts +0 -5
  442. package/lib/system-messages.ts +0 -241
  443. package/lib/themes.ts +0 -241
  444. package/lib/types.ts +0 -776
  445. package/lib/update.ts +0 -2
  446. package/lib/view-build-directives.ts +0 -11
  447. package/lib/workspace-config.ts +0 -48
  448. package/lib/workspace-icon.ts +0 -20
  449. package/lib/workspace-layout.ts +0 -15
  450. package/lib/workspace-name.ts +0 -17
  451. package/lib/workspace-tabs.ts +0 -29
  452. package/server/AGENTS.md +0 -17
  453. package/server/README.md +0 -123
  454. package/server/agent-caller.ts +0 -16
  455. package/server/agent-launcher.ts +0 -27
  456. package/server/api/harnesses.ts +0 -79
  457. package/server/api/index.ts +0 -1351
  458. package/server/api/onboarding.ts +0 -46
  459. package/server/app-config.ts +0 -264
  460. package/server/app-settings.ts +0 -69
  461. package/server/applets/api-base.ts +0 -4
  462. package/server/applets/applet-css.ts +0 -55
  463. package/server/applets/build-applet.ts +0 -475
  464. package/server/applets/build-worker.ts +0 -179
  465. package/server/applets/bundle-queue.ts +0 -19
  466. package/server/applets/config.ts +0 -226
  467. package/server/applets/declarations.ts +0 -45
  468. package/server/applets/dependencies.ts +0 -206
  469. package/server/applets/functions-worker.ts +0 -121
  470. package/server/applets/functions.ts +0 -392
  471. package/server/applets/index.ts +0 -504
  472. package/server/applets/log.ts +0 -149
  473. package/server/applets/runtime/collab.ts +0 -94
  474. package/server/applets/runtime/moi.ts +0 -35
  475. package/server/applets/runtime/rpc.ts +0 -15
  476. package/server/applets/thumbnails.ts +0 -200
  477. package/server/applets/typecheck.ts +0 -100
  478. package/server/applets/ui-components.ts +0 -241
  479. package/server/applets/view-source.ts +0 -73
  480. package/server/applets/views.ts +0 -323
  481. package/server/applets/widgets.ts +0 -181
  482. package/server/cli/applet-selector.ts +0 -19
  483. package/server/cli/args.ts +0 -5
  484. package/server/cli/colors.ts +0 -20
  485. package/server/cli/commands/bundle.ts +0 -119
  486. package/server/cli/commands/call-server-fn.ts +0 -42
  487. package/server/cli/commands/check.ts +0 -53
  488. package/server/cli/commands/config.ts +0 -120
  489. package/server/cli/commands/debug.ts +0 -119
  490. package/server/cli/commands/env.ts +0 -162
  491. package/server/cli/commands/hermes.ts +0 -149
  492. package/server/cli/commands/init.ts +0 -323
  493. package/server/cli/commands/navigate.ts +0 -35
  494. package/server/cli/commands/openclaw.ts +0 -168
  495. package/server/cli/commands/refresh.ts +0 -45
  496. package/server/cli/commands/remote.ts +0 -330
  497. package/server/cli/commands/scratch.ts +0 -496
  498. package/server/cli/commands/service.ts +0 -298
  499. package/server/cli/commands/skill.ts +0 -121
  500. package/server/cli/commands/start.ts +0 -112
  501. package/server/cli/commands/status.ts +0 -80
  502. package/server/cli/commands/tabs.ts +0 -36
  503. package/server/cli/commands/theme.ts +0 -192
  504. package/server/cli/commands/ui-components.ts +0 -15
  505. package/server/cli/commands/update.ts +0 -192
  506. package/server/cli/commands/version.ts +0 -9
  507. package/server/cli/commands/views.ts +0 -87
  508. package/server/cli/control.ts +0 -120
  509. package/server/cli/env.ts +0 -259
  510. package/server/cli/index.ts +0 -175
  511. package/server/cli/pc.ts +0 -20
  512. package/server/cli/provider.ts +0 -25
  513. package/server/cli/remote-command.ts +0 -77
  514. package/server/cli/remote-control.ts +0 -73
  515. package/server/cli/remote-operations.ts +0 -247
  516. package/server/cli/server-version.ts +0 -16
  517. package/server/cli/server.ts +0 -93
  518. package/server/cli/ui-components.ts +0 -294
  519. package/server/cli/ui.ts +0 -52
  520. package/server/cli.ts +0 -3
  521. package/server/collab/cloudflare-access.ts +0 -78
  522. package/server/collab/config.ts +0 -13
  523. package/server/collab/manager.ts +0 -413
  524. package/server/collab/service.ts +0 -136
  525. package/server/collab/skill/index.ts +0 -7
  526. package/server/collab/worker-messages.ts +0 -10
  527. package/server/collab/worker.ts +0 -52
  528. package/server/constants.ts +0 -13
  529. package/server/control-client.ts +0 -124
  530. package/server/control.ts +0 -572
  531. package/server/data-dir.ts +0 -22
  532. package/server/debug.ts +0 -10
  533. package/server/events.ts +0 -25
  534. package/server/harness/README.md +0 -381
  535. package/server/harness/acp/NOTES.md +0 -426
  536. package/server/harness/acp/adapter.ts +0 -206
  537. package/server/harness/acp/archived.ts +0 -88
  538. package/server/harness/acp/client.ts +0 -329
  539. package/server/harness/acp/discovery.ts +0 -127
  540. package/server/harness/acp/model-state.ts +0 -57
  541. package/server/harness/acp/run-durations.ts +0 -68
  542. package/server/harness/acp/session.ts +0 -786
  543. package/server/harness/acp/wire.ts +0 -132
  544. package/server/harness/auth.ts +0 -272
  545. package/server/harness/claude-code/NOTES.md +0 -651
  546. package/server/harness/claude-code/adapter.ts +0 -876
  547. package/server/harness/claude-code/auth.ts +0 -178
  548. package/server/harness/claude-code/cli.ts +0 -42
  549. package/server/harness/claude-code/git-worktree.ts +0 -35
  550. package/server/harness/claude-code/index.ts +0 -171
  551. package/server/harness/claude-code/mcp.ts +0 -152
  552. package/server/harness/claude-code/models.ts +0 -102
  553. package/server/harness/claude-code/permissions.ts +0 -34
  554. package/server/harness/claude-code/run-action.ts +0 -123
  555. package/server/harness/claude-code/session-title.ts +0 -104
  556. package/server/harness/claude-code/session.ts +0 -969
  557. package/server/harness/claude-code/sessions.ts +0 -153
  558. package/server/harness/codex/NOTES.md +0 -259
  559. package/server/harness/codex/adapter.ts +0 -633
  560. package/server/harness/codex/auth.ts +0 -140
  561. package/server/harness/codex/client.ts +0 -439
  562. package/server/harness/codex/connectors.ts +0 -92
  563. package/server/harness/codex/discovery.ts +0 -106
  564. package/server/harness/codex/index.ts +0 -107
  565. package/server/harness/codex/pagination.ts +0 -27
  566. package/server/harness/codex/permissions.ts +0 -80
  567. package/server/harness/codex/probe.ts +0 -183
  568. package/server/harness/codex/run-action.ts +0 -93
  569. package/server/harness/codex/session-title.ts +0 -147
  570. package/server/harness/codex/session.ts +0 -1196
  571. package/server/harness/codex/status.ts +0 -31
  572. package/server/harness/codex/thread-list.ts +0 -78
  573. package/server/harness/codex/transport.ts +0 -191
  574. package/server/harness/command.ts +0 -45
  575. package/server/harness/debug.ts +0 -57
  576. package/server/harness/detect.ts +0 -164
  577. package/server/harness/executable.ts +0 -125
  578. package/server/harness/fork.ts +0 -14
  579. package/server/harness/hermes/NOTES.md +0 -833
  580. package/server/harness/hermes/discovery.ts +0 -175
  581. package/server/harness/hermes/index.ts +0 -167
  582. package/server/harness/hermes/models.ts +0 -99
  583. package/server/harness/install.ts +0 -49
  584. package/server/harness/openclaw/NOTES.md +0 -749
  585. package/server/harness/openclaw/adapter.ts +0 -336
  586. package/server/harness/openclaw/compat.ts +0 -95
  587. package/server/harness/openclaw/cron-view.ts +0 -78
  588. package/server/harness/openclaw/discovery.ts +0 -456
  589. package/server/harness/openclaw/gateway.ts +0 -467
  590. package/server/harness/openclaw/index.ts +0 -125
  591. package/server/harness/openclaw/session.ts +0 -1512
  592. package/server/harness/openclaw/strip.ts +0 -184
  593. package/server/harness/openclaw/thinking.ts +0 -150
  594. package/server/harness/registry.ts +0 -39
  595. package/server/harness/run-action.ts +0 -85
  596. package/server/harness/session-title.ts +0 -59
  597. package/server/harness/shell-path.ts +0 -89
  598. package/server/harness/types.ts +0 -170
  599. package/server/navigation-relay.ts +0 -110
  600. package/server/onboarding/brief.ts +0 -29
  601. package/server/onboarding/ideas.ts +0 -48
  602. package/server/onboarding/jobs.ts +0 -291
  603. package/server/open-browser.ts +0 -7
  604. package/server/operations/commands.ts +0 -46
  605. package/server/operations/files.ts +0 -148
  606. package/server/operations/server.ts +0 -206
  607. package/server/remote/agent.ts +0 -103
  608. package/server/remote/broker-client.ts +0 -76
  609. package/server/remote/broker.ts +0 -81
  610. package/server/remote/client.ts +0 -725
  611. package/server/remote/errors.ts +0 -2
  612. package/server/remote/routes.ts +0 -121
  613. package/server/remote/workspace.ts +0 -34
  614. package/server/scratchpad/assets.ts +0 -258
  615. package/server/scratchpad/document.ts +0 -312
  616. package/server/scratchpad/executor.ts +0 -499
  617. package/server/scratchpad/relay.ts +0 -44
  618. package/server/scratchpad/shape-defaults.ts +0 -82
  619. package/server/server-cwd.ts +0 -23
  620. package/server/service.ts +0 -800
  621. package/server/sessions/archive.ts +0 -23
  622. package/server/sessions/attachment-message.ts +0 -95
  623. package/server/sessions/config.ts +0 -45
  624. package/server/sessions/lifecycle.ts +0 -19
  625. package/server/sessions/pending-views.ts +0 -158
  626. package/server/sessions/selected.ts +0 -113
  627. package/server/sessions/send-message.ts +0 -102
  628. package/server/sessions/store.ts +0 -54
  629. package/server/sessions/view-sessions.ts +0 -192
  630. package/server/skills/locations.ts +0 -82
  631. package/server/skills/lock.ts +0 -29
  632. package/server/skills/template.ts +0 -94
  633. package/server/skills/update.ts +0 -94
  634. package/server/skills/version.ts +0 -129
  635. package/server/skills/workspace.ts +0 -121
  636. package/server/state.ts +0 -40
  637. package/server/static.ts +0 -25
  638. package/server/status.ts +0 -110
  639. package/server/tldraw-package.d.ts +0 -4
  640. package/server/update.ts +0 -429
  641. package/server/uploads.ts +0 -290
  642. package/server/vendor.ts +0 -63
  643. package/server/version.ts +0 -41
  644. package/server/web.ts +0 -350
  645. package/server/workspace-state/file.ts +0 -181
  646. package/server/workspace-state/index.ts +0 -169
  647. package/server/workspace-state/lock.ts +0 -42
  648. package/server/workspace-state/types.ts +0 -16
  649. package/server/workspaces/api.ts +0 -24
  650. package/server/workspaces/change-harness.ts +0 -77
  651. package/server/workspaces/config.ts +0 -42
  652. package/server/workspaces/env-apply.ts +0 -20
  653. package/server/workspaces/env.ts +0 -424
  654. package/server/workspaces/harness-transition.ts +0 -29
  655. package/server/workspaces/icon.ts +0 -13
  656. package/server/workspaces/import.ts +0 -74
  657. package/server/workspaces/init.ts +0 -74
  658. package/server/workspaces/layout.ts +0 -190
  659. package/server/workspaces/preview.ts +0 -72
  660. package/server/workspaces/registry.ts +0 -330
  661. package/server/workspaces/required-env.ts +0 -19
  662. package/server/workspaces/scaffold.ts +0 -189
  663. package/server/workspaces/shared.ts +0 -74
  664. package/server/workspaces/tabs.ts +0 -35
  665. package/server/workspaces/theme.ts +0 -58
  666. package/tsconfig.json +0 -20
@@ -1,1512 +0,0 @@
1
- import type { MessageAttachment } from '@/lib/types'
2
- // Per-(workspaceId, sessionId) live OpenClaw session.
3
- //
4
- // Holds the in-memory view for one session and keeps it current from the
5
- // gateway's event stream: `session.message` rows build the turns, `chat` frames
6
- // drive the streaming preview, tool frames drive the tool cards, and the
7
- // run-end reconcile against `sessions.get` catches anything the wire dropped.
8
- // The gateway is the source of truth — nothing is persisted here, so a cold
9
- // open just re-seeds.
10
- //
11
- // The frame families and the order they arrive in are documented in NOTES.md
12
- // §6; the rules that follow from it (who owns a tool card, why identity is
13
- // decided once) are worth reading before changing anything here.
14
- import { replayAttachmentParts } from '@/lib/moi-attachments'
15
- import {
16
- materializeAttachmentPaths,
17
- prepareAttachmentMessage
18
- } from '../../sessions/attachment-message'
19
- import { type MoiContext, appendMoiContext, renderMoiContext } from '@/lib/moi-context'
20
- import {
21
- type PreviewBlock,
22
- type ToolCall,
23
- type ToolState,
24
- type Turn,
25
- applyEvent,
26
- emptyViewState
27
- } from '@/lib/format'
28
- import type { Part, SessionActivity, StreamEvent, ViewState } from '@/lib/types'
29
-
30
- import { messageIdempotencyKey } from './compat'
31
-
32
- import {
33
- type OpenClawMessage,
34
- type OpenClawSessionDetail,
35
- getOpenClawSessionMessages
36
- } from './discovery'
37
- import {
38
- type ToolResultInfo,
39
- findToolCallOwners,
40
- flattenToolResultContent,
41
- messageToTurn,
42
- toolResultFromMessage
43
- } from './adapter'
44
- import {
45
- currentGatewayHandle,
46
- getGateway,
47
- onGatewayReconnected,
48
- releaseSessionSubscriptionRef
49
- } from './gateway'
50
- import { recordOpenClawThinkingProfile, recordOpenClawThinkingRejection } from './thinking'
51
- import { broadcast } from '../../state'
52
- import { renameSessionReferences } from '../../sessions/lifecycle'
53
-
54
- type OpenClawSessionKey = string // the gateway-side composite key, e.g. `agent:main:main`
55
-
56
- type SessionRecord = {
57
- workspaceId: string
58
- workspacePath: string
59
- agentId: string
60
- sessionId: string
61
- sessionKey: OpenClawSessionKey
62
- // arrival-ordered map keyed by __openclaw.id so we can re-emit owners when
63
- // a result lands. We rely on insertion-order iteration to preserve order.
64
- messagesById: Map<string, OpenClawMessage>
65
- results: Map<string, ToolResultInfo>
66
- view: ViewState
67
- activeRunId: string | null
68
- ingestUnsubscribe?: () => void
69
- // Set once the cold seed has finished, so live frames that arrive
70
- // mid-seed are queued and applied after.
71
- seeded: boolean
72
- pendingFrames: OpenClawMessage[]
73
- // Optimistic id rendezvous: when the client sends a message we push the
74
- // optimistic id + text onto this FIFO. The durable user-row is matched by
75
- // its idempotency key (`<runId>:user`, exact) when the send's runId is
76
- // known, else by text. A queue rather than a single slot so two rapid sends
77
- // don't lose the first rendezvous when the gateway echo lags behind.
78
- pendingUserEchoes: { optimisticId: string; text: string; runId?: string }[]
79
- // Whether the client asked for token previews on the latest send.
80
- streamEnabled: boolean
81
- // Which frame family owns the current run's streaming preview. The first of
82
- // `chat` / `agent` to emit a delta claims the run so a gateway emitting both
83
- // doesn't double-broadcast (see claimPreviewSource).
84
- previewRunId?: string
85
- previewSource?: 'chat' | 'agent'
86
- // Streaming reasoning for the current run, and the last text blocks painted
87
- // with it. The `chat`/`agent` arbitration above decides who owns the TEXT,
88
- // but reasoning is not a duplicate of that text — on claude-cli it arrives on
89
- // its own `agent`/thinking stream while `chat` owns the text — so it bypasses
90
- // the claim and is merged into the same preview here instead. Both are
91
- // per-run and cleared when the run terminalizes.
92
- previewReasoning?: { runId: string; text: string }
93
- previewTextBlocks?: { runId: string; blocks: PreviewBlock[] }
94
- // Calls rendered as their own turn because no durable row owned them when the
95
- // tool started, keyed by toolCallId. Permanent for the session: durable rows
96
- // suppress these ids (adapter `omitToolCallIds`) so a row that later grows the
97
- // matching block can't render the call twice. A broadcast turn can never be
98
- // retracted, so ownership is decided once and then respected.
99
- liveTools: Map<string, { name: string; input: unknown; seq: number }>
100
- // Live reasoning spans from `agent`/item frames of kind `analysis`, keyed by
101
- // itemId. Timing only — those frames carry no reasoning text (see
102
- // handleReasoningItemFrame).
103
- liveThinking: Map<string, { startedAt: number; endedAt?: number; seq?: number }>
104
- // Highest `__openclaw.seq` ingested, and a monotonic tick for the synthetic
105
- // turns that hang off it. Together they place a live card between the
106
- // durable row that preceded it and the one that follows (see liveTurnSeq).
107
- lastDurableSeq: number
108
- liveTurnTick: number
109
- // The model ref we last asked the gateway for, and the `provider/model` the
110
- // last row reported. They differ only when something outside moi moved the
111
- // session, which is the whole point of keeping both.
112
- requestedModel?: string
113
- wireModel?: string
114
- appliedThinking?: string
115
- // Last `reasoningLevel` applied. The gateway defaults this to `off`, which
116
- // suppresses reasoning output entirely on providers that would emit it.
117
- appliedReasoning?: string
118
- // Model of the most recent assistant row seen (seed scan + live ingest). Lets
119
- // ingest detect a mid-session model switch without re-scanning the whole
120
- // messagesById map each frame; the model-change notice reads its `prev` here.
121
- lastAssistantModel?: string
122
- // Idle-eviction timer, armed when the session goes idle and cleared when it
123
- // goes busy or is torn down. OpenClaw holds only WS listeners (no subprocess),
124
- // so eviction just drops the record and releases the subscription.
125
- idleTimer?: ReturnType<typeof setTimeout> | null
126
- // In-flight reconcile, so the two run-end signals (sessions.changed + agent
127
- // lifecycle) coalesce onto one transcript fetch instead of racing two.
128
- reconcilePromise?: Promise<void>
129
- // The run whose failure we already told the user about. A dying run reports
130
- // itself on several frames with several wordings; the first with text wins
131
- // and the rest are echoes (see reportRunError).
132
- reportedErrorRunId?: string
133
- }
134
-
135
- const MAX_PENDING_USER_ECHOES = 16
136
-
137
- // OpenClaw sessions hold only WebSocket listeners — no subprocess, unlike Claude
138
- // Code — so eviction is cheap to redo and a looser TTL avoids churning the
139
- // cold-reopen re-seed. 10 minutes rather than Claude Code's 5.
140
- const IDLE_TTL_MS = 10 * 60_000
141
- // Soft cap on concurrently-held live records. Each is just a subscription +
142
- // in-memory view, so the cap is generous; the oldest idle record is evicted
143
- // when a new one would exceed it (a busy record is never evicted).
144
- const MAX_LIVE_SESSIONS = 32
145
-
146
- const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
147
- const openclawAgents = new Map<
148
- string,
149
- { processing: boolean; sessionKey: string; activeRunId: string | null }
150
- >()
151
-
152
- // On gateway reconnect, the gateway module replays subscriptions but durable
153
- // rows that landed during the disconnect aren't re-pushed. Reconcile every
154
- // known session against the canonical `sessions.get` transcript. Idempotent.
155
- onGatewayReconnected(async () => {
156
- for (const rec of sessions.values()) {
157
- try {
158
- await reconcileAfterRun(rec)
159
- } catch (err) {
160
- console.error('[openclaw-session] reconcile-on-reconnect failed', err)
161
- }
162
- }
163
- // Lifecycle frames emitted during the disconnect window are gone for good —
164
- // a run that ended while we were away would leave its session busy forever.
165
- // Re-derive every busy flag from the gateway's own `sessions.list` status.
166
- try {
167
- const busy = [...sessions.values()].filter(rec =>
168
- isOpenClawProcessing(rec.workspaceId, rec.sessionId)
169
- )
170
- if (busy.length === 0) return
171
- const gw = await getGateway()
172
- const res = await gw.rpc<{ sessions: { key: string; status?: string }[] }>('sessions.list', {
173
- includeGlobal: true
174
- })
175
- const running = new Set(
176
- (res?.sessions ?? []).filter(row => row.status === 'running').map(row => row.key)
177
- )
178
- for (const rec of busy) {
179
- if (!running.has(rec.sessionKey)) setProcessing(rec, false, null)
180
- }
181
- } catch (err) {
182
- console.error('[openclaw-session] busy-flag reconcile failed', err)
183
- }
184
- })
185
-
186
- function recKey(workspaceId: string, sessionId: string): string {
187
- return `${workspaceId}:${sessionId}`
188
- }
189
-
190
- // All non-idle OpenClaw sessions across every workspace, for the status
191
- // snapshot. Key is `${workspaceId}:${sessionId}` (both are colon-free). The
192
- // protocol has no "waiting for user input" concept, so activity is binary.
193
- export function getOpenClawActiveSessions(): {
194
- workspaceId: string
195
- sessionId: string
196
- activity: SessionActivity
197
- }[] {
198
- const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
199
- for (const [k, v] of openclawAgents) {
200
- if (!v.processing) continue
201
- const i = k.indexOf(':')
202
- out.push({ workspaceId: k.slice(0, i), sessionId: k.slice(i + 1), activity: 'running' })
203
- }
204
- return out
205
- }
206
-
207
- export function isOpenClawProcessing(workspaceId: string, sessionId: string): boolean {
208
- return openclawAgents.get(recKey(workspaceId, sessionId))?.processing === true
209
- }
210
-
211
- function setProcessing(rec: SessionRecord, processing: boolean, runId: string | null) {
212
- rec.activeRunId = runId
213
- const existing = openclawAgents.get(recKey(rec.workspaceId, rec.sessionId))
214
- openclawAgents.set(recKey(rec.workspaceId, rec.sessionId), {
215
- processing,
216
- sessionKey: rec.sessionKey,
217
- activeRunId: runId
218
- })
219
- // Idle eviction must never fire mid-run: hold the timer off while busy, and
220
- // (re)arm it whenever the session is idle.
221
- if (processing) clearIdleTimer(rec)
222
- else armIdleTimer(rec)
223
- if (existing?.processing === processing) return
224
- broadcast(rec.workspaceId, {
225
- type: 'session:status',
226
- sessionId: rec.sessionId,
227
- activity: processing ? 'running' : 'idle'
228
- })
229
- }
230
-
231
- function clearIdleTimer(rec: SessionRecord): void {
232
- if (rec.idleTimer) {
233
- clearTimeout(rec.idleTimer)
234
- rec.idleTimer = null
235
- }
236
- }
237
-
238
- function armIdleTimer(rec: SessionRecord): void {
239
- clearIdleTimer(rec)
240
- rec.idleTimer = setTimeout(() => {
241
- rec.idleTimer = null
242
- // A run may have started after the timer was armed — re-check and never
243
- // evict a busy session.
244
- if (isOpenClawProcessing(rec.workspaceId, rec.sessionId)) return
245
- teardownOpenClawSession(rec)
246
- }, IDLE_TTL_MS)
247
- }
248
-
249
- // Drop a live session: stop consuming its frames, release the gateway
250
- // subscription, and forget it. Idempotent — a record already removed from the
251
- // map is a no-op. REST reads (`sessionEvents`/`ensureOpenClawSessionLive`) still
252
- // work afterward: `getOrCreateOpenClawSession` cold-reopens and re-seeds from
253
- // `sessions.get` (or synthesizes cron turns), so eviction only costs a re-seed.
254
- export function teardownOpenClawSession(rec: SessionRecord): void {
255
- const k = recKey(rec.workspaceId, rec.sessionId)
256
- if (sessions.get(k) !== rec) return
257
- clearIdleTimer(rec)
258
- rec.ingestUnsubscribe?.()
259
- rec.ingestUnsubscribe = undefined
260
- // Release the refcounted subscription. When connected, go through the handle
261
- // (drops demand + issues the wire unsubscribe on the last holder); never force
262
- // a connect from teardown. With no live handle (disconnected, or a test
263
- // without a gateway) still drop the demand so a reconnect won't replay a dead
264
- // key — the wire is already down.
265
- const gw = currentGatewayHandle()
266
- if (gw) {
267
- void gw
268
- .releaseSessionSubscription(rec.sessionKey)
269
- .catch(err => console.error('[openclaw-session] releaseSessionSubscription failed', err))
270
- } else {
271
- releaseSessionSubscriptionRef(rec.sessionKey)
272
- }
273
- // Clear this workspace's trailing list-refresh timer only when no other live
274
- // session remains for it — otherwise a sibling still needs it.
275
- const workspaceHasOtherLive = [...sessions.values()].some(
276
- r => r !== rec && r.workspaceId === rec.workspaceId
277
- )
278
- if (!workspaceHasOtherLive) {
279
- const entry = lastListRefresh.get(rec.workspaceId)
280
- if (entry?.trailing) clearTimeout(entry.trailing)
281
- lastListRefresh.delete(rec.workspaceId)
282
- }
283
- const wasProcessing = isOpenClawProcessing(rec.workspaceId, rec.sessionId)
284
- sessions.delete(k)
285
- openclawAgents.delete(k)
286
- // If it was mid-run, mirror setProcessing(rec, false, null)'s client-visible
287
- // effect so no spinner is left hanging.
288
- if (wasProcessing) {
289
- broadcast(rec.workspaceId, {
290
- type: 'session:status',
291
- sessionId: rec.sessionId,
292
- activity: 'idle'
293
- })
294
- }
295
- }
296
-
297
- // Server shutdown: tear down every live record so no session keeps consuming
298
- // frames. We deliberately do NOT stop the shared gateway client — process exit
299
- // drops it, and discovery may still need it during the same run. A cold reopen
300
- // re-seeds from `sessions.get`.
301
- export function killAllOpenClawSessions(): void {
302
- for (const rec of [...sessions.values()]) teardownOpenClawSession(rec)
303
- }
304
-
305
- // Run-end reconcile against the canonical transcript. `toolResult` rows never
306
- // stream (NOTES.md §6) and a row can grow content after it streams, so this is
307
- // how the view catches up. Idempotent.
308
- function reconcileAfterRun(rec: SessionRecord): Promise<void> {
309
- // Both sessions.changed and agent lifecycle can end a run; coalesce onto one
310
- // in-flight transcript fetch rather than racing two.
311
- if (rec.reconcilePromise) return rec.reconcilePromise
312
- const p = reconcileAfterRunImpl(rec).finally(() => {
313
- if (rec.reconcilePromise === p) rec.reconcilePromise = undefined
314
- })
315
- rec.reconcilePromise = p
316
- return p
317
- }
318
-
319
- async function reconcileAfterRunImpl(rec: SessionRecord): Promise<void> {
320
- // Snapshot the unfinished cards BEFORE the fetch: `rec.liveTools` is
321
- // session-wide, and a follow-up run starting during the round-trip would
322
- // otherwise have its fresh cards swept by this run's reconcile.
323
- const stale = unfinishedLiveTools(rec)
324
- const detail = await getOpenClawSessionMessages(rec.sessionId, rec.workspacePath, rec.agentId)
325
- if (!detail?.messages) return
326
- mergeTranscript(rec, detail.messages, stale)
327
- }
328
-
329
- // Tool calls with a live card that has not reported a result yet.
330
- function unfinishedLiveTools(rec: SessionRecord): string[] {
331
- return [...rec.liveTools.keys()].filter(id => rec.results.get(id)?.running)
332
- }
333
-
334
- // Test seam: the merge half of the reconcile, against a transcript the caller
335
- // supplies instead of one fetched over the gateway.
336
- export function reconcileForTest(rec: SessionRecord, messages: OpenClawMessage[]): void {
337
- mergeTranscript(rec, messages, unfinishedLiveTools(rec))
338
- }
339
-
340
- // Test seam: the two halves of the reconcile split, so a test can interleave a
341
- // follow-up run's frames between the snapshot and the merge the way the real
342
- // transcript round-trip does.
343
- export function reconcileSnapshotForTest(rec: SessionRecord): string[] {
344
- return unfinishedLiveTools(rec)
345
- }
346
-
347
- export function reconcileWithStaleForTest(
348
- rec: SessionRecord,
349
- messages: OpenClawMessage[],
350
- stale: string[]
351
- ): void {
352
- mergeTranscript(rec, messages, stale)
353
- }
354
-
355
- // Fold a canonical transcript into the live view: adopt rows we're missing or
356
- // behind on, refresh tool results, and end the cards in `stale` that the run
357
- // left running.
358
- function mergeTranscript(rec: SessionRecord, messages: OpenClawMessage[], stale: string[]): void {
359
- const owners = new Set<OpenClawMessage>()
360
- for (const msg of messages) {
361
- const result = toolResultFromMessage(msg)
362
- if (result) {
363
- const existing = rec.results.get(result.id)
364
- if (
365
- !existing ||
366
- // A live `session.tool` start whose result frame was lost (disconnect)
367
- // must be finalized even when the durable output is identical-empty —
368
- // otherwise the card spins forever.
369
- existing.running ||
370
- existing.output !== result.info.output ||
371
- existing.isError !== result.info.isError
372
- ) {
373
- rec.results.set(result.id, result.info)
374
- for (const o of findToolCallOwners(rec.messagesById.values(), result.id)) {
375
- owners.add(o)
376
- }
377
- }
378
- continue
379
- }
380
- if (msg.role !== 'user' && msg.role !== 'assistant') continue
381
- const id = msg.__openclaw?.id
382
- if (typeof id !== 'string') continue
383
- // Adopt rows we never saw AND rows whose content grew after they streamed.
384
- // Both happen on the live wire: a row that fans out several tool calls is
385
- // pushed as text and gains its `toolCall` blocks silently afterwards, so a
386
- // has-the-id check alone leaves the view permanently behind the transcript.
387
- const known = rec.messagesById.get(id)
388
- if (!known || !sameContent(known, msg)) {
389
- rec.messagesById.set(id, msg)
390
- rememberSeq(rec, msg)
391
- owners.add(msg)
392
- }
393
- }
394
- // Cards still running when this run ended: nothing more is coming for them, so
395
- // end them rather than leaving a permanent spinner. `stale` is captured before
396
- // the transcript fetch — a follow-up run can start during it and add its own
397
- // live cards, and finalizing those would strand the NEW run's tools.
398
- //
399
- // They end as errors, not successes. All we know is that no result arrived;
400
- // reading that as "succeeded, with no output" would show a command that may
401
- // well have failed as if it had worked.
402
- for (const toolCallId of stale) {
403
- const result = rec.results.get(toolCallId)
404
- if (!result?.running) continue
405
- rec.results.set(toolCallId, {
406
- ...result,
407
- running: false,
408
- isError: true,
409
- output: result.output || 'No result was reported before the run ended.'
410
- })
411
- emitLiveToolTurn(rec, toolCallId)
412
- }
413
- if (owners.size === 0) return
414
- let idx = 0
415
- for (const m of rec.messagesById.values()) {
416
- if (owners.has(m)) emitTurn(rec, m, idx)
417
- idx++
418
- }
419
- }
420
-
421
- // Do two versions of the same durable row carry the same content? Structural
422
- // compare on the blocks only — the fields around them (usage, stopReason) can
423
- // be filled in later without changing what the turn renders.
424
- function sameContent(a: OpenClawMessage, b: OpenClawMessage): boolean {
425
- return JSON.stringify(a.content) === JSON.stringify(b.content)
426
- }
427
-
428
- // Re-derive the view from the current messages + results map. Cheaper than
429
- // it sounds because we keep the materialized `view` and re-build only when
430
- // a tool-result update forces a re-emit.
431
- function rebuildView(rec: SessionRecord): void {
432
- let view: ViewState = emptyViewState()
433
- let i = 0
434
- // Mirror the cold path (adapter.toStreamEvents): reconstruct model-change
435
- // notices from the durable rows so a seeded live view replays the same
436
- // notices the static transcript would show. Same ids as the live emitter,
437
- // so a notice seen live upserts instead of duplicating.
438
- let prevModel: string | undefined
439
- for (const msg of rec.messagesById.values()) {
440
- if (msg.role === 'assistant') {
441
- const model = (msg as { model?: unknown }).model
442
- if (typeof model === 'string') {
443
- if (prevModel !== undefined && prevModel !== model) {
444
- view = applyEvent(view, {
445
- kind: 'notice',
446
- notice: {
447
- id: `openclaw:model-change:${msg.__openclaw?.id ?? i}`,
448
- kind: 'model-change',
449
- at:
450
- typeof msg.timestamp === 'number'
451
- ? new Date(msg.timestamp).toISOString()
452
- : new Date().toISOString(),
453
- model,
454
- prev: prevModel
455
- }
456
- })
457
- }
458
- prevModel = model
459
- }
460
- }
461
- const turn = messageToTurn(msg, rec.sessionKey, i++, rec.results, liveToolIds(rec))
462
- if (turn) view = applyEvent(view, { kind: 'turn', turn })
463
- }
464
- // Compaction notices have no durable twin in `sessions.get` — they exist
465
- // only while a live record witnesses the compact frame (known gap; the
466
- // gateway's `sessions.compaction.list` could backfill them).
467
- rec.view = view
468
- // Seed the model cache so live ingest can detect the next switch off the last
469
- // assistant model without re-scanning the transcript.
470
- rec.lastAssistantModel = prevModel
471
- }
472
-
473
- // The preview slot for a run. Doubles as `meta.apiMessageId` on the run's
474
- // committed assistant turns so the client's native preview reconciliation
475
- // clears the live text the instant the durable turn lands.
476
- function previewMessageId(sessionKey: string, runId: string): string {
477
- return `openclaw:${sessionKey}:${runId}`
478
- }
479
-
480
- // Compare the optimistic send text against the durable user-row text
481
- // tolerantly: drop any moi-context envelope (defensive — the optimistic side
482
- // shouldn't carry it) and collapse all whitespace runs so newline/trim drift
483
- // between what we sent and what the gateway stored can't defeat the match.
484
- export function normalizeEchoText(text: string | undefined): string {
485
- if (typeof text !== 'string') return ''
486
- return userEchoKey(replayAttachmentParts([{ type: 'text', text }]))
487
- }
488
-
489
- export function userEchoKey(parts: readonly Part[]): string {
490
- const text = parts
491
- .filter(p => p.type === 'text')
492
- .map(p => p.text)
493
- .join('\n')
494
- const visible = text.replace(/\s+/g, ' ').trim()
495
- const attachments = parts.filter(
496
- p => p.type === 'text-attachment' || p.type === 'file-attachment'
497
- )
498
- return attachments.length ? `${visible}\n${JSON.stringify(attachments)}` : visible
499
- }
500
-
501
- // Synthetic turns (live tool cards, live thinking spans) have no transcript
502
- // row, so they get a fractional position just past the last durable row we
503
- // ingested. That keeps them after the text that introduced them and before
504
- // whatever the backend commits next, without ever colliding with a real seq.
505
- function liveTurnSeq(rec: SessionRecord): number {
506
- rec.liveTurnTick += 1
507
- return rec.lastDurableSeq + rec.liveTurnTick / 1000
508
- }
509
-
510
- // Tool calls owned by a live card, for the adapter to leave out of durable
511
- // rows. `undefined` when there are none, so the common path allocates nothing.
512
- function liveToolIds(rec: SessionRecord): ReadonlySet<string> | undefined {
513
- return rec.liveTools.size > 0 ? new Set(rec.liveTools.keys()) : undefined
514
- }
515
-
516
- function emitTurn(rec: SessionRecord, msg: OpenClawMessage, idx: number): void {
517
- const turn = messageToTurn(msg, rec.sessionKey, idx, rec.results, liveToolIds(rec))
518
- if (!turn) return
519
- // Optimistic-id rendezvous: re-id the durable user row to the bubble the
520
- // client already drew, so it upserts in place instead of duplicating.
521
- if (rec.pendingUserEchoes.length > 0 && turn.role === 'user') {
522
- const idem = messageIdempotencyKey(msg)
523
- // Three ways in, cheapest first: the send's own `<runId>:user` key; the
524
- // same key with the runId read off the row (the echo can beat the
525
- // `sessions.send` response); and normalized text, for rows carrying
526
- // neither.
527
- const idemRunId = idem?.endsWith(':user') ? idem.slice(0, -':user'.length) : undefined
528
- let at = idem
529
- ? rec.pendingUserEchoes.findIndex(
530
- e => (e.runId && `${e.runId}:user` === idem) || (idemRunId && e.runId === idemRunId)
531
- )
532
- : -1
533
- if (at < 0) {
534
- const text = userEchoKey(turn.parts)
535
- if (text) at = rec.pendingUserEchoes.findIndex(e => normalizeEchoText(e.text) === text)
536
- }
537
- if (at >= 0) {
538
- turn.id = rec.pendingUserEchoes[at].optimisticId
539
- rec.pendingUserEchoes.splice(at, 1)
540
- }
541
- }
542
- // Stamp the run's preview slot id so the client clears the streaming
543
- // preview when this turn upserts (chat deltas can trail the durable row).
544
- // Only FRESH turns get the current run's slot — a re-emitted older turn
545
- // (tool-result fold-in, reconcile) keeps whatever it was stamped with, so
546
- // it can never clear a newer run's live preview.
547
- if (turn.role === 'assistant') {
548
- const prior = rec.view.turns.find(t => t.id === turn.id)
549
- if (prior) {
550
- const kept = prior.meta?.apiMessageId
551
- if (kept) turn.meta = { ...turn.meta, apiMessageId: kept }
552
- } else if (rec.activeRunId) {
553
- turn.meta = { ...turn.meta, apiMessageId: previewMessageId(rec.sessionKey, rec.activeRunId) }
554
- }
555
- }
556
- rec.view = applyEvent(rec.view, { kind: 'turn', turn })
557
- broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
558
- }
559
-
560
- // Re-emit every assistant turn that references `toolCallId` so its tool card
561
- // reflects the latest entry in `rec.results`.
562
- function reemitToolCallOwners(rec: SessionRecord, toolCallId: string): void {
563
- const owners = findToolCallOwners(rec.messagesById.values(), toolCallId)
564
- const ownerSet = new Set(owners)
565
- let idx = 0
566
- for (const m of rec.messagesById.values()) {
567
- if (ownerSet.has(m)) emitTurn(rec, m, idx)
568
- idx++
569
- }
570
- }
571
-
572
- // A `chat` delta frame carries the whole in-progress message; map its blocks to
573
- // cumulative PreviewBlocks. Text and thinking only — tool calls have their own
574
- // cards. Exported for tests.
575
- export function chatPreviewBlocks(content: unknown): PreviewBlock[] {
576
- if (typeof content === 'string') {
577
- return content ? [{ index: 0, kind: 'text', text: content }] : []
578
- }
579
- if (!Array.isArray(content)) return []
580
- const blocks: PreviewBlock[] = []
581
- content.forEach((block, index) => {
582
- if (!block || typeof block !== 'object') return
583
- const b = block as { type?: unknown; text?: unknown; thinking?: unknown }
584
- if (b.type === 'text' && typeof b.text === 'string' && b.text) {
585
- blocks.push({ index, kind: 'text', text: b.text })
586
- } else if (b.type === 'thinking' && typeof b.thinking === 'string' && b.thinking) {
587
- blocks.push({ index, kind: 'reasoning', text: b.thinking })
588
- }
589
- })
590
- return blocks
591
- }
592
-
593
- // A gateway streams the assistant text on BOTH `chat` state=delta and `agent`
594
- // stream=assistant, for the same run, in the same millisecond. Whichever emits
595
- // first claims the run so the two cumulative snapshots can't race into a
596
- // flicker; a gateway sending only one of them still streams.
597
- type PreviewSource = 'chat' | 'agent'
598
- // Exported for tests: only reads/writes the two preview-source fields.
599
- export function claimPreviewSource(
600
- rec: Pick<SessionRecord, 'previewRunId' | 'previewSource'>,
601
- runId: string,
602
- source: PreviewSource
603
- ): boolean {
604
- if (rec.previewRunId !== runId) {
605
- rec.previewRunId = runId
606
- rec.previewSource = source
607
- return true
608
- }
609
- return rec.previewSource === source
610
- }
611
-
612
- function broadcastPreview(rec: SessionRecord, messageId: string, blocks: PreviewBlock[]): void {
613
- broadcast(rec.workspaceId, {
614
- type: 'session:preview',
615
- sessionId: rec.sessionId,
616
- messageId,
617
- parentToolUseId: null,
618
- blocks
619
- })
620
- }
621
-
622
- // Repaint the preview from both streams at once: reasoning first (it precedes
623
- // the answer), then the text. A preview replaces every block for its messageId,
624
- // so broadcasting the two separately would erase one with the other. Keyed by
625
- // runId rather than by the claim, so reasoning can never lock the text source
626
- // out of its own run.
627
- function emitMergedPreview(rec: SessionRecord, runId: string, messageId: string): void {
628
- const blocks: PreviewBlock[] = []
629
- const reasoning = rec.previewReasoning?.runId === runId ? rec.previewReasoning.text : ''
630
- if (reasoning) blocks.push({ index: 0, kind: 'reasoning', text: reasoning })
631
- if (rec.previewTextBlocks?.runId === runId) {
632
- for (const block of rec.previewTextBlocks.blocks)
633
- blocks.push({ ...block, index: blocks.length })
634
- }
635
- broadcastPreview(rec, messageId, blocks)
636
- }
637
-
638
- // Drop the per-run preview state once the run terminalizes, so the next run
639
- // starts clean instead of inheriting the previous run's reasoning.
640
- function clearPreviewState(rec: SessionRecord): void {
641
- rec.previewReasoning = undefined
642
- rec.previewTextBlocks = undefined
643
- }
644
-
645
- // `agent` stream=assistant / reasoning frames carry the cumulative in-progress
646
- // text in `data.text` — the fallback streaming source for gateways that don't
647
- // emit `chat` delta frames.
648
- function handleAgentStreamFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
649
- if (!rec.streamEnabled) return
650
- const stream = payload.stream
651
- // `thinking` is a second wire name for the reasoning stream, carrying the
652
- // same `{ text, delta }` shape as `assistant`. Matching only `reasoning`
653
- // dropped it on the floor. Verified on the wire from the `openai-codex`
654
- // responses transport (`…:skill-workshop-review:*` sessions stream real
655
- // reasoning text under `stream: 'thinking'`). Note this does NOT light up
656
- // the claude-cli backend: its `thinking` frames are bare
657
- // `{ progressTokens }` heartbeats with no text at all, so they fall out on
658
- // the empty-text check below — that backend simply never ships the words.
659
- const kind: PreviewBlock['kind'] | null =
660
- stream === 'assistant'
661
- ? 'text'
662
- : stream === 'reasoning' || stream === 'thinking'
663
- ? 'reasoning'
664
- : null
665
- if (!kind) return
666
- const runId = typeof payload.runId === 'string' ? payload.runId : rec.activeRunId
667
- if (!runId) return
668
- const data = payload.data as { text?: unknown } | undefined
669
- const text = typeof data?.text === 'string' ? data.text : ''
670
- if (!text) return
671
- if (kind === 'reasoning') {
672
- // Reasoning bypasses the text claim entirely — see `previewReasoning`.
673
- rec.previewReasoning = { runId, text }
674
- } else {
675
- if (!claimPreviewSource(rec, runId, 'agent')) return
676
- rec.previewTextBlocks = { runId, blocks: [{ index: 0, kind, text }] }
677
- }
678
- emitMergedPreview(rec, runId, previewMessageId(rec.sessionKey, runId))
679
- }
680
-
681
- // A dying run says why on three different frames with three different wordings
682
- // (NOTES.md §6), and the reason is something the user can act on. Report the
683
- // first that carries text; the rest are echoes. Without this the chat just
684
- // stops — spinner off, nothing said.
685
- export function reportRunError(rec: SessionRecord, runId: string, message: unknown): void {
686
- if (rec.reportedErrorRunId === runId) return
687
- const text = typeof message === 'string' ? message.trim() : ''
688
- if (!text) return
689
- rec.reportedErrorRunId = runId
690
- broadcast(rec.workspaceId, { kind: 'error', sessionId: rec.sessionId, content: text })
691
- }
692
-
693
- function handleChatFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
694
- const runId = typeof payload.runId === 'string' ? payload.runId : rec.activeRunId
695
- if (!runId) return
696
- // Errors are reported whether or not the client asked for token streaming —
697
- // the toggle governs previews, not whether failures are visible.
698
- if (payload.state === 'error') reportRunError(rec, runId, payload.errorMessage)
699
- if (!rec.streamEnabled) return
700
- const messageId = previewMessageId(rec.sessionKey, runId)
701
- const state = payload.state
702
- if (state === 'delta') {
703
- const message = payload.message as { content?: unknown } | undefined
704
- const blocks = chatPreviewBlocks(message?.content)
705
- if (blocks.length === 0) return
706
- if (!claimPreviewSource(rec, runId, 'chat')) return
707
- rec.previewTextBlocks = { runId, blocks }
708
- // Merged, not raw: on claude-cli the reasoning arrives on a separate
709
- // stream, and a bare broadcast here would wipe it off the preview.
710
- emitMergedPreview(rec, runId, messageId)
711
- } else if (state === 'final' || state === 'error' || state === 'aborted') {
712
- clearPreviewState(rec)
713
- // Belt-and-braces clear: the durable turn's apiMessageId already clears
714
- // the slot, but a trailing delta after the durable row would repaint it.
715
- // 'aborted' arrives when a steer/abort interrupts the run mid-stream —
716
- // without the clear the dead preview would linger (verified live).
717
- broadcastPreview(rec, messageId, [])
718
- }
719
- }
720
-
721
- // The id of the live tool turn for a toolCallId. Stable for the session, so
722
- // every later frame for that call upserts the same card.
723
- function liveToolTurnId(sessionKey: string, toolCallId: string): string {
724
- return `openclaw:${sessionKey}:livetool:${toolCallId}`
725
- }
726
-
727
- // Build (and broadcast) a synthetic assistant turn holding a single tool card,
728
- // from the live tool state in `rec.liveTools` + `rec.results`. Used when a
729
- // tool executes before its durable owner row exists.
730
- function emitLiveToolTurn(rec: SessionRecord, toolCallId: string): void {
731
- const meta = rec.liveTools.get(toolCallId)
732
- if (!meta) return
733
- const result = rec.results.get(toolCallId)
734
- let state: ToolState = 'pending'
735
- if (result) state = result.running ? 'running' : result.isError ? 'error' : 'success'
736
- const call: ToolCall = {
737
- toolCallId,
738
- name: meta.name,
739
- caller: 'model',
740
- provider: 'openclaw',
741
- state,
742
- input: meta.input
743
- }
744
- if (result && !result.running) {
745
- if (result.isError) call.errorText = result.output
746
- else call.output = result.output
747
- }
748
- const turn: Turn = {
749
- id: liveToolTurnId(rec.sessionKey, toolCallId),
750
- role: 'assistant',
751
- origin: { kind: 'user-input' },
752
- parts: [{ type: 'tool-call', call }],
753
- seq: meta.seq
754
- }
755
- rec.view = applyEvent(rec.view, { kind: 'turn', turn })
756
- broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
757
- }
758
-
759
- // A run can die during admission, before it reports any lifecycle phase. The
760
- // gateway announces that only as `sessions.changed { reason:
761
- // 'chat.dispatch-error' }` — no runId, no error text — so the runId-keyed
762
- // clauses never fire and the composer would spin forever. With no cause on the
763
- // wire, say the one thing the user can act on.
764
- export function handleDispatchError(rec: SessionRecord): void {
765
- setProcessing(rec, false, null)
766
- broadcast(rec.workspaceId, {
767
- kind: 'error',
768
- sessionId: rec.sessionId,
769
- content: 'OpenClaw could not start the run. Send the message again.'
770
- })
771
- }
772
-
773
- // The id of the run-scoped live thinking turn for a reasoning item.
774
- function liveThinkingTurnId(sessionKey: string, itemId: string): string {
775
- return `openclaw:${sessionKey}:livethink:${itemId}`
776
- }
777
-
778
- // Some runtimes report reasoning as an `agent`/item frame of `kind: 'analysis'`
779
- // (emitted by `extensions/codex`) — presence and timing, never text. Render
780
- // what they do give: a "Thinking" row that becomes "Thought for 1.2s", instead
781
- // of a silent gap before the first token. Not durable — nothing in the
782
- // transcript backs it, so a cold reload drops the row.
783
- export function handleReasoningItemFrame(
784
- rec: SessionRecord,
785
- payload: Record<string, unknown>
786
- ): void {
787
- const data = payload.data as
788
- | { itemId?: unknown; phase?: unknown; kind?: unknown; title?: unknown }
789
- | undefined
790
- if (!data || typeof data.itemId !== 'string') return
791
- // Only the analysis/Reasoning item; other item kinds are tool lifecycle.
792
- const isReasoning =
793
- data.kind === 'analysis' || String(data.title ?? '').toLowerCase() === 'reasoning'
794
- if (!isReasoning) return
795
- const itemId = data.itemId
796
- const at = typeof payload.ts === 'number' ? payload.ts : Date.now()
797
-
798
- if (data.phase === 'start') {
799
- rec.liveThinking.set(itemId, { startedAt: at })
800
- } else if (data.phase === 'end') {
801
- const started = rec.liveThinking.get(itemId)
802
- if (!started) return
803
- rec.liveThinking.set(itemId, { ...started, endedAt: at })
804
- } else {
805
- return
806
- }
807
- emitLiveThinkingTurn(rec, itemId)
808
- }
809
-
810
- function emitLiveThinkingTurn(rec: SessionRecord, itemId: string): void {
811
- const span = rec.liveThinking.get(itemId)
812
- if (!span) return
813
- const duration = span.endedAt !== undefined ? span.endedAt - span.startedAt : undefined
814
- const turn: Turn = {
815
- id: liveThinkingTurnId(rec.sessionKey, itemId),
816
- role: 'assistant',
817
- origin: { kind: 'user-input' },
818
- // Placed once, on the `start` frame — the `end` frame upserts the same
819
- // turn, so the row must not hop to a new position when it finishes.
820
- seq: (span.seq ??= liveTurnSeq(rec)),
821
- parts: [
822
- {
823
- type: 'reasoning',
824
- text: '',
825
- redacted: true,
826
- ...(duration !== undefined && duration >= 0 ? { durationMs: duration } : {})
827
- }
828
- ]
829
- }
830
- rec.view = applyEvent(rec.view, { kind: 'turn', turn })
831
- broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
832
- }
833
-
834
- // Live tool state, from either frame family: `session.tool` and `agent`/tool
835
- // are the same payload sent to disjoint audiences (NOTES.md §6), so one
836
- // handler serves both. start/update → running, result → success/error with
837
- // output. Exported for tests.
838
- export function handleToolFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
839
- const data = payload.data as
840
- | {
841
- phase?: unknown
842
- name?: unknown
843
- toolCallId?: unknown
844
- isError?: unknown
845
- result?: unknown
846
- args?: unknown
847
- }
848
- | undefined
849
- if (!data || typeof data.toolCallId !== 'string') return
850
- const id = data.toolCallId
851
- const name = typeof data.name === 'string' ? data.name : undefined
852
- const toolName = name ? { toolName: name } : {}
853
- if (data.phase === 'start' || data.phase === 'update') {
854
- // Does a durable row already own this call? If so it renders the card. If
855
- // not, this frame is the only evidence the call exists, so give it a turn of
856
- // its own. Which case applies is a property of the run, not of the backend
857
- // (NOTES.md §6) — asking the messages map is exact and needs no guess.
858
- if (
859
- name &&
860
- !rec.liveTools.has(id) &&
861
- findToolCallOwners(rec.messagesById.values(), id).length === 0
862
- ) {
863
- rec.liveTools.set(id, { name, input: data.args, seq: liveTurnSeq(rec) })
864
- }
865
- const existing = rec.results.get(id)
866
- if (existing && !existing.running) return // final result already landed
867
- rec.results.set(id, { output: '', isError: false, running: true, ...toolName })
868
- } else if (data.phase === 'result') {
869
- // Two result shapes on the wire: `{ content: [...] }` from the exec-style
870
- // tools, and a bare string from CLI-backed runtimes. Reading `.content` off
871
- // a string yields undefined, which rendered those cards with an empty body.
872
- const raw = data.result
873
- const content =
874
- typeof raw === 'string' ? raw : ((raw as { content?: unknown } | undefined)?.content ?? '')
875
- rec.results.set(id, {
876
- output: flattenToolResultContent(content as OpenClawMessage['content']),
877
- isError: data.isError === true,
878
- ...toolName
879
- })
880
- } else {
881
- return
882
- }
883
- const owners = findToolCallOwners(rec.messagesById.values(), id)
884
- if (owners.length > 0) reemitToolCallOwners(rec, id)
885
- else if (rec.liveTools.has(id)) emitLiveToolTurn(rec, id)
886
- }
887
-
888
- // Debounced session-list refresh. `sessions.changed` fires for every session
889
- // under the agent and several records can hold subscriptions for one workspace,
890
- // so bursts are the norm; the trailing flush catches the tail of one (a create
891
- // followed straight away by the title patch).
892
- const lastListRefresh = new Map<string, { at: number; trailing?: ReturnType<typeof setTimeout> }>()
893
- const LIST_REFRESH_MIN_MS = 400
894
- const LIST_REFRESH_REASONS = new Set([
895
- 'chat.title',
896
- 'create',
897
- 'delete',
898
- 'patch',
899
- 'label',
900
- 'compact',
901
- 'send',
902
- 'steer',
903
- 'subagent-status'
904
- ])
905
- function broadcastSessionsChanged(rec: SessionRecord): void {
906
- const now = Date.now()
907
- const entry = lastListRefresh.get(rec.workspaceId)
908
- if (entry && now - entry.at < LIST_REFRESH_MIN_MS) {
909
- if (!entry.trailing) {
910
- entry.trailing = setTimeout(
911
- () => {
912
- lastListRefresh.set(rec.workspaceId, { at: Date.now() })
913
- broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
914
- },
915
- LIST_REFRESH_MIN_MS - (now - entry.at)
916
- )
917
- }
918
- return
919
- }
920
- if (entry?.trailing) clearTimeout(entry.trailing)
921
- lastListRefresh.set(rec.workspaceId, { at: now })
922
- broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
923
- }
924
-
925
- // Exported for tests (the live subscription is the only production caller).
926
- export function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
927
- // toolResult: update the results map and re-emit each owner turn so the
928
- // tool-call card gets `state: 'success'/'error'` + output folded in.
929
- const result = toolResultFromMessage(msg)
930
- if (result) {
931
- rec.results.set(result.id, result.info)
932
- reemitToolCallOwners(rec, result.id)
933
- return
934
- }
935
-
936
- if (msg.role !== 'user' && msg.role !== 'assistant') return
937
- // Skip the gateway's transient pre-envelope echo — those frames lack
938
- // `__openclaw.id`. The durable row arrives ~6s later with id + envelope.
939
- const id = msg.__openclaw?.id
940
- if (typeof id !== 'string') return
941
- // A durable assistant row on a different model than the previous one marks
942
- // a mid-session model switch (sessions.patch here or anywhere else) —
943
- // surface it as a notice instead of letting it pass silently.
944
- if (msg.role === 'assistant') {
945
- const model = (msg as { model?: unknown }).model
946
- if (typeof model === 'string') {
947
- // Compare against the cached last assistant model instead of re-scanning
948
- // the whole messagesById map each frame. Same notice id (`__openclaw.id`)
949
- // as the cold rebuildView path, so live and cold agree on upsert.
950
- const prev = rec.lastAssistantModel
951
- if (prev !== undefined && prev !== model) {
952
- const notice = {
953
- id: `openclaw:model-change:${id}`,
954
- kind: 'model-change' as const,
955
- // The switching turn's own timestamp, so live and cold placement
956
- // agree (the client sorts equal-time notices before the turn).
957
- at:
958
- typeof msg.timestamp === 'number'
959
- ? new Date(msg.timestamp).toISOString()
960
- : new Date().toISOString(),
961
- model,
962
- prev
963
- }
964
- // Fold into the view too — the REST events replay must agree with
965
- // the WS frames the client already saw.
966
- rec.view = applyEvent(rec.view, { kind: 'notice', notice })
967
- broadcast(rec.workspaceId, { kind: 'notice', sessionId: rec.sessionId, notice })
968
- }
969
- rec.lastAssistantModel = model
970
- }
971
- }
972
- rec.messagesById.set(id, msg)
973
- rememberSeq(rec, msg)
974
- // Compute idx as insertion order — for an update use the existing position,
975
- // for a new message it's the last slot.
976
- let idx = 0
977
- for (const k of rec.messagesById.keys()) {
978
- if (k === id) break
979
- idx++
980
- }
981
- emitTurn(rec, msg, idx)
982
- }
983
-
984
- // Track the furthest transcript position we've ingested, so synthetic turns
985
- // can be placed just past it (liveTurnSeq).
986
- function rememberSeq(rec: SessionRecord, msg: OpenClawMessage): void {
987
- const seq = msg.__openclaw?.seq
988
- if (typeof seq === 'number' && seq > rec.lastDurableSeq) rec.lastDurableSeq = seq
989
- }
990
-
991
- async function seed(rec: SessionRecord): Promise<void> {
992
- const detail: OpenClawSessionDetail | null = await getOpenClawSessionMessages(
993
- rec.sessionId,
994
- rec.workspacePath,
995
- rec.agentId
996
- )
997
- if (detail?.messages) {
998
- for (const msg of detail.messages) {
999
- // Apply the same toolResult/role gating as live ingest for consistency.
1000
- const result = toolResultFromMessage(msg)
1001
- if (result) {
1002
- rec.results.set(result.id, result.info)
1003
- continue
1004
- }
1005
- if (msg.role !== 'user' && msg.role !== 'assistant') continue
1006
- const id = msg.__openclaw?.id
1007
- if (typeof id !== 'string') continue
1008
- rec.messagesById.set(id, msg)
1009
- rememberSeq(rec, msg)
1010
- }
1011
- rebuildView(rec)
1012
- }
1013
- rec.seeded = true
1014
- // Drain any frames that arrived during seed.
1015
- const queued = rec.pendingFrames
1016
- rec.pendingFrames = []
1017
- for (const m of queued) ingest(rec, m)
1018
- }
1019
-
1020
- async function ensureSubscribed(rec: SessionRecord): Promise<void> {
1021
- if (rec.ingestUnsubscribe) return
1022
- const gw = await getGateway()
1023
- await gw.ensureTopLevelSubscribed()
1024
- await gw.ensureSessionSubscribed(rec.sessionKey)
1025
-
1026
- rec.ingestUnsubscribe = gw.on((event, payload) => {
1027
- // All live frames must wait for seed — `sessions.changed phase:'start'`
1028
- // arriving before `messagesById` is populated would otherwise trigger
1029
- // `reconcileAfterRun` against an empty map (it would emit no owners but
1030
- // still pull the full transcript over RPC). Cleaner to gate everything.
1031
- if (!rec.seeded && event !== 'session.message') return
1032
- if (event === 'session.message') {
1033
- if (payload.sessionKey !== rec.sessionKey) return
1034
- const message = payload.message as OpenClawMessage | undefined
1035
- if (!message) return
1036
- if (!rec.seeded) {
1037
- rec.pendingFrames.push(message)
1038
- return
1039
- }
1040
- ingest(rec, message)
1041
- } else if (event === 'chat') {
1042
- if (payload.sessionKey !== rec.sessionKey) return
1043
- handleChatFrame(rec, payload)
1044
- } else if (event === 'session.tool') {
1045
- if (payload.sessionKey !== rec.sessionKey) return
1046
- handleToolFrame(rec, payload)
1047
- } else if (event === 'sessions.changed') {
1048
- // List refreshes apply to ANY session of the workspace's agent — cron
1049
- // spawns, subagents, titles, patches. (2026.6.x never emits
1050
- // `chat.title`; the other reasons cover title refreshes there.)
1051
- const reason = typeof payload.reason === 'string' ? payload.reason : undefined
1052
- if (reason && LIST_REFRESH_REASONS.has(reason)) broadcastSessionsChanged(rec)
1053
- if (payload.sessionKey !== rec.sessionKey) return
1054
- if (reason === 'compact') {
1055
- const notice = {
1056
- id: `openclaw:compact:${typeof payload.ts === 'number' ? payload.ts : Date.now()}`,
1057
- kind: 'compact' as const,
1058
- at: new Date().toISOString()
1059
- }
1060
- rec.view = applyEvent(rec.view, { kind: 'notice', notice })
1061
- broadcast(rec.workspaceId, { kind: 'notice', sessionId: rec.sessionId, notice })
1062
- }
1063
- // Frames embed the fresh session row — keep the applied-model cache
1064
- // truthful even when the session is patched outside moi. Run-phase frames
1065
- // nest it under `session`; `reason` frames flatten it onto the payload.
1066
- const row = (payload.session ?? payload) as
1067
- | { model?: unknown; modelProvider?: unknown; thinkingLevel?: unknown }
1068
- | undefined
1069
- if (row && typeof row.model === 'string' && typeof row.modelProvider === 'string') {
1070
- rec.wireModel = `${row.modelProvider}/${row.model}`
1071
- }
1072
- if (row && typeof row.thinkingLevel === 'string') rec.appliedThinking = row.thinkingLevel
1073
- // Every row carries the model's resolved thinking menu — the only source
1074
- // the effort picker has for it (thinking.ts).
1075
- if (row) recordOpenClawThinkingProfile(row)
1076
- const phase = payload.phase as string | undefined
1077
- const runId = payload.runId as string | undefined
1078
- if (reason === 'chat.dispatch-error') {
1079
- handleDispatchError(rec)
1080
- } else if (phase === 'start' && runId) {
1081
- setProcessing(rec, true, runId)
1082
- } else if ((phase === 'end' || phase === 'error') && runId) {
1083
- if (rec.activeRunId === runId) {
1084
- setProcessing(rec, false, null)
1085
- // Safety net: pick up any toolResult rows the live stream missed.
1086
- reconcileAfterRun(rec).catch(err =>
1087
- console.error('[openclaw-session] reconcile failed', err)
1088
- )
1089
- }
1090
- }
1091
- } else if (event === 'agent') {
1092
- if (payload.sessionKey !== rec.sessionKey) return
1093
- const stream = payload.stream as string | undefined
1094
- // Streaming text/reasoning fallback for gateways that don't emit `chat`
1095
- // delta frames (handleAgentStreamFrame no-ops when `chat` already owns
1096
- // the run's TEXT; reasoning is merged in alongside it). `thinking` is a
1097
- // second wire name for the reasoning stream — text-bearing on some
1098
- // runtimes, a bare `{ progressTokens }` heartbeat on others, which the
1099
- // empty-text check drops.
1100
- if (stream === 'assistant' || stream === 'reasoning' || stream === 'thinking') {
1101
- handleAgentStreamFrame(rec, payload)
1102
- return
1103
- }
1104
- // Tool activity for runs WE started (see handleToolFrame for why the
1105
- // same payload also arrives as `session.tool` for runs we only watch).
1106
- if (stream === 'tool') {
1107
- handleToolFrame(rec, payload)
1108
- return
1109
- }
1110
- // Reasoning also surfaces as an `item` frame of kind `analysis` —
1111
- // timing, no text.
1112
- if (stream === 'item') {
1113
- handleReasoningItemFrame(rec, payload)
1114
- return
1115
- }
1116
- // Backstop for run lifecycle — `sessions.changed` should already cover
1117
- // this, but `agent` lifecycle frames are the authoritative signal.
1118
- if (stream !== 'lifecycle') return
1119
- const runId = payload.runId as string | undefined
1120
- const data = payload.data as { phase?: string; error?: unknown } | undefined
1121
- const phase = data?.phase
1122
- if (phase === 'error' && runId) reportRunError(rec, runId, data?.error)
1123
- if (phase === 'start' && runId) setProcessing(rec, true, runId)
1124
- else if ((phase === 'end' || phase === 'error') && runId) {
1125
- if (rec.activeRunId === runId) {
1126
- setProcessing(rec, false, null)
1127
- reconcileAfterRun(rec).catch(err =>
1128
- console.error('[openclaw-session] reconcile failed', err)
1129
- )
1130
- }
1131
- }
1132
- }
1133
- })
1134
- }
1135
-
1136
- export async function getOrCreateOpenClawSession(input: {
1137
- workspaceId: string
1138
- workspacePath: string
1139
- agentId: string
1140
- sessionId: string
1141
- }): Promise<SessionRecord> {
1142
- const k = recKey(input.workspaceId, input.sessionId)
1143
- let rec = sessions.get(k)
1144
- if (rec) return rec
1145
-
1146
- // We use the gateway's session key. For OpenClaw the public API takes a
1147
- // sessionId, but RPCs need the composite key. `sessions.resolve` does that
1148
- // mapping; cache it on the record.
1149
- const gw = await getGateway()
1150
- const resolved = await gw
1151
- .rpc<{ key?: string }>('sessions.resolve', {
1152
- sessionId: input.sessionId,
1153
- agentId: input.agentId
1154
- })
1155
- .catch(() => null)
1156
- const sessionKey = resolved?.key
1157
- if (!sessionKey) throw new Error(`unable to resolve session ${input.sessionId}`)
1158
-
1159
- evictIdleIfNeeded()
1160
- rec = {
1161
- ...input,
1162
- sessionKey,
1163
- messagesById: new Map(),
1164
- results: new Map(),
1165
- view: emptyViewState(),
1166
- activeRunId: null,
1167
- seeded: false,
1168
- // Default to whole-block delivery like the other harnesses: a cold-opened
1169
- // (REST-ensured) live session must not broadcast previews until a send opts
1170
- // in (send sets `streamEnabled = input.stream === true`).
1171
- streamEnabled: false,
1172
- pendingFrames: [],
1173
- pendingUserEchoes: [],
1174
- liveTools: new Map(),
1175
- liveThinking: new Map(),
1176
- lastDurableSeq: 0,
1177
- liveTurnTick: 0
1178
- }
1179
- sessions.set(k, rec)
1180
- await ensureSubscribed(rec)
1181
- await seed(rec)
1182
- return rec
1183
- }
1184
-
1185
- // Evict one idle record to stay under the soft cap. A processing session is
1186
- // never evicted; if every record is busy we allow a temporary overflow rather
1187
- // than tearing down a live run.
1188
- function evictIdleIfNeeded(): void {
1189
- if (sessions.size < MAX_LIVE_SESSIONS) return
1190
- for (const rec of sessions.values()) {
1191
- if (!isOpenClawProcessing(rec.workspaceId, rec.sessionId)) {
1192
- teardownOpenClawSession(rec)
1193
- return
1194
- }
1195
- }
1196
- }
1197
-
1198
- // Cold-load helper for the REST events endpoint. If we already have a live
1199
- // session, return its current view materialized as StreamEvents (so it stays
1200
- // in sync with WS deltas the client will receive moments later). Otherwise
1201
- // fall back to the static `getOpenClawSessionMessages → toStreamEvents` path
1202
- // without spinning up a live subscription (subscription is only created when
1203
- // chat is sent or the live session is explicitly requested).
1204
- export function viewAsEvents(rec: SessionRecord): StreamEvent[] {
1205
- const evs: StreamEvent[] = []
1206
- for (const turn of rec.view.turns) evs.push({ kind: 'turn', turn })
1207
- if (rec.view.snapshot) evs.unshift({ kind: 'snapshot', snapshot: rec.view.snapshot })
1208
- for (const notice of rec.view.notices) evs.push({ kind: 'notice', notice })
1209
- if (rec.view.result) evs.push({ kind: 'result', result: rec.view.result })
1210
- return evs
1211
- }
1212
-
1213
- export async function sendOpenClawMessage(input: {
1214
- workspaceId: string
1215
- workspacePath: string
1216
- agentId: string
1217
- sessionId: string
1218
- isNew: boolean
1219
- content: string
1220
- // Upload ids. Basic support: the gateway's `sessions.send` only takes a string
1221
- // message, so we materialize each upload to a temp file and append the paths
1222
- // for the agent to read. Rich vision blocks await a gateway content-block API
1223
- // (see dev/file-uploads.md).
1224
- attachments?: MessageAttachment[]
1225
- optimisticId?: string
1226
- // Picker selections, applied to the gateway session via `sessions.patch`
1227
- // before the send (see applySessionSettings).
1228
- model?: string
1229
- effort?: string
1230
- // Client's live-typing toggle; previews are only broadcast when on.
1231
- stream?: boolean
1232
- // Structured moi context (lib/moi-context.ts), rendered and appended at
1233
- // the gateway send only — `content` stays clean so the optimistic-id echo
1234
- // rendezvous keeps matching on the user's text.
1235
- context?: MoiContext
1236
- }): Promise<void> {
1237
- await materializeAttachmentPaths(input.workspaceId, input.attachments)
1238
- const { text: content } = prepareAttachmentMessage(
1239
- input.workspaceId,
1240
- input.content,
1241
- input.attachments,
1242
- false
1243
- )
1244
- if (!content) return
1245
- return sendOpenClawMessageImpl({ ...input, content })
1246
- }
1247
-
1248
- // Apply the picker's model/effort to the gateway session before the send. The
1249
- // effort comes from that model's own learned menu (thinking.ts), so a rejection
1250
- // means the menu is stale — relearn from the error rather than failing the send.
1251
- // `reasoningLevel` rides along because it is the gateway's gate on emitting
1252
- // reasoning at all; it is only set when the user asked to think, so a session
1253
- // left at `off` keeps the gateway's default.
1254
- async function applySessionSettings(
1255
- rec: SessionRecord,
1256
- model: string | undefined,
1257
- effort: string | undefined
1258
- ): Promise<void> {
1259
- const patch: Record<string, unknown> = {}
1260
- // Patch the model only on a real change — `sessions.patch { model }` writes
1261
- // agent config, so it is not free.
1262
- //
1263
- // Both comparisons are exact: rows echo back the provider of the ref that was
1264
- // patched, and `anthropic/claude-sonnet-5` and `claude-cli/claude-sonnet-5`
1265
- // are separate catalog entries a user can pick between, so a switch between
1266
- // them has to reach the gateway.
1267
- const moved = rec.wireModel !== undefined && rec.wireModel !== rec.requestedModel
1268
- if (model && (model !== rec.requestedModel || moved)) patch.model = model
1269
- if (effort && effort !== rec.appliedThinking) patch.thinkingLevel = effort
1270
- const reasoning = effort && effort !== 'off' ? 'stream' : undefined
1271
- if (reasoning && reasoning !== rec.appliedReasoning) patch.reasoningLevel = reasoning
1272
- if (Object.keys(patch).length === 0) return
1273
- const gw = await getGateway()
1274
- try {
1275
- await gw.rpc('sessions.patch', { key: rec.sessionKey, ...patch })
1276
- } catch (err) {
1277
- // A level outside the model's menu is rejected by name; learn the real menu
1278
- // from the message so the picker self-corrects, then degrade rather than
1279
- // block the send. A rejected MODEL still throws — running on the wrong
1280
- // model is worse than not sending.
1281
- const relearned = recordOpenClawThinkingRejection(err)
1282
- if (typeof patch.thinkingLevel === 'string') {
1283
- console.warn(
1284
- `[openclaw-session] thinkingLevel "${patch.thinkingLevel}" rejected${
1285
- relearned ? ' (menu relearned from the gateway)' : ''
1286
- }; sending at the session's current level`,
1287
- err
1288
- )
1289
- const { thinkingLevel: _dropped, ...rest } = patch
1290
- if (Object.keys(rest).length === 0) return
1291
- await gw.rpc('sessions.patch', { key: rec.sessionKey, ...rest })
1292
- if (typeof rest.model === 'string') rec.requestedModel = rest.model
1293
- if (typeof rest.reasoningLevel === 'string') rec.appliedReasoning = rest.reasoningLevel
1294
- return
1295
- }
1296
- throw err
1297
- }
1298
- if (typeof patch.model === 'string') rec.requestedModel = patch.model
1299
- if (typeof patch.thinkingLevel === 'string') rec.appliedThinking = patch.thinkingLevel
1300
- if (typeof patch.reasoningLevel === 'string') rec.appliedReasoning = patch.reasoningLevel
1301
- }
1302
-
1303
- async function sendOpenClawMessageImpl(input: {
1304
- workspaceId: string
1305
- workspacePath: string
1306
- agentId: string
1307
- sessionId: string
1308
- isNew: boolean
1309
- content: string
1310
- optimisticId?: string
1311
- model?: string
1312
- effort?: string
1313
- stream?: boolean
1314
- context?: MoiContext
1315
- }): Promise<void> {
1316
- // New threads: ask the gateway to create one, then rename the client's
1317
- // tentative UUID to the real session id. Mirrors the Claude Code flow
1318
- // where the SDK echoes back a real `session_id` on first turn.
1319
- let realSessionId = input.sessionId
1320
- let rec: SessionRecord
1321
- try {
1322
- if (input.isNew) {
1323
- const gw = await getGateway()
1324
- const created = await gw.rpc<{ key?: string; sessionId?: string }>('sessions.create', {
1325
- agentId: input.agentId,
1326
- // Carry the model IN the create rather than patching it just before
1327
- // the send. `sessions.patch { model }` persists the pick into the
1328
- // agent's effective `model.primary`, and on 2026.7.2-beta.x that config
1329
- // write bumps the prepared-model-runtime generation and supersedes a run
1330
- // being admitted right then: `sessions.send` answers `status: 'started'`
1331
- // with a runId and the run is dead 2s later with `chat.dispatch-error`,
1332
- // so the first message of a new chat fails and the resend works.
1333
- //
1334
- // Re-tested on the pinned 2026.7.1 and the race does NOT reproduce
1335
- // there. Kept regardless: it is a round-trip fewer, the model belongs to
1336
- // the session from the start, and it keeps new chats working on the beta
1337
- // line. Only `model` may ride along — `sessions.create` rejects
1338
- // `thinkingLevel` (`unexpected property`, verified live), and effort is
1339
- // session-scoped anyway, so it stays a patch.
1340
- ...(input.model ? { model: input.model } : {})
1341
- })
1342
- if (created?.sessionId && created.sessionId !== input.sessionId) {
1343
- realSessionId = created.sessionId
1344
- await renameSessionReferences(
1345
- { id: input.workspaceId, path: input.workspacePath },
1346
- input.sessionId,
1347
- realSessionId
1348
- )
1349
- }
1350
- }
1351
- rec = await getOrCreateOpenClawSession({
1352
- workspaceId: input.workspaceId,
1353
- workspacePath: input.workspacePath,
1354
- agentId: input.agentId,
1355
- sessionId: realSessionId
1356
- })
1357
- // The create already carried the model, so record it as applied — otherwise
1358
- // `applySessionSettings` sees an empty cache on this brand-new record and
1359
- // issues exactly the pre-send `sessions.patch { model }` we just avoided.
1360
- // A fresh session has no wire row to seed the cache from (that path only
1361
- // fires once a row reports `modelProvider`/`model`), so this is the only
1362
- // thing standing between the fix and the race coming straight back.
1363
- if (input.isNew && input.model) rec.requestedModel = input.model
1364
- } catch (err) {
1365
- const message = err instanceof Error ? err.message : 'failed to start session'
1366
- broadcast(input.workspaceId, {
1367
- kind: 'error',
1368
- sessionId: realSessionId,
1369
- content: message
1370
- })
1371
- throw err
1372
- }
1373
-
1374
- // Omitted means whole-block delivery, same as the other harnesses.
1375
- rec.streamEnabled = input.stream === true
1376
-
1377
- const echo: { optimisticId: string; text: string; runId?: string } | null = input.optimisticId
1378
- ? { optimisticId: input.optimisticId, text: input.content }
1379
- : null
1380
- if (echo) {
1381
- rec.pendingUserEchoes.push(echo)
1382
- if (rec.pendingUserEchoes.length > MAX_PENDING_USER_ECHOES) {
1383
- rec.pendingUserEchoes.shift()
1384
- }
1385
- }
1386
- // Flip processing immediately — the run starts within ~100ms of `sessions.send`
1387
- // resolving, but we don't want the UI's send button to flicker.
1388
- setProcessing(rec, true, rec.activeRunId)
1389
-
1390
- try {
1391
- await applySessionSettings(rec, input.model, input.effort)
1392
- const gw = await getGateway()
1393
- const resp = await gw.rpc<{ runId?: string; status?: string }>('sessions.send', {
1394
- key: rec.sessionKey,
1395
- message: input.context
1396
- ? appendMoiContext(input.content, renderMoiContext(input.context))
1397
- : input.content
1398
- })
1399
- if (resp?.runId) {
1400
- setProcessing(rec, true, resp.runId)
1401
- // The durable user echo carries `<runId>:user` — arm the exact match.
1402
- if (echo) echo.runId = resp.runId
1403
- }
1404
- } catch (err) {
1405
- setProcessing(rec, false, null)
1406
- if (input.optimisticId) {
1407
- const idx = rec.pendingUserEchoes.findIndex(e => e.optimisticId === input.optimisticId)
1408
- if (idx >= 0) rec.pendingUserEchoes.splice(idx, 1)
1409
- }
1410
- const message = err instanceof Error ? err.message : 'send failed'
1411
- broadcast(rec.workspaceId, {
1412
- kind: 'error',
1413
- sessionId: rec.sessionId,
1414
- content: message
1415
- })
1416
- throw err
1417
- }
1418
- }
1419
-
1420
- export async function abortOpenClawRun(input: {
1421
- workspaceId: string
1422
- sessionId: string
1423
- }): Promise<void> {
1424
- const rec = sessions.get(recKey(input.workspaceId, input.sessionId))
1425
- if (!rec) return
1426
- try {
1427
- const gw = await getGateway()
1428
- await gw.rpc('sessions.abort', {
1429
- key: rec.sessionKey,
1430
- ...(rec.activeRunId ? { runId: rec.activeRunId } : {})
1431
- })
1432
- broadcast(rec.workspaceId, { kind: 'stopped', sessionId: rec.sessionId })
1433
- setProcessing(rec, false, null)
1434
- } catch (err) {
1435
- broadcast(rec.workspaceId, {
1436
- kind: 'error',
1437
- sessionId: rec.sessionId,
1438
- content: err instanceof Error ? err.message : 'abort failed'
1439
- })
1440
- // Stop is the user's escape hatch from a stuck spinner — clear the busy
1441
- // flag even when the abort RPC fails (the run may already be gone).
1442
- setProcessing(rec, false, null)
1443
- }
1444
- }
1445
-
1446
- // Read-side hook for the REST events endpoint. If a live session exists we
1447
- // return its current materialized view so it agrees with the WS deltas the
1448
- // client will start receiving on its next message. If no live session has
1449
- // been created yet, return null and let the caller use the static path.
1450
- export function getLiveOpenClawEvents(
1451
- workspaceId: string,
1452
- sessionId: string
1453
- ): StreamEvent[] | null {
1454
- const rec = sessions.get(recKey(workspaceId, sessionId))
1455
- if (!rec || !rec.seeded) return null
1456
- return viewAsEvents(rec)
1457
- }
1458
-
1459
- // Lazily ensure a session is live before serving its events. Used by the
1460
- // REST endpoint to make subsequent WS frames upsert into the same view.
1461
- export async function ensureOpenClawSessionLive(input: {
1462
- workspaceId: string
1463
- workspacePath: string
1464
- agentId: string
1465
- sessionId: string
1466
- }): Promise<StreamEvent[]> {
1467
- const rec = await getOrCreateOpenClawSession(input)
1468
- return viewAsEvents(rec)
1469
- }
1470
-
1471
- // Test seam. The README sanctions tests importing harness internals; the live
1472
- // `sessions` map is otherwise private and creating a real record needs a
1473
- // gateway. This seeds a minimal live record so teardown/idle behavior can be
1474
- // exercised in unit tests without a connection.
1475
- export function createOpenClawSessionForTest(input: {
1476
- workspaceId: string
1477
- sessionId: string
1478
- sessionKey: string
1479
- }): SessionRecord {
1480
- const rec: SessionRecord = {
1481
- workspaceId: input.workspaceId,
1482
- workspacePath: '/test-workspace',
1483
- agentId: 'test-agent',
1484
- sessionId: input.sessionId,
1485
- sessionKey: input.sessionKey,
1486
- messagesById: new Map(),
1487
- results: new Map(),
1488
- view: emptyViewState(),
1489
- activeRunId: null,
1490
- seeded: true,
1491
- streamEnabled: false,
1492
- pendingFrames: [],
1493
- pendingUserEchoes: [],
1494
- liveTools: new Map(),
1495
- liveThinking: new Map(),
1496
- lastDurableSeq: 0,
1497
- liveTurnTick: 0
1498
- }
1499
- sessions.set(recKey(input.workspaceId, input.sessionId), rec)
1500
- return rec
1501
- }
1502
-
1503
- // Test seam: put a record into the processing state a send would leave it in,
1504
- // so a test can assert that a terminal frame clears it.
1505
- export function markProcessingForTest(rec: SessionRecord, runId: string): void {
1506
- setProcessing(rec, true, runId)
1507
- }
1508
-
1509
- // Test seam: is a live record held for this (workspaceId, sessionId)?
1510
- export function hasOpenClawLiveSessionForTest(workspaceId: string, sessionId: string): boolean {
1511
- return sessions.has(recKey(workspaceId, sessionId))
1512
- }