moi-computer 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/bunfig.toml +4 -0
  2. package/client/api/workspaces.ts +277 -6
  3. package/client/assets/mcp/agentation.png +0 -0
  4. package/client/assets/mcp/airtable.png +0 -0
  5. package/client/assets/mcp/apollo.png +0 -0
  6. package/client/assets/mcp/asana.png +0 -0
  7. package/client/assets/mcp/box.png +0 -0
  8. package/client/assets/mcp/chrome.svg +33 -0
  9. package/client/assets/mcp/clickup.png +0 -0
  10. package/client/assets/mcp/cloudflare.png +0 -0
  11. package/client/assets/mcp/context7.png +0 -0
  12. package/client/assets/mcp/datadog.png +0 -0
  13. package/client/assets/mcp/dropbox.png +0 -0
  14. package/client/assets/mcp/elevenlabs.png +0 -0
  15. package/client/assets/mcp/exa.png +0 -0
  16. package/client/assets/mcp/firecrawl.png +0 -0
  17. package/client/assets/mcp/gmail.png +0 -0
  18. package/client/assets/mcp/googlecalendar.png +0 -0
  19. package/client/assets/mcp/googledrive.png +0 -0
  20. package/client/assets/mcp/grafana.png +0 -0
  21. package/client/assets/mcp/huggingface.png +0 -0
  22. package/client/assets/mcp/intercom.png +0 -0
  23. package/client/assets/mcp/monday.png +0 -0
  24. package/client/assets/mcp/mongodb.png +0 -0
  25. package/client/assets/mcp/paper.png +0 -0
  26. package/client/assets/mcp/paypal.png +0 -0
  27. package/client/assets/mcp/perplexity.png +0 -0
  28. package/client/assets/mcp/postgresql.png +0 -0
  29. package/client/assets/mcp/posthog.png +0 -0
  30. package/client/assets/mcp/puppeteer.png +0 -0
  31. package/client/assets/mcp/railway.png +0 -0
  32. package/client/assets/mcp/redis.png +0 -0
  33. package/client/assets/mcp/salesforce.png +0 -0
  34. package/client/assets/mcp/shopify.png +0 -0
  35. package/client/assets/mcp/snowflake.png +0 -0
  36. package/client/assets/mcp/telegram.png +0 -0
  37. package/client/assets/mcp/twilio.png +0 -0
  38. package/client/assets/mcp/zapier.png +0 -0
  39. package/client/components/App.tsx +7 -1
  40. package/client/components/ChatInput.tsx +194 -13
  41. package/client/components/ChatPanel.tsx +116 -47
  42. package/client/components/ChatPopup.tsx +1 -1
  43. package/client/components/IconMcp.tsx +21 -0
  44. package/client/components/McpMenu.tsx +125 -0
  45. package/client/components/ModelPicker.tsx +147 -0
  46. package/client/components/Scratchpad.tsx +775 -0
  47. package/client/components/ShimmerText.tsx +20 -0
  48. package/client/components/ThreadSelector.tsx +2 -2
  49. package/client/components/TurnView.tsx +111 -531
  50. package/client/components/WidgetShell.tsx +1 -1
  51. package/client/components/WorkspacesPage.tsx +12 -4
  52. package/client/components/layout/SidebarLayout.tsx +18 -9
  53. package/client/components/playground/ToolCallsPage.tsx +81 -0
  54. package/client/components/routes/workspace/[id].tsx +534 -141
  55. package/client/components/routes/workspace/create.tsx +155 -0
  56. package/client/components/settings/IconPicker.tsx +590 -0
  57. package/client/components/settings/SettingsPages.tsx +307 -0
  58. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  59. package/client/components/tool-group/CodeBlock.tsx +41 -0
  60. package/client/components/tool-group/Collapse.tsx +28 -0
  61. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  62. package/client/components/tool-group/SubagentCard.tsx +135 -0
  63. package/client/components/tool-group/TimelineRow.tsx +147 -0
  64. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  65. package/client/components/tool-group/ToolOutput.tsx +139 -0
  66. package/client/components/tool-group/detect.ts +93 -0
  67. package/client/components/tool-group/fixtures.ts +315 -0
  68. package/client/components/tool-group/format.ts +211 -0
  69. package/client/components/tool-group/index.ts +9 -0
  70. package/client/components/ui/dialog.tsx +58 -0
  71. package/client/components/ui/hover-card.tsx +44 -0
  72. package/client/components/ui/switch.tsx +23 -0
  73. package/client/components/ui/tooltip.tsx +54 -0
  74. package/client/externalize-react.ts +6 -0
  75. package/client/hooks/useApplet.ts +117 -0
  76. package/client/hooks/useChat.ts +162 -62
  77. package/client/hooks/useMeiEvents.ts +9 -2
  78. package/client/hooks/useStickToBottom.ts +86 -0
  79. package/client/hooks/useWorkspaceTheme.ts +8 -2
  80. package/client/index.css +48 -2
  81. package/client/index.html +9 -5
  82. package/client/index.tsx +29 -2
  83. package/client/lib/WorkspaceContext.tsx +5 -8
  84. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  85. package/client/lib/applet-cache.ts +54 -0
  86. package/client/lib/connection.ts +237 -0
  87. package/client/lib/flags.ts +10 -0
  88. package/client/lib/mcp-icons.ts +142 -10
  89. package/client/lib/preview-turn.ts +37 -0
  90. package/client/lib/render-icon.ts +173 -0
  91. package/client/lib/scratch-executor.ts +20 -0
  92. package/client/lib/uploads.ts +18 -0
  93. package/client/main.tsx +5 -0
  94. package/client/store/live.ts +282 -0
  95. package/client/structured-clone-shim.ts +14 -0
  96. package/client/theme.css +2 -2
  97. package/client/vendor/emojibase/en/data.json +1 -0
  98. package/client/vendor/emojibase/en/messages.json +1 -0
  99. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  100. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  101. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  102. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  103. package/client/vendor/react/development/_impl/react.js +863 -0
  104. package/client/vendor/react/development/react-dom-client.js +6 -0
  105. package/client/vendor/react/development/react-dom.js +17 -0
  106. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  107. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  108. package/client/vendor/react/development/react.js +47 -0
  109. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  110. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  111. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  112. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  113. package/client/vendor/react/production/_impl/react.js +428 -0
  114. package/client/vendor/react/production/react-dom-client.js +6 -0
  115. package/client/vendor/react/production/react-dom.js +17 -0
  116. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  117. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  118. package/client/vendor/react/production/react.js +47 -0
  119. package/dist/agentation-4s0nn45p.png +0 -0
  120. package/dist/airtable-hsa66v6q.png +0 -0
  121. package/dist/apollo-2ed5dy2d.png +0 -0
  122. package/dist/asana-tvgtwbx2.png +0 -0
  123. package/dist/box-w3n36t5g.png +0 -0
  124. package/dist/chrome-tspm94rw.svg +33 -0
  125. package/dist/chunk-kc6e9nd4.css +1 -0
  126. package/dist/chunk-yf3p7qg7.js +673 -0
  127. package/dist/clickup-qqrqqvqb.png +0 -0
  128. package/dist/cloudflare-j9p931v6.png +0 -0
  129. package/dist/context7-8ht0xjfy.png +0 -0
  130. package/dist/datadog-70ne3yzt.png +0 -0
  131. package/dist/dropbox-4m5s9mgr.png +0 -0
  132. package/dist/elevenlabs-2nzzej1t.png +0 -0
  133. package/dist/exa-qqj3vr0x.png +0 -0
  134. package/dist/firecrawl-w2t8nehx.png +0 -0
  135. package/dist/gmail-sg6a5v3x.png +0 -0
  136. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  137. package/dist/googledrive-6s8xyab7.png +0 -0
  138. package/dist/grafana-1yfsnwr6.png +0 -0
  139. package/dist/huggingface-kxzaxj83.png +0 -0
  140. package/dist/index.html +10 -6
  141. package/dist/intercom-td763jt8.png +0 -0
  142. package/dist/monday-jdbs4wwf.png +0 -0
  143. package/dist/mongodb-emzxvhd5.png +0 -0
  144. package/dist/paper-zbt34fab.png +0 -0
  145. package/dist/paypal-kwwf7xsc.png +0 -0
  146. package/dist/perplexity-4y63rxvj.png +0 -0
  147. package/dist/postgresql-qsspbsr1.png +0 -0
  148. package/dist/posthog-sphppc4w.png +0 -0
  149. package/dist/puppeteer-2xjt1a9b.png +0 -0
  150. package/dist/railway-834de8d2.png +0 -0
  151. package/dist/redis-spm6w2m1.png +0 -0
  152. package/dist/salesforce-1mk56v4z.png +0 -0
  153. package/dist/shopify-90dadaav.png +0 -0
  154. package/dist/snowflake-hfpykpgy.png +0 -0
  155. package/dist/telegram-v6tjyrs7.png +0 -0
  156. package/dist/twilio-dpyjdwpj.png +0 -0
  157. package/dist/zapier-p67qfch0.png +0 -0
  158. package/lib/attachment-note.ts +48 -0
  159. package/lib/claude-adapter.ts +219 -29
  160. package/lib/format.ts +32 -0
  161. package/lib/types.ts +314 -6
  162. package/package.json +10 -5
  163. package/server/CLAUDE.md +3 -0
  164. package/server/agent.ts +25 -118
  165. package/server/api.ts +593 -0
  166. package/server/applets.ts +396 -0
  167. package/server/build-applet.ts +580 -0
  168. package/server/cc-session.ts +611 -0
  169. package/server/cli-colors.ts +17 -0
  170. package/server/cli-ui.ts +52 -0
  171. package/server/cli.ts +964 -72
  172. package/server/control.ts +166 -19
  173. package/server/debug.ts +10 -0
  174. package/server/events.ts +24 -0
  175. package/server/functions-worker.ts +18 -2
  176. package/server/functions.ts +59 -12
  177. package/server/icon.ts +13 -0
  178. package/server/layout.ts +25 -3
  179. package/server/mcp.ts +125 -0
  180. package/server/moi-scaffold.ts +85 -0
  181. package/server/openclaw-session.ts +41 -10
  182. package/server/openclaw.ts +22 -0
  183. package/server/preview.ts +70 -0
  184. package/server/registry.ts +32 -2
  185. package/server/scratchpad-executor.ts +380 -0
  186. package/server/scratchpad-relay.ts +45 -0
  187. package/server/scratchpad.ts +171 -0
  188. package/server/skill-version.ts +146 -0
  189. package/server/skills-template.ts +6 -1
  190. package/server/state.ts +22 -36
  191. package/server/static.ts +23 -0
  192. package/server/status.ts +94 -0
  193. package/server/thread-config.ts +125 -0
  194. package/server/uploads.ts +0 -0
  195. package/server/vendor.ts +63 -0
  196. package/server/views.ts +0 -0
  197. package/server/web.ts +108 -253
  198. package/server/widgets.ts +52 -142
  199. package/server/workspace-config.ts +37 -0
  200. package/server/workspace-env.ts +407 -0
  201. package/server/workspace-init.ts +66 -0
  202. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  203. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  204. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  205. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  206. package/client/hooks/useWidget.ts +0 -72
  207. package/client/hooks/useWidgetList.ts +0 -30
  208. package/client/lib/ws.ts +0 -129
  209. package/client/store/chat.tsx +0 -162
  210. package/dist/chunk-4615fa69.js +0 -67
  211. package/dist/chunk-582xmy05.css +0 -1
  212. package/server/build-widget.ts +0 -343
  213. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  214. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
