moi-computer 0.13.1-next.2 → 0.13.1-next.4

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 (109) hide show
  1. package/client/app/app-provider.tsx +14 -20
  2. package/client/app/app-router.tsx +5 -8
  3. package/client/app/routes/workspace-route.tsx +28 -11
  4. package/client/app/shell/sidebar-layout.tsx +5 -10
  5. package/client/features/app-settings/api.ts +3 -3
  6. package/client/features/applets/applet-cache.ts +1 -2
  7. package/client/features/applets/use-applet.ts +18 -20
  8. package/client/features/chat/chat-store.ts +1 -1
  9. package/client/features/chat/connection/chat-connection.ts +25 -68
  10. package/client/features/chat/connection/chat-frames.ts +20 -32
  11. package/client/features/chat/sessions/api.ts +2 -2
  12. package/client/features/chat/sessions/use-selected-session.ts +0 -13
  13. package/client/features/collab/presence/client.ts +63 -83
  14. package/client/features/collab/presence/provider.tsx +8 -2
  15. package/client/features/dev/chat-states-page.tsx +1 -1
  16. package/client/features/dev/harness-debug-page.tsx +2 -2
  17. package/client/features/scratchpad/scratchpad.tsx +29 -20
  18. package/client/features/views/api.ts +38 -14
  19. package/client/features/views/use-view-actions.ts +2 -23
  20. package/client/features/workspace/api.ts +6 -11
  21. package/client/features/workspace/harness-transition.ts +3 -5
  22. package/client/features/workspace/remote.ts +9 -0
  23. package/client/features/workspace/settings/use-env-vars.ts +4 -4
  24. package/client/features/workspace/tab-resolution.ts +1 -8
  25. package/client/features/workspace/use-workspace-navigation.ts +5 -4
  26. package/client/features/workspace/use-workspace-socket.ts +51 -0
  27. package/client/features/workspace/workspace-content.tsx +5 -18
  28. package/client/features/workspace/workspace-layout-context.tsx +6 -13
  29. package/client/features/workspace/workspace-preferences.ts +67 -10
  30. package/client/features/workspace/workspace-state.ts +57 -21
  31. package/client/runtime/app-context.ts +2 -2
  32. package/client/runtime/app-events.ts +75 -0
  33. package/client/runtime/reconnecting-socket.ts +115 -0
  34. package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
  35. package/client/store/ui.ts +1 -6
  36. package/client/store/workspace-session.ts +30 -0
  37. package/dist/chunk-0t8m1ehd.js +2 -0
  38. package/dist/chunk-851bx8ss.js +72 -0
  39. package/dist/{chunk-n0fawy9x.js → chunk-c8g5x288.js} +1 -1
  40. package/dist/chunk-cty37f3v.js +1 -0
  41. package/dist/chunk-dy6f6h3e.js +5 -0
  42. package/dist/chunk-j6928pwm.js +1 -0
  43. package/dist/{chunk-rmd0ctfx.js → chunk-k32585ne.js} +73 -73
  44. package/dist/chunk-qtkv7hp8.js +2 -0
  45. package/dist/chunk-rh58dc0y.js +2 -0
  46. package/dist/{chunk-ec5ennpv.js → chunk-wjbejzek.js} +1 -1
  47. package/dist/index.html +1 -1
  48. package/lib/events.ts +61 -0
  49. package/lib/ids.ts +2 -8
  50. package/lib/moi-context.ts +19 -5
  51. package/lib/types.ts +16 -20
  52. package/lib/workspace-layout.ts +3 -20
  53. package/package.json +2 -1
  54. package/server/AGENTS.md +4 -4
  55. package/server/README.md +50 -33
  56. package/server/api/index.ts +175 -152
  57. package/server/applets/views.ts +15 -14
  58. package/server/applets/widgets.ts +4 -3
  59. package/server/cli/commands/init.ts +7 -2
  60. package/server/cli/commands/refresh.ts +2 -5
  61. package/server/cli/commands/remote.ts +128 -26
  62. package/server/cli/remote-control.ts +12 -9
  63. package/server/cli/remote-operations.ts +47 -44
  64. package/server/control.ts +33 -34
  65. package/server/events.ts +14 -13
  66. package/server/harness/README.md +7 -7
  67. package/server/harness/acp/session.ts +9 -5
  68. package/server/harness/auth.ts +7 -30
  69. package/server/harness/claude-code/session.ts +8 -4
  70. package/server/harness/codex/NOTES.md +1 -1
  71. package/server/harness/codex/session.ts +18 -10
  72. package/server/harness/hermes/NOTES.md +3 -3
  73. package/server/harness/openclaw/session.ts +9 -5
  74. package/server/onboarding/jobs.ts +8 -8
  75. package/server/operations/commands.ts +1 -1
  76. package/server/remote/broker-client.ts +76 -0
  77. package/server/remote/broker.ts +81 -0
  78. package/server/remote/client.ts +212 -152
  79. package/server/remote/errors.ts +2 -0
  80. package/server/remote/routes.ts +121 -0
  81. package/server/scratchpad/document.ts +3 -2
  82. package/server/scratchpad/executor.ts +2 -2
  83. package/server/scratchpad/relay.ts +3 -3
  84. package/server/sessions/archive.ts +1 -1
  85. package/server/sessions/lifecycle.ts +1 -1
  86. package/server/sessions/pending-views.ts +19 -12
  87. package/server/sessions/send-message.ts +102 -0
  88. package/server/sessions/view-sessions.ts +4 -94
  89. package/server/web.ts +42 -31
  90. package/server/workspace-state/file.ts +2 -0
  91. package/server/workspace-state/index.ts +15 -4
  92. package/server/workspaces/api.ts +4 -8
  93. package/server/workspaces/config.ts +14 -13
  94. package/server/workspaces/env-apply.ts +1 -1
  95. package/server/workspaces/layout.ts +40 -7
  96. package/server/workspaces/shared.ts +1 -1
  97. package/server/workspaces/tabs.ts +1 -2
  98. package/skill/SKILL.md +75 -34
  99. package/skill/references/SCRATCHPAD.md +4 -0
  100. package/skill/references/UI-COMPONENTS.md +1 -1
  101. package/client/features/scratchpad/scratch-executor.ts +0 -20
  102. package/client/runtime/workspace-events.ts +0 -168
  103. package/dist/chunk-44khk4sp.js +0 -2
  104. package/dist/chunk-ba6mz56s.js +0 -72
  105. package/dist/chunk-ectsnw81.js +0 -2
  106. package/dist/chunk-en7w5ypg.js +0 -1
  107. package/dist/chunk-f695wcx5.js +0 -5
  108. package/dist/chunk-pdt9hxfw.js +0 -2
  109. package/dist/chunk-zv22wv0g.js +0 -1
