moi-computer 0.13.1-next.3 → 0.13.1-next.5

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