package/server/web.ts CHANGED
@@ -1,88 +1,68 @@
1
- import { existsSync } from 'node:fs'
2
- import { join, sep } from 'node:path'
3
-
4
1
  import type { ClientMessage } from '@/lib/types'
5
2
 
6
3
  import index from '../client/index.html'
7
- import { getMcpStatus, handleChat, stopChat } from './agent'
4
+ import { api } from './api'
5
+ import {
6
+ getCCRunningSessions,
7
+ interruptCCSession,
8
+ killAllCCSessions,
9
+ sendCCMessage
10
+ } from './cc-session'
8
11
  import { PORT } from './constants'
9
12
  import { control } from './control'
10
- import { callFunction, killAllWorkers } from './functions'
11
- import { getWorkspacePreview, loadLayout, saveLayout } from './layout'
12
- import { getOpenClawSessionMessages, getOpenClawSessions } from './openclaw'
13
- import { toSessionInfo, toStreamEvents } from './openclaw-adapter'
13
+ import { EVENTS_TOPIC, setEventServer } from './events'
14
+ import { killAllWorkers } from './functions'
15
+ import { resolveScratchOp } from './scratchpad-relay'
14
16
  import {
15
17
  abortOpenClawRun,
16
- ensureOpenClawSessionLive,
17
- getLiveOpenClawEvents,
18
- getOpenClawProcessingSessions,
18
+ getOpenClawRunningSessions,
19
19
  sendOpenClawMessage
20
20
  } from './openclaw-session'