@@ -11,13 +11,14 @@ import type { SpeedMode } from '@/lib/types'
11
11
  import { isSpeedMode } from '@/lib/speed-mode'
12
12
  import { isMessageAttachments } from '@/lib/message-attachments'
13
13
  import { Hono } from 'hono'
14
+ import { z } from 'zod'
15
+ import { AGENT_THEMES, COLOR_THEMES, FONT_THEMES, RADIUS_THEMES } from '@/lib/themes'
14
16
  import { serveStatic } from 'hono/bun'
15
17
  import { createMiddleware } from 'hono/factory'
16
18
  import { existsSync } from 'node:fs'
17
19
  import { basename, resolve } from 'node:path'
18
20
 
19
21
  import { UPDATE_ACTIVE_AGENT_MESSAGE } from '@/lib/update'
20
- import { resolveWorkspaceTheme } from '@/lib/themes'
21
22
  import { isWorkspaceIcon } from '@/lib/workspace-icon'
22
23
  import type {
23
24
  AppletKind,
@@ -43,12 +44,7 @@ import { applyEnvChanged } from '../workspaces/env-apply'
43
44
  import { publishEvent } from '../events'
44
45
  import { callFunction, parseFunctionPath } from '../applets/functions'
45
46
  import { processIcon } from '../workspaces/icon'
46
- import {
47
- getWorkspacePreview,
48
- loadLayout,
49
- mergeLayoutForSave,
50
- saveLayout
51
- } from '../workspaces/layout'
47
+ import { getWorkspacePreview, mergeLayoutForSave, updateLayout } from '../workspaces/layout'
52
48
  import {
53
49
  getAppletThumbnailRecords,
54
50
  isValidAppletId,
@@ -78,7 +74,8 @@ import {
78
74
  import { saveSessionConfig } from '../sessions/config'
79
75
  import type { SessionConfigPatch } from '../sessions/config'
80
76
  import { archiveWorkspaceSession } from '../sessions/archive'
81
- import { getWorkspaceState } from '../workspace-state'
77
+ import { getWorkspaceState, updateWorkspaceState } from '../workspace-state'
78
+ import { normalizeOpenTabs } from '@/lib/workspace-layout'
82
79
  import { DIST_DIR, prebuilt } from '../static'
83
80
  import { getWorkspaceSkillsStatus, updateWorkspaceSkills } from '../skills/update'
84
81
  import { serveWorkspaceImagePreview } from '../workspaces/preview'
@@ -117,7 +114,7 @@ import {
117
114
  updateInProgress
118
115
  } from '../update'
119
116
 
120
- // The resolved workspace is stashed on the context by `withWorkspace`, so every
117
+ // The resolved workspace is stashed on the context by the workspace middleware, so every
121
118
  // `/api/workspaces/:id/*` handler can read it without re-querying the registry.
122
119
  type ApiEnv = { Variables: { ws: WorkspaceEntry } }
123
120
 
@@ -165,53 +162,42 @@ async function handleFunctionCall(
165
162
  }
166
163
  }
167
164
 
168
- // Routes that describe the person using a workspace, not the workspace itself:
169
- // their chats, their agent and what that agent runs with. A visitor's Moi answers
170
- // them from its own folder; an owner never serves them to visitors.
171
- const PERSONAL_ROUTE_RE = /^\/(?:sessions|state|harness|skills|env|mcp|uploads|preview)(?:\/|$)/
172
- // A view being built belongs to the chat building it, so its lifecycle is
173
- // personal too. Compiled views stay with the owner.
174
- const PENDING_VIEW_ROUTE_RE = /^\/views(?:\/[^/]+(?:\/submit)?)?$/
175
-
176
- // Resolve `:id` to a registered workspace once, 404 if unknown, and stash it on
177
- // the context. Mounted on the single-workspace sub-app so every nested route
178
- // shares the lookup instead of repeating `getWorkspace(...) ?? 404`.
179
- const withWorkspace = createMiddleware<ApiEnv>(async (c, next) => {
180
- const id = c.req.param('id')
181
- if (!id) return c.text('Workspace not found', 404)
182
- let release: (() => void) | undefined
183
- try {
184
- if (c.req.method !== 'GET' && !c.req.path.endsWith('/harness'))
185
- release = reserveWorkspaceOperation(id)
186
- const ws = await getWorkspace(id)
187
- if (!ws) return c.text('Workspace not found', 404)
188
- const suffix = (c.req.path.split(`/workspaces/${encodeURIComponent(id)}`)[1] ?? '').replace(
189
- /\/$/,
190
- ''
191
- )
192
- const personal =
193
- PERSONAL_ROUTE_RE.test(suffix) ||
194
- (c.req.method !== 'GET' && PENDING_VIEW_ROUTE_RE.test(suffix))
195
- if (ws.remote && suffix === '' && c.req.method === 'DELETE')
196
- return c.text('Leaving remote workspaces is not available yet', 403)
197
- if (ws.remote && getAppConfig().environment !== 'cloud')
198
- return c.text('Remote workspaces require Cloud mode', 403)
199
- if (ws.remote && suffix !== '' && !personal)
200
- return c.text('Use the owner workspace address', 404)
201
- c.set('ws', ws)
202
- await next()
203
- } catch (error) {
204
- if (error instanceof HarnessTransitionError) return c.text(error.message, 409)
205
- throw error
206
- } finally {
207
- release?.()
208
- }
209
- })
165
+ // Resolve the workspace and enforce the route's storage boundary. Personal
166
+ // routes use this Moi's chats, agent and pending views, including for a remote
167
+ // reference. Shared content must be requested at the owner's workspace address.
168
+ function workspaceAccess(
169
+ scope: 'personal' | 'owner',
170
+ { reserveOperation = true }: { reserveOperation?: boolean } = {}
171
+ ) {
172
+ return createMiddleware<ApiEnv>(async (c, next) => {
173
+ const id = c.req.param('id')
174
+ if (!id) return c.text('Workspace not found', 404)
175
+ let release: (() => void) | undefined
176
+ try {
177
+ if (reserveOperation && c.req.method !== 'GET') release = reserveWorkspaceOperation(id)
178
+ const ws = await getWorkspace(id)
179
+ if (!ws) return c.text('Workspace not found', 404)
180
+ if (ws.remote && getAppConfig().environment !== 'cloud')
181
+ return c.text('Remote workspaces require Cloud mode', 403)
182
+ if (ws.remote && scope === 'owner') return c.text('Use the owner workspace address', 404)
183
+ c.set('ws', ws)
184
+ await next()
185
+ } catch (error) {
186
+ if (error instanceof HarnessTransitionError) return c.text(error.message, 409)
187
+ throw error
188
+ } finally {
189
+ release?.()
190
+ }
191
+ })
192
+ }
193
+
194
+ const personalWorkspace = workspaceAccess('personal')
195
+ const ownerWorkspace = workspaceAccess('owner')
210
196
 
211
197
  // ---- single workspace: /api/workspaces/:id/* --------------------------------
212
198
  const one = new Hono<ApiEnv>()
213
- one.use('*', withWorkspace)
214
- one.patch('/harness', async c => {
199
+ // Switching agents takes its own exclusive lock.
200
+ one.patch('/harness', workspaceAccess('personal', { reserveOperation: false }), async c => {
215
201
  if (getAppConfig().demo) return c.text('Changing agents is unavailable in the demo', 403)
216
202
  const body = await c.req.json().catch(() => null)
217
203
  if (!body || !['claude-code', 'codex'].includes(body.harness))
@@ -224,13 +210,13 @@ one.patch('/harness', async c => {
224
210
  }
225
211
  })
226
212
 
227
- one.get('/widgets', c => listWidgets(c.get('ws').path))
213
+ one.get('/widgets', ownerWorkspace, c => listWidgets(c.get('ws').path))
228
214
 
229
215
  // Widget bundle: the compiled ESM for one widget, dynamically imported by the
230
216
  // client (useWidget). Sits beside the GET .../widgets list above — the exact
231
217
  // path lists, `/*` serves a file from the bundle dir (`<name>/<file>`:
232
218
  // index.js, a chunk, or a hashed asset).
233
- one.get('/widgets/*', c => {
219
+ one.get('/widgets/*', ownerWorkspace, c => {
234
220
  const ws = c.get('ws')
235
221
  const { name, file } = parseAppletTail(c.req.url, ws.id, 'widgets')
236
222
  if (!name) return c.text('Not found', 404)
@@ -239,7 +225,7 @@ one.get('/widgets/*', c => {
239
225
 
240
226
  // Views — full-screen agent apps. Mirrors the widget pair above: the exact path
241
227
  // lists (in manifest/nav order), `/*` serves one bundle file.
242
- one.get('/views', async c =>
228
+ one.get('/views', ownerWorkspace, async c =>
243
229
  c.req.query('includePending') === 'true'
244
230
  ? c.json({ views: await getWorkspaceViews(c.get('ws')) })
245
231
  : listViews(c.get('ws').path)
@@ -247,7 +233,8 @@ one.get('/views', async c =>
247
233
 
248
234
  const OWNER_VIEW = 'Use the owner workspace address for compiled views'
249
235
 
250
- one.patch('/views/:viewId', async c => {
236
+ // Pending views are personal; these handlers also accept compiled views on the owner.
237
+ one.patch('/views/:viewId', personalWorkspace, async c => {
251
238
  const ws = c.get('ws')
252
239
  const body = await c.req.json().catch(() => null)
253
240
  if (await getPendingView(ws, c.req.param('viewId'))) {
@@ -283,7 +270,7 @@ one.patch('/views/:viewId', async c => {
283
270
  }
284
271
  })
285
272
 
286
- one.delete('/views/:viewId', async c => {
273
+ one.delete('/views/:viewId', personalWorkspace, async c => {
287
274
  const ws = c.get('ws')
288
275
  try {
289
276
  const viewId = c.req.param('viewId')
@@ -305,19 +292,19 @@ one.delete('/views/:viewId', async c => {
305
292
  }
306
293
  })
307
294
 
308
- one.get('/views/*', c => {
295
+ one.get('/views/*', ownerWorkspace, c => {
309
296
  const ws = c.get('ws')
310
297
  const { name, file } = parseAppletTail(c.req.url, ws.id, 'views')
311
298
  if (!name) return c.text('Not found', 404)
312
299
  return serveView(name, file, ws.path, workspaceApiBase(ws.id), c.req.header('if-none-match'))
313
300
  })
314
301
 
315
- one.post('/views', async c => {
302
+ one.post('/views', personalWorkspace, async c => {
316
303
  const ws = c.get('ws')
317
304
  return c.json(await createPendingView(ws), 201)
318
305
  })
319
306
 
320
- one.post('/views/:viewId/submit', async c => {
307
+ one.post('/views/:viewId/submit', personalWorkspace, async c => {
321
308
  const ws = c.get('ws')
322
309
  const body = await c.req.json<{
323
310
  requirements?: string
@@ -356,7 +343,7 @@ one.post('/views/:viewId/submit', async c => {
356
343
  speedMode: isSpeedMode(body.speedMode) ? body.speedMode : undefined,
357
344
  stream: body.stream === true ? true : undefined
358
345
  })
359
- return c.json(result)
346
+ return c.json({ ...result, state: await getWorkspaceState(ws) })
360
347
  } catch (err) {
361
348
  if (err instanceof PendingViewError) return c.text(err.message, err.status)
362
349
  if (err instanceof ViewStartupError)
@@ -370,7 +357,7 @@ one.post('/views/:viewId/submit', async c => {
370
357
  // dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions
371
358
  // are allowed — the workspace holds secrets, and this route is unauthenticated.
372
359
  // localhost binding is NOT the guard.
373
- one.get('/files/*', c => {
360
+ one.get('/files/*', ownerWorkspace, c => {
374
361
  const ws = c.get('ws')
375
362
  const tail = new URL(c.req.url).pathname.split(`${workspaceApiBase(ws.id)}/files/`)[1] ?? ''
376
363
  return serveWorkspaceFile(ws.path, tail, c.req.header('range'), c.req.header('if-none-match'))
@@ -379,7 +366,7 @@ one.get('/files/*', c => {
379
366
  // Applet RPC — the home for server-function calls from a bundle. The bundle's
380
367
  // sentinel base resolves to `/api/workspaces/<id>`, so it POSTs to
381
368
  // `…/rpc/<module>/<fn>`.
382
- one.post('/rpc/*', c => {
369
+ one.post('/rpc/*', ownerWorkspace, c => {
383
370
  const ws = c.get('ws')
384
371
  const tail = new URL(c.req.url).pathname.split(`${workspaceApiBase(ws.id)}/rpc/`)[1] ?? ''
385
372
  return handleFunctionCall(c.req.raw, tail, ws.path)
@@ -392,7 +379,7 @@ one.post('/rpc/*', c => {
392
379
  // sources (`build`/`rpc` are server-recorded and can't be spoofed by a tab),
393
380
  // pattern-check the applet name, cap the batch size; applets/log.ts caps string
394
381
  // lengths.
395
- one.post('/applet-log', async c => {
382
+ one.post('/applet-log', ownerWorkspace, async c => {
396
383
  let body: { events?: unknown }
397
384
  try {
398
385
  body = await c.req.json()
@@ -435,7 +422,7 @@ one.post('/applet-log', async c => {
435
422
  // Downscaled image preview of a workspace file. The chat's expanded tool rows
436
423
  // use this to show the picture an agent `Read` — same guards as /files/ above,
437
424
  // images only, resized server-side (see server/workspaces/preview.ts).
438
- one.get('/preview/*', c => {
425
+ one.get('/preview/*', personalWorkspace, c => {
439
426
  const ws = c.get('ws')
440
427
  const tail = new URL(c.req.url).pathname.split(`${workspaceApiBase(ws.id)}/preview/`)[1] ?? ''
441
428
  return serveWorkspaceImagePreview(ws.path, tail, c.req.header('if-none-match'))
@@ -446,7 +433,7 @@ one.get('/preview/*', c => {
446
433
  // upload ids the chat WS frame references. Images are downscaled and inlined as
447
434
  // vision blocks at send time; other files are referenced by a temp path. See
448
435
  // server/uploads.ts and dev/file-uploads.md.
449
- one.post('/uploads', async c => {
436
+ one.post('/uploads', personalWorkspace, async c => {
450
437
  const ws = c.get('ws')
451
438
  let form: FormData
452
439
  try {
@@ -481,7 +468,7 @@ one.post('/uploads', async c => {
481
468
  })
482
469
 
483
470
  // Existing workspace documents enter the same upload pipeline without a browser round trip.
484
- one.post('/uploads/from-path', async c => {
471
+ one.post('/uploads/from-path', personalWorkspace, async c => {
485
472
  const body: unknown = await c.req.json().catch(() => null)
486
473
  if (!body || typeof body !== 'object' || !('path' in body) || typeof body.path !== 'string') {
487
474
  return c.text('Choose a file from this workspace', 400)
@@ -507,7 +494,7 @@ one.post('/uploads/from-path', async c => {
507
494
  // base64 data URL so the transcript broadcast / client cache stay small. The id
508
495
  // is content-addressed (sha256), so the response is immutable while it lives —
509
496
  // let the browser cache it for the store's TTL.
510
- one.get('/uploads/:uploadId', c => {
497
+ one.get('/uploads/:uploadId', personalWorkspace, c => {
511
498
  const u = getUpload(c.get('ws').id, c.req.param('uploadId'))
512
499
  if (!u) return c.text('Not found or expired', 404)
513
500
  const body = u.data ? new Uint8Array(u.data) : u.path ? Bun.file(u.path) : null
@@ -521,18 +508,25 @@ one.get('/uploads/:uploadId', c => {
521
508
  })
522
509
  })
523
510
 
524
- // Per-user chat state: pin, the chat each tab shows, per-chat settings and
525
- // fork history, and views being built. Every write below answers with the new
526
- // state; other clients get it as `state:changed`.
527
- one.get('/state', async c => c.json(await getWorkspaceState(c.get('ws'))))
511
+ // Personal state writes return the latest snapshot and publish `personal-state:changed`.
512
+ one.get('/state', personalWorkspace, async c => c.json(await getWorkspaceState(c.get('ws'))))
513
+
514
+ one.put('/state/tabs', personalWorkspace, async c => {
515
+ const body = await c.req.json().catch(() => null)
516
+ const ws = c.get('ws')
517
+ await updateWorkspaceState(ws, state => {
518
+ state.openTabs = normalizeOpenTabs(body?.openTabs)
519
+ })
520
+ return c.json(await getWorkspaceState(ws))
521
+ })
528
522
 
529
523
  // The agent's chats. Tab ownership and settings come from `/state`.
530
- one.get('/sessions', async c => {
524
+ one.get('/sessions', personalWorkspace, async c => {
531
525
  const ws = c.get('ws')
532
526
  return c.json(await harnessFor(ws).listSessions(ws))
533
527
  })
534
528
 
535
- one.put('/sessions/:sessionId/pin', async c => {
529
+ one.put('/sessions/:sessionId/pin', personalWorkspace, async c => {
536
530
  const ws = c.get('ws')
537
531
  const sessionId = c.req.param('sessionId')
538
532
  const harness = harnessFor(ws)
@@ -545,7 +539,7 @@ one.put('/sessions/:sessionId/pin', async c => {
545
539
  return c.json(await getWorkspaceState(ws))
546
540
  })
547
541
 
548
- one.delete('/sessions/:sessionId/pin', async c => {
542
+ one.delete('/sessions/:sessionId/pin', personalWorkspace, async c => {
549
543
  const ws = c.get('ws')
550
544
  await unpinSession(ws, c.req.param('sessionId'))
551
545
  return c.json(await getWorkspaceState(ws))
@@ -553,7 +547,7 @@ one.delete('/sessions/:sessionId/pin', async c => {
553
547
 
554
548
  // Show the chat in a tab. `ifMatch` (a chat id, or null for none) applies the
555
549
  // change only while the tab still shows that chat.
556
- one.put('/sessions/:sessionId/selection', async c => {
550
+ one.put('/sessions/:sessionId/selection', personalWorkspace, async c => {
557
551
  const ws = c.get('ws')
558
552
  const body: unknown = await c.req.json().catch(() => null)
559
553
  if (!body || typeof body !== 'object') return c.text('Bad request', 400)
@@ -574,7 +568,7 @@ one.put('/sessions/:sessionId/selection', async c => {
574
568
 
575
569
  // Stop showing the chat in a tab, which then opens a new chat. A tab showing
576
570
  // another chat is left alone.
577
- one.delete('/sessions/:sessionId/selection', async c => {
571
+ one.delete('/sessions/:sessionId/selection', personalWorkspace, async c => {
578
572
  const ws = c.get('ws')
579
573
  const body: unknown = await c.req.json().catch(() => null)
580
574
  const tabId = (body as { tabId?: unknown } | null)?.tabId
@@ -584,34 +578,39 @@ one.delete('/sessions/:sessionId/selection', async c => {
584
578
  })
585
579
 
586
580
  // Change run settings. Omitted fields stay; null clears one.
587
- one.on('PATCH', ['/sessions/:sessionId/config', '/state/chat-defaults'], async c => {
588
- const body = await c.req.json().catch(() => null)
589
- if (typeof body !== 'object' || body === null) {
590
- return c.text('Expected a JSON object', 400)
591
- }
592
- const patch: SessionConfigPatch = {}
593
- const record = body as Record<string, unknown>
594
- for (const key of ['model', 'effort'] as const) {
595
- if (!(key in record)) continue
596
- const value = record[key]
597
- if (value !== null && typeof value !== 'string') {
598
- return c.text(`${key} must be a string or null`, 400)
581
+ one.on(
582
+ 'PATCH',
583
+ ['/sessions/:sessionId/config', '/state/chat-defaults'],
584
+ personalWorkspace,
585
+ async c => {
586
+ const body = await c.req.json().catch(() => null)
587
+ if (typeof body !== 'object' || body === null) {
588
+ return c.text('Expected a JSON object', 400)
599
589
  }
600
- patch[key] = value
601
- }
602
- if ('speedMode' in record) {
603
- const value = record.speedMode
604
- if (value !== null && !isSpeedMode(value)) {
605
- return c.text('speedMode must be "normal", "fast", "ultrafast", or null', 400)
590
+ const patch: SessionConfigPatch = {}
591
+ const record = body as Record<string, unknown>
592
+ for (const key of ['model', 'effort'] as const) {
593
+ if (!(key in record)) continue
594
+ const value = record[key]
595
+ if (value !== null && typeof value !== 'string') {
596
+ return c.text(`${key} must be a string or null`, 400)
597
+ }
598
+ patch[key] = value
599
+ }
600
+ if ('speedMode' in record) {
601
+ const value = record.speedMode
602
+ if (value !== null && !isSpeedMode(value)) {
603
+ return c.text('speedMode must be "normal", "fast", "ultrafast", or null', 400)
604
+ }
605
+ patch.speedMode = value
606
606
  }
607
- patch.speedMode = value
607
+ const ws = c.get('ws')
608
+ await saveSessionConfig(ws, c.req.param('sessionId'), patch)
609
+ return c.json(await getWorkspaceState(ws))
608
610
  }
609
- const ws = c.get('ws')
610
- await saveSessionConfig(ws, c.req.param('sessionId'), patch)
611
- return c.json(await getWorkspaceState(ws))
612
- })
611
+ )
613
612
 
614
- one.post('/sessions/:sessionId/archive', async c => {
613
+ one.post('/sessions/:sessionId/archive', personalWorkspace, async c => {
615
614
  const ws = c.get('ws')
616
615
  const harness = harnessFor(ws)
617
616
  const sessionId = c.req.param('sessionId')
@@ -630,13 +629,13 @@ one.post('/sessions/:sessionId/archive', async c => {
630
629
  }
631
630
  })
632
631
 
633
- one.get('/sessions/:sessionId/events', async c => {
632
+ one.get('/sessions/:sessionId/events', personalWorkspace, async c => {
634
633
  const ws = c.get('ws')
635
634
  const sessionId = c.req.param('sessionId')
636
635
  return c.json(await harnessFor(ws).sessionEvents(ws, sessionId))
637
636
  })
638
637
 
639
- one.get('/mcp', async c => {
638
+ one.get('/mcp', personalWorkspace, async c => {
640
639
  const ws = c.get('ws')
641
640
  const harness = harnessFor(ws)
642
641
  if (c.req.query('stream') !== 'true') return c.json((await harness.mcpStatus?.(ws)) ?? [])
@@ -670,7 +669,7 @@ one.get('/mcp', async c => {
670
669
  // (Codex: app-server JSON-RPC, both directions; Claude Code: raw SDK messages
671
670
  // + enqueued inputs) and the exact frames the server pushed to chat clients.
672
671
  // `sinceWire`/`sinceBroadcast` are seq cursors so the page can poll deltas.
673
- one.get('/harness/debug', async c => {
672
+ one.get('/harness/debug', personalWorkspace, async c => {
674
673
  const ws = c.get('ws')
675
674
  const harness = harnessFor(ws)
676
675
  const sinceWire = Number(c.req.query('sinceWire') ?? 0) || 0
@@ -685,7 +684,7 @@ one.get('/harness/debug', async c => {
685
684
 
686
685
  // Per-workspace env vars. GET returns the effective view (discovered `.env` + UI
687
686
  // custom secrets + scopes + declared-required keys; values masked).
688
- one.get('/env', async c => {
687
+ one.get('/env', personalWorkspace, async c => {
689
688
  const ws = c.get('ws')
690
689
  // Unawaited on purpose: getWorkspaceEnvView loads it in parallel with the
691
690
  // env stores (manifest reads and env reads are independent).
@@ -696,7 +695,7 @@ one.get('/env', async c => {
696
695
  // then reaps the workspace's function worker and idle agent sessions so the next
697
696
  // call/message picks up the change (env is frozen at spawn — a hard restart is
698
697
  // the only way).
699
- one.put('/env', async c => {
698
+ one.put('/env', personalWorkspace, async c => {
700
699
  const ws = c.get('ws')
701
700
  const patch = parseEnvUpdate(await c.req.json().catch(() => null))
702
701
  if (typeof patch === 'string') return c.text(patch, 400)
@@ -714,12 +713,12 @@ one.put('/env', async c => {
714
713
  return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
715
714
  })
716
715
 
717
- one.get('/skills', async c => {
716
+ one.get('/skills', personalWorkspace, async c => {
718
717
  const ws = c.get('ws')
719
718
  return c.json(await getWorkspaceSkillsStatus(ws.path, ws.harness))
720
719
  })
721
720
 
722
- one.post('/skills/update', async c => {
721
+ one.post('/skills/update', personalWorkspace, async c => {
723
722
  const ws = c.get('ws')
724
723
  const result = await updateWorkspaceSkills(ws.path, ws.harness ?? 'claude-code')
725
724
  return c.json(result.status)
@@ -727,7 +726,7 @@ one.post('/skills/update', async c => {
727
726
 
728
727
  // Workspace configuration and models. Shared account status is served by
729
728
  // /harnesses/status; only workspace overrides and gateways are probed here.
730
- one.get('/harness', async c => {
729
+ one.get('/harness', personalWorkspace, async c => {
731
730
  const ws = c.get('ws')
732
731
  const harness = harnessFor(ws)
733
732
  const capabilities = {
@@ -764,9 +763,7 @@ one.get('/harness', async c => {
764
763
  // Gateway-backed harnesses still have workspace-specific readiness.
765
764
  harness.authStatus && !hasAuthOverrides
766
765
  ? Promise.resolve({ status: 'available' as const })
767
- : refresh
768
- ? harnessStore.refresh(ws)
769
- : harnessStore.getAvailability(ws),
766
+ : harnessStore.getAvailability(ws, refresh),
770
767
  harness.listModels(ws).catch(err => {
771
768
  console.error(`[api] listModels failed for ${harness.id}`, err)
772
769
  return []
@@ -781,11 +778,11 @@ one.get('/harness', async c => {
781
778
  })
782
779
 
783
780
  // Workspace identity. Uploads use the image route below.
784
- one.get('/config', async c => {
781
+ one.get('/config', ownerWorkspace, async c => {
785
782
  return c.json(await getWorkspaceConfig(c.get('ws').path))
786
783
  })
787
784
 
788
- one.put('/config', async c => {
785
+ one.put('/config', ownerWorkspace, async c => {
789
786
  const ws = c.get('ws')
790
787
  const parsed: unknown = await c.req.json().catch(() => null)
791
788
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
@@ -804,7 +801,11 @@ one.put('/config', async c => {
804
801
  return c.text('Expected a workspace config field', 400)
805
802
  }
806
803
  await setWorkspaceConfig(ws.path, { name, icon })
807
- publishEvent({ type: 'workspace:updated', workspaceId: ws.id, origin: eventOrigin(body.origin) })
804
+ publishEvent({
805
+ type: 'workspace-config:changed',
806
+ workspaceId: ws.id,
807
+ origin: eventOrigin(body.origin)
808
+ })
808
809
  return c.json(await getWorkspaceConfig(ws.path))
809
810
  })
810
811
 
@@ -814,7 +815,7 @@ one.put('/config', async c => {
814
815
  // `origin` is the writing tab's id — echoed in the broadcast so that tab can
815
816
  // ignore its own save. This is the browser's write path; the agent's draws are
816
817
  // written server-side (see server/scratchpad/executor.ts). See docs/moi-scratchpad.md.
817
- one.post('/scratchpad/ops', async c => {
818
+ one.post('/scratchpad/ops', ownerWorkspace, async c => {
818
819
  try {
819
820
  const form = await c.req.formData()
820
821
  const op = JSON.parse(String(form.get('op'))) as ScratchOp | null
@@ -832,11 +833,11 @@ one.post('/scratchpad/ops', async c => {
832
833
  }
833
834
  })
834
835
 
835
- one.get('/scratchpad', async c => {
836
+ one.get('/scratchpad', ownerWorkspace, async c => {
836
837
  return c.json(await loadScratchpadDoc(c.get('ws').path))
837
838
  })
838
839
 
839
- one.put('/scratchpad', async c => {
840
+ one.put('/scratchpad', ownerWorkspace, async c => {
840
841
  const ws = c.get('ws')
841
842
  const body = await c.req.json().catch(() => null)
842
843
  if (!body || typeof body !== 'object' || !body.document) {
@@ -844,7 +845,7 @@ one.put('/scratchpad', async c => {
844
845
  }
845
846
  await saveScratchpadDoc(body.document, ws.path)
846
847
  publishEvent({
847
- type: 'scratchpad:updated',
848
+ type: 'scratchpad:changed',
848
849
  workspaceId: ws.id,
849
850
  origin: eventOrigin(body.origin)
850
851
  })
@@ -856,7 +857,7 @@ one.put('/scratchpad', async c => {
856
857
  // never inlined as base64 in the JSON (see server/scratchpad/assets.ts). The
857
858
  // browser's TLAssetStore POSTs the raw file here on paste and resolves `asset:`
858
859
  // srcs back through the GET when rendering.
859
- one.post('/scratchpad/assets', async c => {
860
+ one.post('/scratchpad/assets', ownerWorkspace, async c => {
860
861
  const length = Number(c.req.header('content-length') ?? 0)
861
862
  if (length > MAX_ASSET_BYTES) {
862
863
  return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
@@ -872,7 +873,7 @@ one.post('/scratchpad/assets', async c => {
872
873
 
873
874
  // The file name is content-addressed (sha256 of the bytes), so a hit is
874
875
  // immutable — let the browser cache it indefinitely.
875
- one.get('/scratchpad/assets/:file', async c => {
876
+ one.get('/scratchpad/assets/:file', ownerWorkspace, async c => {
876
877
  const resolved = scratchpadAssetFile(c.get('ws').path, c.req.param('file'))
877
878
  if (!resolved || !(await resolved.file.exists())) return c.text('Not found', 404)
878
879
  return new Response(resolved.file, {
@@ -890,7 +891,7 @@ one.get('/scratchpad/assets/:file', async c => {
890
891
 
891
892
  // Workspace upload. PUT resizes an image to a 128×128 WebP. DELETE resets any
892
893
  // custom icon to the provider default. Both broadcast for a live refresh.
893
- one.put('/icon', async c => {
894
+ one.put('/icon', ownerWorkspace, async c => {
894
895
  const ws = c.get('ws')
895
896
  const bytes = new Uint8Array(await c.req.arrayBuffer())
896
897
  if (bytes.length === 0) return c.text('Empty image body', 400)
@@ -903,20 +904,20 @@ one.put('/icon', async c => {
903
904
  }
904
905
  const workspaceIcon = { type: 'upload', value: icon } as const
905
906
  await setWorkspaceConfig(ws.path, { icon: workspaceIcon })
906
- publishEvent({ type: 'workspace:updated', workspaceId: c.get('ws').id })
907
+ publishEvent({ type: 'workspace-config:changed', workspaceId: c.get('ws').id })
907
908
  return c.json({ icon: workspaceIcon })
908
909
  })
909
910
 
910
- one.delete('/icon', async c => {
911
+ one.delete('/icon', ownerWorkspace, async c => {
911
912
  await setWorkspaceConfig(c.get('ws').path, { icon: null })
912
- publishEvent({ type: 'workspace:updated', workspaceId: c.get('ws').id })
913
+ publishEvent({ type: 'workspace-config:changed', workspaceId: c.get('ws').id })
913
914
  return c.body(null, 204)
914
915
  })
915
916
 
916
917
  // All info about a single workspace: its persisted layout (widget grid, layout
917
918
  // mode, theme) plus server-resolved metadata. GET reads, PUT writes the layout,
918
919
  // DELETE unregisters.
919
- one.get('/', async c => {
920
+ one.get('/', personalWorkspace, async c => {
920
921
  const ws = c.get('ws')
921
922
  const config = await loadWorkspaceFileConfig(ws.path)
922
923
  if (config.remote) {
@@ -947,11 +948,11 @@ one.get('/', async c => {
947
948
 
948
949
  // Thumbnail freshness records, without image bytes — the capture hook compares
949
950
  // these against live bundle revisions. Images are served per-applet below.
950
- one.get('/applet-thumbnails', async c =>
951
+ one.get('/applet-thumbnails', ownerWorkspace, async c =>
951
952
  c.json({ thumbnails: await getAppletThumbnailRecords(c.get('ws').path) })
952
953
  )
953
954
 
954
- one.get('/applet-thumbnails/:kind/:name', c => {
955
+ one.get('/applet-thumbnails/:kind/:name', ownerWorkspace, c => {
955
956
  const kind = c.req.param('kind')
956
957
  if (kind !== 'widget' && kind !== 'view') return c.text('Not found', 404)
957
958
  // `<id>` or `<id>:<version>`. Applet ids never contain `:`, and the version
@@ -967,7 +968,7 @@ one.get('/applet-thumbnails/:kind/:name', c => {
967
968
  })
968
969
 
969
970
  // Settled widget and view visits share one batch endpoint and storage path.
970
- one.put('/applet-thumbnails', async c => {
971
+ one.put('/applet-thumbnails', ownerWorkspace, async c => {
971
972
  const body: unknown = await c.req.json().catch(() => null)
972
973
  if (!body || typeof body !== 'object' || Array.isArray(body)) return c.text('Bad request', 400)
973
974
  const input = body as AppletThumbnailBatch
@@ -992,7 +993,34 @@ one.put('/applet-thumbnails', async c => {
992
993
  return c.body(null, 204)
993
994
  })
994
995
 
995
- one.put('/', async c => {
996
+ function themePreset<T extends string>(presets: Record<T, unknown>) {
997
+ return z.custom<T>(value => typeof value === 'string' && Object.hasOwn(presets, value))
998
+ }
999
+
1000
+ const layoutPatchSchema = z
1001
+ .strictObject({
1002
+ theme: z
1003
+ .strictObject({
1004
+ font: themePreset(FONT_THEMES),
1005
+ color: themePreset(COLOR_THEMES),
1006
+ radius: themePreset(RADIUS_THEMES),
1007
+ agent: themePreset(AGENT_THEMES)
1008
+ })
1009
+ .optional(),
1010
+ widgetGrid: z
1011
+ .array(
1012
+ z.object({
1013
+ i: z.string().min(1),
1014
+ x: z.int().nonnegative(),
1015
+ y: z.int().nonnegative()
1016
+ })
1017
+ )
1018
+ .optional(),
1019
+ origin: z.string().optional()
1020
+ })
1021
+ .refine(patch => patch.theme !== undefined || patch.widgetGrid !== undefined)
1022
+
1023
+ one.put('/', personalWorkspace, async c => {
996
1024
  const ws = c.get('ws')
997
1025
  if (ws.remote) {
998
1026
  return c.text(
@@ -1000,26 +1028,23 @@ one.put('/', async c => {
1000
1028
  403
1001
1029
  )
1002
1030
  }
1003
- const body = await c.req.json()
1004
- if (!body || body.version !== 2) return c.text('Bad request', 400)
1005
- // `origin` is the writing tab's id, echoed so that tab skips its own event.
1006
- const { origin } = body
1007
- // Only widgets and theme are taken from the body, so a grid/theme save can't
1008
- // erase a `moi config`-set name or icon. See mergeLayoutForSave.
1009
- const existing = await loadLayout(ws.path)
1010
- const next = mergeLayoutForSave(existing, body)
1011
- await saveLayout(next, ws.path)
1012
- if (
1013
- JSON.stringify(resolveWorkspaceTheme(existing.theme)) !==
1014
- JSON.stringify(resolveWorkspaceTheme(next.theme))
1015
- ) {
1016
- publishEvent({ type: 'theme:updated', workspaceId: ws.id, origin: eventOrigin(origin) })
1031
+ const patch = layoutPatchSchema.safeParse(await c.req.json().catch(() => null))
1032
+ if (!patch.success) return c.text('Invalid layout patch', 400)
1033
+ const { origin, ...layout } = patch.data
1034
+ const { changed } = await updateLayout(ws.path, current => mergeLayoutForSave(current, layout))
1035
+ if (changed) {
1036
+ publishEvent({
1037
+ type: 'workspace-config:changed',
1038
+ workspaceId: ws.id,
1039
+ origin
1040
+ })
1017
1041
  }
1018
1042
  return c.body(null, 204)
1019
1043
  })
1020
1044
 
1021
- one.delete('/', async c => {
1045
+ one.delete('/', personalWorkspace, async c => {
1022
1046
  const ws = c.get('ws')
1047
+ if (ws.remote) return c.text('Leaving remote workspaces is not available yet', 403)
1023
1048
  const ok = await removeWorkspace(ws.id)
1024
1049
  if (!ok) return c.text('Workspace not found', 404)
1025
1050
  harnessFor(ws).stopWorkspace?.(ws.path)
@@ -1073,9 +1098,9 @@ workspaces.put('/order', async c => {
1073
1098
  const hiddenIds = all.filter(entry => !visible.has(entry.id)).map(entry => entry.id)
1074
1099
  const entries = await reorderWorkspaces([...body.ids, ...hiddenIds])
1075
1100
  // List-only change: a narrow event so clients refetch just the sidebar
1076
- // list, not every per-workspace query (`workspace:updated` also triggers
1101
+ // list, not every per-workspace query (`workspace-config:changed` also triggers
1077
1102
  // layout refetches in open workspaces).
1078
- publishEvent({ type: 'workspaces-list:updated', origin: eventOrigin(body.origin) })
1103
+ publishEvent({ type: 'workspaces-list:changed', origin: eventOrigin(body.origin) })
1079
1104
  return c.json(await mergeWorkspaceList(visibleWorkspaces(entries)))
1080
1105
  } catch (err) {
1081
1106
  const message = err instanceof Error ? err.message : String(err)
@@ -1214,13 +1239,11 @@ workspaces.post('/create', async c => {
1214
1239
  await setWorkspaceConfig(path, { name })
1215
1240
  const entry = await registerWorkspace(path, { id: basename(path), harness, name })
1216
1241
  // Nudge every connected client (the sidebar list) to refetch.
1217
- publishEvent({ type: 'workspaces-list:updated' })
1242
+ publishEvent({ type: 'workspaces-list:changed' })
1218
1243
  return c.json(entry, 201)
1219
1244
  })
1220
1245
 
1221
1246
  // `/:id` is registered after the static `/discover` so the literal path wins.
1222
- // `/api/workspaces/ws` (the live-event WebSocket) is intercepted by Bun's routes
1223
- // table before it ever reaches Hono, so it never collides with `:id`.
1224
1247
  workspaces.route('/:id', one)
1225
1248
 
1226
1249
  // ---- top-level API ----------------------------------------------------------
@@ -1302,7 +1325,7 @@ api.patch('/api/settings', async c => {
1302
1325
  }
1303
1326
  // Other open clients hold these in a query cache with no polling; broadcast
1304
1327
  // the new value so an app-wide preference applies everywhere immediately.
1305
- publishEvent({ type: 'settings:updated', settings })
1328
+ publishEvent({ type: 'app-settings:changed', settings })
1306
1329
  return c.json(settings)
1307
1330
  })
1308
1331