21
- import {
22
- discoverWorkspaces,
23
- getWorkspace,
24
- listWorkspaces,
25
- registerWorkspace,
26
- removeWorkspace
27
- } from './registry'
28
- import {
29
- addClient,
30
- getProcessingSessions,
31
- getSessionEvents,
32
- getSessions,
33
- removeClient,
34
- sendToClient
35
- } from './state'
36
- import { listWidgets, serveWidget } from './widgets'
21
+ import { getWorkspace } from './registry'
22
+ import { addClient, removeClient, sendToClient } from './state'
23
+ import { distShell, prebuilt } from './static'
24
+ import { renderStatus } from './status'
25
+ import { serveVendorEmojibase, serveVendorReact } from './vendor'
37
26
 
38
- const MEI_TOPIC = 'mei'
39
-
40
- type WsData = { channel: 'chat' | 'mei'; workspaceId: string }
27
+ type WsData = { channel: 'chat' | 'events'; workspaceId: string }
41
28
 
42
29
  function isClientMessage(value: unknown): value is ClientMessage {
43
30
  if (typeof value !== 'object' || value === null || !('type' in value)) return false
44
31
  const v = value as {
45
32
  type: string
33
+ workspaceId?: unknown
46
34
  sessionId?: unknown
47
35
  content?: unknown
48
36
  isNew?: unknown
49
37
  optimisticId?: unknown
38
+ model?: unknown
39
+ effort?: unknown
40
+ stream?: unknown
41
+ attachments?: unknown
42
+ opId?: unknown
50
43
  }
51
44
  if (v.type === 'chat')
52
45
  return (
46
+ typeof v.workspaceId === 'string' &&
53
47
  typeof v.content === 'string' &&
54
48
  typeof v.sessionId === 'string' &&
55
49
  typeof v.isNew === 'boolean' &&
56
- (v.optimisticId === undefined || typeof v.optimisticId === 'string')
50
+ (v.optimisticId === undefined || typeof v.optimisticId === 'string') &&
51
+ (v.model === undefined || typeof v.model === 'string') &&
52
+ (v.effort === undefined || typeof v.effort === 'string') &&
53
+ (v.stream === undefined || typeof v.stream === 'boolean') &&
54
+ (v.attachments === undefined ||
55
+ (Array.isArray(v.attachments) && v.attachments.every(a => typeof a === 'string')))
57
56
  )
58
- if (v.type === 'stop') return typeof v.sessionId === 'string'
57
+ if (v.type === 'stop') return typeof v.workspaceId === 'string' && typeof v.sessionId === 'string'
58
+ if (v.type === 'scratchpad:op-result') return typeof v.opId === 'string'
59
59
  return false
60
60
  }
61
61
 
62
- // Production (published/global install) ships a prebuilt client in `dist/`
63
- // (see scripts/build-client.ts). When present we serve it as static files,
64
- // because Bun's runtime bundler won't run plugins on source under the global
65
- // install tree. In dev there is no `dist/`, so we fall back to the imported
66
- // HTML route + Bun.serve's live bundler (HMR). `import.meta.dir` is server/.
67
- const DIST_DIR = join(import.meta.dir, '..', 'dist')
68
- const DIST_INDEX = join(DIST_DIR, 'index.html')
69
- // Serve prebuilt static assets when `dist/` exists — but never in dev mode
70
- // (MOI_DEV is set by the dev supervisor), so `bun run dev` always uses the
71
- // live bundler + HMR even if a stale `dist/` is lying around the working tree.
72
- const serveStatic = !process.env.MOI_DEV && existsSync(DIST_INDEX)
73
-
74
- // The SPA shell: prebuilt index.html in prod, the live-bundled HTML in dev.
75
- const shell = serveStatic ? () => new Response(Bun.file(DIST_INDEX)) : index
76
-
77
- // Serve a hashed asset (`/chunk-….js`, `/favicon-….png`, …) from `dist/`.
78
- // Returns null when the path isn't a real file under dist (path-traversal safe).
79
- async function serveDistAsset(pathname: string): Promise<Response | null> {
80
- if (!serveStatic) return null
81
- const filePath = join(DIST_DIR, pathname)
82
- if (filePath !== DIST_DIR && !filePath.startsWith(DIST_DIR + sep)) return null
83
- const file = Bun.file(filePath)
84
- return (await file.exists()) ? new Response(file) : null
85
- }
62
+ // The SPA shell: prebuilt index.html in prod (served statically), the
63
+ // live-bundled HTML import in dev (Bun.serve's bundler + HMR). The HTML import
64
+ // stays here, in the routes table, so Bun's dev bundler keys off it.
65
+ const shell = prebuilt ? distShell : index
86
66
 
87
67
  type Upgradable = { upgrade(req: Request, opts: { data: WsData }): boolean }
88
68
 
@@ -92,173 +72,60 @@ function upgrade(server: Upgradable, req: Request, data: WsData) {
92
72
  : new Response('Upgrade failed', { status: 500 })
93
73
  }
94
74
 
75
+ // Bun owns the fullstack surface: the HTML shell + dev bundler/HMR, and the two
76
+ // WebSocket channels (which need Bun's native `server.upgrade` + pub/sub). Every
77
+ // HTTP API route is delegated to the Hono app (`./api`) via `fetch`.
95
78
  export const app = Bun.serve<WsData>({
96
79
  port: PORT,
97
80
  hostname: process.env.HOST ?? '127.0.0.1',
98
81
  // HMR only in dev; prod serves prebuilt static assets (no bundler).
99
- development: serveStatic ? false : { hmr: true },
82
+ development: prebuilt ? false : { hmr: true },
100
83
  routes: {
101
- // Client-side routes — serve the SPA shell
84
+ // Plain-text server introspection — live sessions held in cache, connected
85
+ // tabs, last message per thread. A quick peek into the process when a chat
86
+ // seems stuck. Served as text/plain so curl/browser both show it raw.
87
+ '/status': () =>
88
+ new Response(renderStatus(), {
89
+ headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }
90
+ }),
91
+
92
+ // Locally-vendored React ESM (offline; no CDN). The importmap in
93
+ // client/index.html points here; the handler picks dev/prod per env.
94
+ '/vendor/react/*': req => serveVendorReact(req),
95
+
96
+ // Vendored emojibase-data for the settings emoji picker (offline; no CDN).
97
+ '/vendor/emojibase/*': req => serveVendorEmojibase(req),
98
+
99
+ // Client-side routes — serve the SPA shell.
102
100
  '/': shell,
103
101
  '/playground': shell,
102
+ '/playground/*': shell,
104
103
  '/workspace/*': shell,
105
104
 
106
- // Workspace registry API
107
- '/api/workspaces': async req => {
108
- if (req.method === 'GET') return Response.json(await listWorkspaces())
109
- if (req.method === 'POST') {
110
- const body = await req.json()
111
- if (!body?.path) return new Response('Missing path', { status: 400 })
112
- const rawType = body?.type
113
- const type = rawType === 'claude-code' || rawType === 'openclaw' ? rawType : undefined
114
- const entry = await registerWorkspace(String(body.path), {
115
- type,
116
- name: typeof body?.name === 'string' ? body.name : undefined,
117
- agentId: typeof body?.agentId === 'string' ? body.agentId : undefined,
118
- isDefault: typeof body?.isDefault === 'boolean' ? body.isDefault : undefined,
119
- lastRunAt: typeof body?.lastRunAt === 'string' ? body.lastRunAt : undefined
120
- })
121
- return Response.json(entry, { status: 201 })
122
- }
123
- return new Response('Method not allowed', { status: 405 })
124
- },
125
- '/api/workspaces/discover': async () => Response.json(await discoverWorkspaces()),
126
- '/api/workspaces/:id/preview': async req => {
127
- const ws = await getWorkspace(req.params.id)
128
- if (!ws) return Response.json({ cols: 4, items: [] })
129
- return Response.json(await getWorkspacePreview(ws.path))
130
- },
131
- '/api/workspaces/:id/layout': async req => {
132
- const ws = await getWorkspace(req.params.id)
133
- if (!ws) return new Response('Workspace not found', { status: 404 })
134
- if (req.method === 'GET') {
135
- return Response.json({
136
- ...(await loadLayout(ws.path)),
137
- cwd: ws.path,
138
- name: ws.name,
139
- agentId: ws.agentId
140
- })
141
- }
142
- if (req.method === 'PUT') {
143
- const body = await req.json()
144
- if (!body || body.version !== 1) return new Response('Bad request', { status: 400 })
145
- await saveLayout(body, ws.path)
146
- return new Response(null, { status: 204 })
147
- }
148
- return new Response('Method not allowed', { status: 405 })
149
- },
150
- '/api/workspaces/:id/widgets': async req => {
151
- const ws = await getWorkspace(req.params.id)
152
- if (!ws) return new Response('Workspace not found', { status: 404 })
153
- return listWidgets(ws.path)
154
- },
155
- '/api/workspaces/:id/sessions': async req => {
156
- const ws = await getWorkspace(req.params.id)
157
- if (!ws) return new Response('Workspace not found', { status: 404 })
158
- if (ws.type === 'openclaw') {
159
- const rows = await getOpenClawSessions(ws.path, ws.agentId)
160
- return Response.json(rows.map(r => toSessionInfo(r, ws.path)))
161
- }
162
- return Response.json(await getSessions(ws.path))
163
- },
164
- // Widget bundle: the compiled ESM module for one widget, dynamically
165
- // imported by the client (useWidget). Sits beside the GET .../widgets list
166
- // above — the exact path lists, `/*` serves a bundle.
167
- '/api/workspaces/:id/widgets/*': async req => {
168
- const ws = await getWorkspace(req.params.id)
169
- if (!ws) return new Response('Workspace not found', { status: 404 })
170
- const name = new URL(req.url).pathname.split('/').pop()?.replace(/\.js$/, '')
171
- return name ? serveWidget(name, ws.path) : new Response('Not found', { status: 404 })
172
- },
173
- '/api/workspaces/:id/sessions/:sessionId/events': async req => {
174
- const ws = await getWorkspace(req.params.id)
175
- if (!ws) return new Response('Workspace not found', { status: 404 })
176
- if (ws.type === 'openclaw') {
177
- // Prefer the live view if we already hold one — keeps REST + WS in
178
- // agreement for any reload that lands while a run is active. The
179
- // first cold call also primes the live subscription so subsequent
180
- // WS frames upsert into the same view.
181
- const live = getLiveOpenClawEvents(req.params.id, req.params.sessionId)
182
- if (live) return Response.json(live)
183
- if (ws.agentId) {
184
- try {
185
- const evs = await ensureOpenClawSessionLive({
186
- workspaceId: req.params.id,
187
- workspacePath: ws.path,
188
- agentId: ws.agentId,
189
- sessionId: req.params.sessionId
190
- })
191
- return Response.json(evs)
192
- } catch {
193
- // fall through to static path
194
- }
195
- }
196
- const preview = await getOpenClawSessionMessages(req.params.sessionId, ws.path, ws.agentId)
197
- return Response.json(toStreamEvents(preview))
198
- }
199
- return Response.json(await getSessionEvents(req.params.sessionId, ws.path))
200
- },
201
- '/api/workspaces/:id/mcp': async req => {
202
- const ws = await getWorkspace(req.params.id)
203
- if (!ws) return new Response('Workspace not found', { status: 404 })
204
- return Response.json(await getMcpStatus(ws.path))
205
- },
105
+ // Chat websocket — app-wide (one per client, not per workspace). Each chat
106
+ // frame carries its own workspaceId.
107
+ '/ws': (req, server) => upgrade(server, req, { channel: 'chat', workspaceId: '' }),
108
+
206
109
  // Live widget-event stream (build/refresh pushes). A static path, so Bun
207
- // routes it ahead of the `/api/workspaces/:id` param route below; the
208
- // upgrade happens in-handler via the route's `server` argument.
110
+ // routes it ahead of the Hono-served `/api/workspaces/:id`; the upgrade
111
+ // happens in-handler via the route's `server` argument.
209
112
  '/api/workspaces/ws': (req, server) =>
210
- upgrade(server, req, { channel: 'mei', workspaceId: '' }),
211
- '/api/workspaces/:id': async req => {
212
- if (req.method === 'DELETE') {
213
- const ok = await removeWorkspace(req.params.id)
214
- if (!ok) return new Response('Workspace not found', { status: 404 })
215
- return new Response(null, { status: 204 })
216
- }
217
- return new Response('Method not allowed', { status: 405 })
218
- },
219
-
220
- // Widget RPC: a widget bundle POSTs here to call one of its `.server.ts`
221
- // functions. Kept on its own internal `/_rpc/` prefix, off the public API.
222
- '/_rpc/:wid/fn/*': async req => {
223
- if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
224
- const ws = await getWorkspace(req.params.wid)
225
- if (!ws) return new Response('Workspace not found', { status: 404 })
226
- const prefix = `/_rpc/${req.params.wid}/fn/`
227
- const tail = new URL(req.url).pathname.slice(prefix.length)
228
- return handleFunctionCall(req, tail, ws.path)
229
- }
230
- },
231
- async fetch(req, server) {
232
- const url = new URL(req.url)
233
- // Chat websocket (per-workspace). The widget-event websocket lives in the
234
- // routes table at /api/workspaces/ws.
235
- if (url.pathname === '/ws') {
236
- const workspaceId = url.searchParams.get('workspace') ?? ''
237
- return upgrade(server, req, { channel: 'chat', workspaceId })
238
- }
239
- // Prod: serve prebuilt hashed assets (/chunk-….js, /favicon-….png, …).
240
- // No-op in dev (the live bundler serves assets via the HTML route).
241
- if (req.method === 'GET') {
242
- const asset = await serveDistAsset(url.pathname)
243
- if (asset) return asset
244
- }
245
- return new Response('Not found', { status: 404 })
113
+ upgrade(server, req, { channel: 'events', workspaceId: '' })
246
114
  },
115
+ // Anything not matched above (the whole HTTP API + prod static assets + 404)
116
+ // is handled by Hono.
117
+ fetch: req => api.fetch(req),
247
118
  websocket: {
248
119
  open(ws) {
249
120
  if (ws.data.channel === 'chat') {
250
- addClient(ws.data.workspaceId, ws)
251
- const seen = new Set<string>()
252
- for (const sid of getProcessingSessions(ws.data.workspaceId)) {
253
- seen.add(sid)
254
- sendToClient(ws, { type: 'status', sessionId: sid, processing: true })
255
- }
256
- for (const sid of getOpenClawProcessingSessions(ws.data.workspaceId)) {
257
- if (seen.has(sid)) continue
258
- sendToClient(ws, { type: 'status', sessionId: sid, processing: true })
259
- }
121
+ addClient(ws)
122
+ // Authoritative snapshot of every running session (CC + OpenClaw) so the
123
+ // client can light/clear spinners correctly even for runs whose status
124
+ // transitions it missed while disconnected.
125
+ const running = [...getCCRunningSessions(), ...getOpenClawRunningSessions()]
126
+ sendToClient(ws, { type: 'status_snapshot', running })
260
127
  } else {
261
- ws.subscribe(MEI_TOPIC)
128
+ ws.subscribe(EVENTS_TOPIC)
262
129
  }
263
130
  },
264
131
  async message(ws, message) {
@@ -267,77 +134,64 @@ export const app = Bun.serve<WsData>({
267
134
  const data = JSON.parse(String(message))
268
135
  if (!isClientMessage(data)) return
269
136
 
270
- if (data.type === 'chat' && data.content?.trim()) {
271
- const workspace = await getWorkspace(ws.data.workspaceId)
137
+ // Allow a message that carries only attachments (no text).
138
+ if (data.type === 'chat' && (data.content?.trim() || data.attachments?.length)) {
139
+ const workspace = await getWorkspace(data.workspaceId)
272
140
  if (!workspace) return
273
141
  if (workspace.type === 'openclaw' && workspace.agentId) {
274
142
  sendOpenClawMessage({
275
- workspaceId: ws.data.workspaceId,
143
+ workspaceId: data.workspaceId,
276
144
  workspacePath: workspace.path,
277
145
  agentId: workspace.agentId,
278
146
  sessionId: data.sessionId,
279
147
  isNew: data.isNew,
280
148
  content: data.content.trim(),
149
+ attachments: data.attachments,
281
150
  optimisticId: data.optimisticId
282
151
  })
283
152
  } else {
284
- handleChat(
285
- data.content.trim(),
286
- data.sessionId,
287
- data.isNew,
288
- ws.data.workspaceId,
289
- workspace.path,
290
- data.optimisticId
291
- )
153
+ // `stream` is only wired for the Claude Code path; the OpenClaw
154
+ // branch above never receives it (unsupported provider).
155
+ sendCCMessage({
156
+ workspaceId: data.workspaceId,
157
+ workspacePath: workspace.path,
158
+ sessionId: data.sessionId,
159
+ isNew: data.isNew,
160
+ content: data.content.trim(),
161
+ attachments: data.attachments,
162
+ optimisticId: data.optimisticId,
163
+ model: data.model,
164
+ effort: data.effort,
165
+ stream: data.stream
166
+ })
292
167
  }
293
168
  }
294
169
  if (data.type === 'stop') {
295
- const workspace = await getWorkspace(ws.data.workspaceId)
170
+ const workspace = await getWorkspace(data.workspaceId)
296
171
  if (workspace?.type === 'openclaw') {
297
- abortOpenClawRun({ workspaceId: ws.data.workspaceId, sessionId: data.sessionId })
172
+ abortOpenClawRun({ workspaceId: data.workspaceId, sessionId: data.sessionId })
298
173
  } else {
299
- stopChat(data.sessionId, ws.data.workspaceId)
174
+ interruptCCSession(data.workspaceId, data.sessionId)
300
175
  }
301
176
  }
177
+ // A tab's reply to a relayed Scratchpad op — settle the pending CLI
178
+ // request (first reply wins; later/duplicate replies are ignored).
179
+ if (data.type === 'scratchpad:op-result') {
180
+ resolveScratchOp(data.opId, data.result, data.error)
181
+ }
302
182
  } catch {}
303
183
  },
304
184
  close(ws) {
305
- if (ws.data.channel === 'chat') removeClient(ws.data.workspaceId, ws)
306
- else ws.unsubscribe(MEI_TOPIC)
185
+ if (ws.data.channel === 'chat') removeClient(ws)
186
+ else ws.unsubscribe(EVENTS_TOPIC)
307
187
  }
308
188
  }
309
189
  })
310
190
 
311
- async function handleFunctionCall(
312
- req: Request,
313
- tail: string,
314
- workspacePath: string
315
- ): Promise<Response> {
316
- const parts = tail.split('/')
317
- if (parts.length !== 2) return new Response('Bad request', { status: 400 })
318
-
319
- const [module, name] = parts
320
- if (!/^[a-zA-Z0-9_$-]+$/.test(module) || !/^[a-zA-Z0-9_$]+$/.test(name)) {
321
- return new Response('Invalid module or function name', { status: 400 })
322
- }
323
-
324
- try {
325
- const contentLength = Number(req.headers.get('content-length') ?? 0)
326
- if (contentLength > 1_000_000) {
327
- return new Response('Request body too large', { status: 413 })
328
- }
329
- const args = await req.text()
330
- const result = await callFunction(module, name, args, workspacePath)
331
- return new Response(result, { headers: { 'Content-Type': 'application/json' } })
332
- } catch (err) {
333
- const message = err instanceof Error ? err.message : 'Unknown error'
334
- return new Response(message, { status: 500 })
335
- }
336
- }
337
-
338
- export function publishMei(msg: unknown) {
339
- app.publish(MEI_TOPIC, JSON.stringify(msg))
340
- }
191
+ // Wire the live-event publisher (`publishEvent`) to this server instance now
192
+ // that it exists. Kept in ./events so control.ts and ./api can publish without
193
+ // importing web.ts (which binds ports on load).
194
+ setEventServer(app)
341
195
 
342
196
  // Graceful shutdown. In dev the supervisor sends SIGTERM on server-file
343
197
  // changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the
@@ -349,6 +203,7 @@ function shutdown() {
349
203
  try {
350
204
  control.stop(true)
351
205
  } catch {}
206
+ killAllCCSessions()
352
207
  killAllWorkers()
353
208
  process.exit(0)
354
209
  }