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

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 (205) hide show
  1. package/client/api/app-config.ts +12 -1
  2. package/client/api/http.ts +11 -1
  3. package/client/app/app-router.tsx +3 -2
  4. package/client/app/routes/home-route.tsx +1 -1
  5. package/client/app/routes/workspace-registration.tsx +68 -0
  6. package/client/app/routes/workspace-route.tsx +33 -6
  7. package/client/app/shell/sidebar-layout.tsx +10 -5
  8. package/client/components/shared/workspace-icon.tsx +8 -17
  9. package/client/features/account/account-test-utils.tsx +15 -9
  10. package/client/features/account/api.ts +6 -6
  11. package/client/features/account/profile-actions.ts +5 -7
  12. package/client/features/app-settings/settings-page.tsx +2 -1
  13. package/client/features/applets/api.ts +6 -6
  14. package/client/features/applets/applet-cache.ts +6 -5
  15. package/client/features/applets/applet-log.ts +2 -1
  16. package/client/features/applets/applet-runtime.ts +2 -1
  17. package/client/features/applets/use-applet.ts +73 -18
  18. package/client/features/applets/widget-shell.tsx +4 -2
  19. package/client/features/chat/applet-chat-intents.ts +5 -13
  20. package/client/features/chat/chat-popup.tsx +8 -4
  21. package/client/features/chat/chat-send.ts +2 -2
  22. package/client/features/chat/composer/model-order.ts +4 -4
  23. package/client/features/chat/composer/model-picker.tsx +12 -10
  24. package/client/features/chat/composer/use-workspace-composer-state.tsx +1 -1
  25. package/client/features/chat/sessions/api.ts +11 -28
  26. package/client/features/chat/sessions/use-selected-session.ts +14 -109
  27. package/client/features/chat/use-chat.ts +8 -12
  28. package/client/features/collab/members/api.ts +4 -10
  29. package/client/features/collab/members/hooks.ts +32 -38
  30. package/client/features/collab/members/store.ts +96 -71
  31. package/client/features/collab/members/types.ts +5 -3
  32. package/client/features/collab/presence/client.ts +2 -3
  33. package/client/features/collab/presence/hooks.tsx +1 -1
  34. package/client/features/collab/proxy-user.ts +1 -3
  35. package/client/features/collab/sharing/workspace-members.tsx +0 -8
  36. package/client/features/dev/chat-states-page.tsx +3 -1
  37. package/client/features/dev/harness-debug-page.tsx +7 -7
  38. package/client/features/dev/workspace-setup-mocks.ts +1 -1
  39. package/client/features/dev/workspace-setup-preview.tsx +6 -4
  40. package/client/features/harness/api.ts +13 -10
  41. package/client/features/harness/harness-login-panel.tsx +9 -5
  42. package/client/features/harness/harness-presentation.ts +4 -4
  43. package/client/features/harness/harness-selector.tsx +13 -13
  44. package/client/features/harness/use-harness-login.ts +5 -5
  45. package/client/features/home/api.ts +38 -2
  46. package/client/features/home/home-page.tsx +43 -13
  47. package/client/features/home/shared-workspaces.tsx +70 -0
  48. package/client/features/home/workspace-invitations.tsx +101 -0
  49. package/client/features/identity/host-api.ts +3 -2
  50. package/client/features/identity/store.ts +1 -7
  51. package/client/features/onboarding/agent-setup-step.tsx +8 -8
  52. package/client/features/onboarding/onboarding-page.tsx +3 -2
  53. package/client/features/onboarding/workspace-setup-step.tsx +1 -1
  54. package/client/features/overview/api.ts +3 -5
  55. package/client/features/overview/default/registry.tsx +1 -1
  56. package/client/features/overview/default/views-widget.tsx +2 -2
  57. package/client/features/overview/hidden-panel.tsx +7 -5
  58. package/client/features/overview/overview.tsx +18 -16
  59. package/client/features/overview/workspace-name.tsx +2 -2
  60. package/client/features/scratchpad/scratchpad.tsx +9 -7
  61. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +13 -5
  62. package/client/features/views/api.ts +66 -23
  63. package/client/features/views/use-view-actions.ts +10 -41
  64. package/client/features/views/view-manager.tsx +1 -1
  65. package/client/features/views/view-submission.ts +2 -21
  66. package/client/features/workspace/add/api.ts +5 -4
  67. package/client/features/workspace/add/create-workspace-dialog.tsx +12 -9
  68. package/client/features/workspace/add/import-workspace-dialog.tsx +7 -7
  69. package/client/features/workspace/add/use-workspace-import.ts +10 -10
  70. package/client/features/workspace/add/workspace-agent-options.ts +21 -20
  71. package/client/features/workspace/add/workspace-agent-selector.tsx +11 -11
  72. package/client/features/workspace/api.ts +60 -13
  73. package/client/features/workspace/harness-transition.ts +7 -13
  74. package/client/features/workspace/remote.ts +25 -0
  75. package/client/features/workspace/settings/api.ts +7 -12
  76. package/client/features/workspace/settings/connectors-settings.tsx +3 -3
  77. package/client/features/workspace/settings/general-settings.tsx +8 -8
  78. package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
  79. package/client/features/workspace/setup/workspace-recovery-states.tsx +43 -14
  80. package/client/features/workspace/setup/workspace-setup.tsx +6 -6
  81. package/client/features/workspace/tab-resolution.ts +1 -8
  82. package/client/features/workspace/use-workspace-navigation.ts +11 -7
  83. package/client/features/workspace/workspace-content.tsx +24 -31
  84. package/client/features/workspace/workspace-frame.tsx +13 -26
  85. package/client/features/workspace/workspace-layout-context.tsx +45 -12
  86. package/client/features/workspace/workspace-menu.tsx +2 -2
  87. package/client/features/workspace/workspace-pane.tsx +22 -0
  88. package/client/features/workspace/workspace-pending-screen.tsx +1 -1
  89. package/client/features/workspace/workspace-preferences.ts +91 -0
  90. package/client/features/workspace/workspace-presentation.tsx +12 -16
  91. package/client/features/workspace/workspace-screen.tsx +2 -2
  92. package/client/features/workspace/workspace-state.ts +42 -16
  93. package/client/features/workspace/workspace-tabs.tsx +1 -1
  94. package/client/features/workspace/workspace-test-utils.ts +23 -0
  95. package/client/runtime/use-workspace-events.ts +14 -0
  96. package/client/runtime/workspace-events.ts +9 -9
  97. package/client/store/ui.ts +24 -9
  98. package/client/store/workspace-session.ts +30 -0
  99. package/dist/chunk-0h4zypgf.js +1 -0
  100. package/dist/chunk-1tksq43z.js +72 -0
  101. package/dist/chunk-6gxf0xr8.js +5 -0
  102. package/dist/chunk-a865c7x4.js +1 -0
  103. package/dist/chunk-f44cs6mw.js +2 -0
  104. package/dist/chunk-h3qag4a6.js +2 -0
  105. package/dist/chunk-kffcah9w.css +1 -0
  106. package/dist/chunk-q2tpy0h7.js +2 -0
  107. package/dist/chunk-r95acex1.js +546 -0
  108. package/dist/chunk-w5h9grdr.js +1 -0
  109. package/dist/{chunk-th91xfnp.js → chunk-xj1pjhng.js} +1 -1
  110. package/dist/index.html +1 -1
  111. package/lib/harness-instructions.ts +4 -4
  112. package/lib/harness-types.ts +13 -0
  113. package/lib/moi-context.ts +19 -5
  114. package/lib/types.ts +38 -54
  115. package/lib/workspace-config.ts +48 -0
  116. package/lib/workspace-layout.ts +5 -24
  117. package/package.json +5 -2
  118. package/server/AGENTS.md +1 -1
  119. package/server/README.md +36 -31
  120. package/server/api/harnesses.ts +5 -5
  121. package/server/api/index.ts +268 -162
  122. package/server/applets/index.ts +15 -9
  123. package/server/applets/views.ts +2 -17
  124. package/server/applets/widgets.ts +3 -2
  125. package/server/cli/commands/config.ts +8 -20
  126. package/server/cli/commands/hermes.ts +2 -2
  127. package/server/cli/commands/init.ts +102 -54
  128. package/server/cli/commands/openclaw.ts +2 -2
  129. package/server/cli/commands/refresh.ts +10 -1
  130. package/server/cli/commands/remote.ts +330 -0
  131. package/server/cli/commands/skill.ts +4 -4
  132. package/server/cli/commands/tabs.ts +5 -12
  133. package/server/cli/control.ts +35 -4
  134. package/server/cli/index.ts +10 -6
  135. package/server/cli/remote-command.ts +77 -0
  136. package/server/cli/remote-control.ts +73 -0
  137. package/server/cli/remote-operations.ts +247 -0
  138. package/server/collab/config.ts +3 -3
  139. package/server/collab/skill/index.ts +3 -3
  140. package/server/control.ts +47 -12
  141. package/server/harness/acp/session.ts +4 -4
  142. package/server/harness/auth.ts +26 -31
  143. package/server/harness/claude-code/index.ts +1 -1
  144. package/server/harness/codex/discovery.ts +1 -1
  145. package/server/harness/codex/session.ts +1 -1
  146. package/server/harness/detect.ts +14 -19
  147. package/server/harness/executable.ts +10 -10
  148. package/server/harness/hermes/NOTES.md +2 -2
  149. package/server/harness/hermes/index.ts +1 -1
  150. package/server/harness/install.ts +11 -11
  151. package/server/harness/openclaw/index.ts +1 -1
  152. package/server/harness/registry.ts +7 -6
  153. package/server/harness/types.ts +4 -4
  154. package/server/onboarding/jobs.ts +2 -2
  155. package/server/operations/commands.ts +46 -0
  156. package/server/operations/files.ts +148 -0
  157. package/server/operations/server.ts +206 -0
  158. package/server/remote/agent.ts +103 -0
  159. package/server/remote/broker-client.ts +76 -0
  160. package/server/remote/broker.ts +81 -0
  161. package/server/remote/client.ts +725 -0
  162. package/server/remote/errors.ts +2 -0
  163. package/server/remote/routes.ts +121 -0
  164. package/server/remote/workspace.ts +34 -0
  165. package/server/scratchpad/document.ts +33 -12
  166. package/server/scratchpad/executor.ts +16 -7
  167. package/server/sessions/config.ts +8 -5
  168. package/server/sessions/pending-views.ts +17 -0
  169. package/server/sessions/send-message.ts +102 -0
  170. package/server/sessions/view-sessions.ts +9 -101
  171. package/server/skills/locations.ts +4 -4
  172. package/server/skills/update.ts +11 -11
  173. package/server/skills/version.ts +7 -7
  174. package/server/skills/workspace.ts +13 -11
  175. package/server/web.ts +13 -9
  176. package/server/workspace-state/file.ts +4 -0
  177. package/server/workspace-state/index.ts +0 -4
  178. package/server/workspaces/api.ts +24 -0
  179. package/server/workspaces/change-harness.ts +15 -26
  180. package/server/workspaces/import.ts +4 -4
  181. package/server/workspaces/init.ts +15 -13
  182. package/server/workspaces/layout.ts +60 -66
  183. package/server/workspaces/registry.ts +43 -18
  184. package/server/workspaces/shared.ts +74 -0
  185. package/server/workspaces/tabs.ts +5 -12
  186. package/skill/SKILL.md +80 -19
  187. package/skill/references/SCRATCHPAD.md +4 -0
  188. package/skill/references/UI-COMPONENTS.md +1 -1
  189. package/client/api/app-ui-keys.ts +0 -6
  190. package/client/features/chat/sessions/browser-tab-state.ts +0 -43
  191. package/client/features/collab/members/keys.ts +0 -6
  192. package/client/features/workspace/browser-tab-state.ts +0 -51
  193. package/client/features/workspace/layout-save.ts +0 -13
  194. package/dist/chunk-3smkkcfw.js +0 -546
  195. package/dist/chunk-47h9c2qy.js +0 -2
  196. package/dist/chunk-8qed2gqp.js +0 -75
  197. package/dist/chunk-8zy3vesm.js +0 -1
  198. package/dist/chunk-a47zy276.js +0 -2
  199. package/dist/chunk-g4c1nte9.css +0 -1
  200. package/dist/chunk-kcactdr4.js +0 -2
  201. package/dist/chunk-m8bhx6tw.js +0 -1
  202. package/dist/chunk-pf19zcrn.js +0 -2
  203. package/dist/chunk-ygzxah0e.js +0 -1
  204. package/lib/workspace-types.ts +0 -13
  205. package/server/workspace-state/legacy-migration.ts +0 -79
@@ -1,3 +1,8 @@
1
+ import { openSharedWorkspace } from '../workspaces/shared'
2
+ import { executeScratchOp } from '../scratchpad/executor'
3
+ import type { ScratchOp, WorkspaceInfoResponse } from '@/lib/types'
4
+ import { workspaceApiBase, parseRemoteWorkspaceTarget } from '@/lib/workspace-config'
5
+ import { loadWorkspaceFileConfig } from '../workspaces/layout'
1
6
  import { resolveWorkspaceEnv } from '../workspaces/env'
2
7
  import { changeWorkspaceHarness } from '../workspaces/change-harness'
3
8
  import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition'
@@ -19,11 +24,10 @@ import type {
19
24
  AppletThumbnailBatch,
20
25
  AppSettings,
21
26
  HarnessAvailability,
22
- SelectedSessionScope,
23
27
  UploadInfo,
24
28
  WorkspaceHarness,
25
29
  WorkspaceEntry,
26
- WorkspaceType
30
+ HarnessType
27
31
  } from '@/lib/types'
28
32
  import { isWorkspaceTabId } from '@/lib/workspace-tabs'
29
33
 
@@ -34,7 +38,7 @@ import { harnesses } from './harnesses'
34
38
  import { clientAppConfig, createdWorkspacesRoot, getAppConfig } from '../app-config'
35
39
  import { getAppSettings, pickAppSettingsPatch, saveAppSettings } from '../app-settings'
36
40
  import { appletForModule, recordAppletError } from '../applets/log'
37
- import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from '../applets'
41
+ import { parseAppletTail, serveWorkspaceFile } from '../applets'
38
42
  import { applyEnvChanged } from '../workspaces/env-apply'
39
43
  import { publishEvent } from '../events'
40
44
  import { callFunction, parseFunctionPath } from '../applets/functions'
@@ -74,7 +78,8 @@ import {
74
78
  import { saveSessionConfig } from '../sessions/config'
75
79
  import type { SessionConfigPatch } from '../sessions/config'
76
80
  import { archiveWorkspaceSession } from '../sessions/archive'
77
- import { getWorkspaceState } from '../workspace-state'
81
+ import { getWorkspaceState, updateWorkspaceState } from '../workspace-state'
82
+ import { normalizeOpenTabs } from '@/lib/workspace-layout'
78
83
  import { DIST_DIR, prebuilt } from '../static'
79
84
  import { getWorkspaceSkillsStatus, updateWorkspaceSkills } from '../skills/update'
80
85
  import { serveWorkspaceImagePreview } from '../workspaces/preview'
@@ -83,6 +88,7 @@ import { requiredEnvFor } from '../workspaces/required-env'
83
88
  import {
84
89
  deleteView,
85
90
  listCompiledViews,
91
+ getWorkspaceViews,
86
92
  listViews,
87
93
  serveView,
88
94
  updateViewTitle,
@@ -112,7 +118,7 @@ import {
112
118
  updateInProgress
113
119
  } from '../update'
114
120
 
115
- // The resolved workspace is stashed on the context by `withWorkspace`, so every
121
+ // The resolved workspace is stashed on the context by the workspace middleware, so every
116
122
  // `/api/workspaces/:id/*` handler can read it without re-querying the registry.
117
123
  type ApiEnv = { Variables: { ws: WorkspaceEntry } }
118
124
 
@@ -160,62 +166,79 @@ async function handleFunctionCall(
160
166
  }
161
167
  }
162
168
 
163
- // Resolve `:id` to a registered workspace once, 404 if unknown, and stash it on
164
- // the context. Mounted on the single-workspace sub-app so every nested route
165
- // shares the lookup instead of repeating `getWorkspace(...) ?? 404`.
166
- const withWorkspace = createMiddleware<ApiEnv>(async (c, next) => {
167
- const id = c.req.param('id')
168
- if (!id) return c.text('Workspace not found', 404)
169
- let release: (() => void) | undefined
170
- try {
171
- if (c.req.method !== 'GET' && !c.req.path.endsWith('/harness'))
172
- release = reserveWorkspaceOperation(id)
173
- const ws = await getWorkspace(id)
174
- if (!ws) return c.text('Workspace not found', 404)
175
- c.set('ws', ws)
176
- await next()
177
- } catch (error) {
178
- if (error instanceof HarnessTransitionError) return c.text(error.message, 409)
179
- throw error
180
- } finally {
181
- release?.()
182
- }
183
- })
169
+ // Resolve the workspace and enforce the route's storage boundary. Personal
170
+ // routes use this Moi's chats, agent and pending views, including for a remote
171
+ // reference. Shared content must be requested at the owner's workspace address.
172
+ function workspaceAccess(
173
+ scope: 'personal' | 'owner',
174
+ { reserveOperation = true }: { reserveOperation?: boolean } = {}
175
+ ) {
176
+ return createMiddleware<ApiEnv>(async (c, next) => {
177
+ const id = c.req.param('id')
178
+ if (!id) return c.text('Workspace not found', 404)
179
+ let release: (() => void) | undefined
180
+ try {
181
+ if (reserveOperation && c.req.method !== 'GET') release = reserveWorkspaceOperation(id)
182
+ const ws = await getWorkspace(id)
183
+ if (!ws) return c.text('Workspace not found', 404)
184
+ if (ws.remote && getAppConfig().environment !== 'cloud')
185
+ return c.text('Remote workspaces require Cloud mode', 403)
186
+ if (ws.remote && scope === 'owner') return c.text('Use the owner workspace address', 404)
187
+ c.set('ws', ws)
188
+ await next()
189
+ } catch (error) {
190
+ if (error instanceof HarnessTransitionError) return c.text(error.message, 409)
191
+ throw error
192
+ } finally {
193
+ release?.()
194
+ }
195
+ })
196
+ }
197
+
198
+ const personalWorkspace = workspaceAccess('personal')
199
+ const ownerWorkspace = workspaceAccess('owner')
184
200
 
185
201
  // ---- single workspace: /api/workspaces/:id/* --------------------------------
186
202
  const one = new Hono<ApiEnv>()
187
- one.use('*', withWorkspace)
188
- one.patch('/harness', async c => {
203
+ // Switching agents takes its own exclusive lock.
204
+ one.patch('/harness', workspaceAccess('personal', { reserveOperation: false }), async c => {
189
205
  if (getAppConfig().demo) return c.text('Changing agents is unavailable in the demo', 403)
190
206
  const body = await c.req.json().catch(() => null)
191
- if (!body || !['claude-code', 'codex'].includes(body.type))
207
+ if (!body || !['claude-code', 'codex'].includes(body.harness))
192
208
  return c.text('Invalid agent selection', 400)
193
209
  try {
194
- return c.json(await changeWorkspaceHarness(c.get('ws'), body.type))
210
+ return c.json(await changeWorkspaceHarness(c.get('ws'), body.harness))
195
211
  } catch (error) {
196
212
  if (error instanceof HarnessTransitionError) return c.text(error.message, 409)
197
213
  throw error
198
214
  }
199
215
  })
200
216
 
201
- one.get('/widgets', c => listWidgets(c.get('ws').path))
217
+ one.get('/widgets', ownerWorkspace, c => listWidgets(c.get('ws').path))
202
218
 
203
219
  // Widget bundle: the compiled ESM for one widget, dynamically imported by the
204
220
  // client (useWidget). Sits beside the GET .../widgets list above — the exact
205
221
  // path lists, `/*` serves a file from the bundle dir (`<name>/<file>`:
206
222
  // index.js, a chunk, or a hashed asset).
207
- one.get('/widgets/*', c => {
223
+ one.get('/widgets/*', ownerWorkspace, c => {
208
224
  const ws = c.get('ws')
209
225
  const { name, file } = parseAppletTail(c.req.url, ws.id, 'widgets')
210
226
  if (!name) return c.text('Not found', 404)
211
- return serveWidget(name, file, ws.path, apiBaseFor(ws.id), c.req.header('if-none-match'))
227
+ return serveWidget(name, file, ws.path, workspaceApiBase(ws.id), c.req.header('if-none-match'))
212
228
  })
213
229
 
214
230
  // Views — full-screen agent apps. Mirrors the widget pair above: the exact path
215
231
  // lists (in manifest/nav order), `/*` serves one bundle file.
216
- one.get('/views', c => listViews(c.get('ws').path))
232
+ one.get('/views', ownerWorkspace, async c =>
233
+ c.req.query('includePending') === 'true'
234
+ ? c.json({ views: await getWorkspaceViews(c.get('ws')) })
235
+ : listViews(c.get('ws').path)
236
+ )
217
237
 
218
- one.patch('/views/:viewId', async c => {
238
+ const OWNER_VIEW = 'Use the owner workspace address for compiled views'
239
+
240
+ // Pending views are personal; these handlers also accept compiled views on the owner.
241
+ one.patch('/views/:viewId', personalWorkspace, async c => {
219
242
  const ws = c.get('ws')
220
243
  const body = await c.req.json().catch(() => null)
221
244
  if (await getPendingView(ws, c.req.param('viewId'))) {
@@ -238,6 +261,7 @@ one.patch('/views/:viewId', async c => {
238
261
  throw error
239
262
  }
240
263
  }
264
+ if (ws.remote) return c.text(OWNER_VIEW, 404)
241
265
  const title = typeof body?.title === 'string' ? body.title.trim() : ''
242
266
  if (!title) return c.text('Expected { title: string }', 400)
243
267
 
@@ -250,7 +274,7 @@ one.patch('/views/:viewId', async c => {
250
274
  }
251
275
  })
252
276
 
253
- one.delete('/views/:viewId', async c => {
277
+ one.delete('/views/:viewId', personalWorkspace, async c => {
254
278
  const ws = c.get('ws')
255
279
  try {
256
280
  const viewId = c.req.param('viewId')
@@ -262,7 +286,8 @@ one.delete('/views/:viewId', async c => {
262
286
  .map(session => session.sessionId)
263
287
  )
264
288
  await discardPendingView(ws, viewId, active)
265
- } else await deleteView(publishEvent, ws, viewId)
289
+ } else if (ws.remote) return c.text(OWNER_VIEW, 404)
290
+ else await deleteView(publishEvent, ws, viewId)
266
291
  return c.body(null, 204)
267
292
  } catch (error) {
268
293
  if (error instanceof ViewMutationError || error instanceof PendingViewError)
@@ -271,25 +296,24 @@ one.delete('/views/:viewId', async c => {
271
296
  }
272
297
  })
273
298
 
274
- one.get('/views/*', c => {
299
+ one.get('/views/*', ownerWorkspace, c => {
275
300
  const ws = c.get('ws')
276
301
  const { name, file } = parseAppletTail(c.req.url, ws.id, 'views')
277
302
  if (!name) return c.text('Not found', 404)
278
- return serveView(name, file, ws.path, apiBaseFor(ws.id), c.req.header('if-none-match'))
303
+ return serveView(name, file, ws.path, workspaceApiBase(ws.id), c.req.header('if-none-match'))
279
304
  })
280
305
 
281
- one.post('/views', async c => {
306
+ one.post('/views', personalWorkspace, async c => {
282
307
  const ws = c.get('ws')
283
308
  return c.json(await createPendingView(ws), 201)
284
309
  })
285
310
 
286
- one.post('/views/:viewId/submit', async c => {
311
+ one.post('/views/:viewId/submit', personalWorkspace, async c => {
287
312
  const ws = c.get('ws')
288
313
  const body = await c.req.json<{
289
314
  requirements?: string
290
315
  sessionId?: string
291
316
  optimisticId?: string
292
- selectedSessionScope?: SelectedSessionScope
293
317
  model?: string
294
318
  effort?: string
295
319
  speedMode?: SpeedMode
@@ -302,13 +326,6 @@ one.post('/views/:viewId/submit', async c => {
302
326
  if (body.optimisticId !== undefined && typeof body.optimisticId !== 'string') {
303
327
  return c.text('Invalid optimisticId', 400)
304
328
  }
305
- if (
306
- body.selectedSessionScope !== undefined &&
307
- body.selectedSessionScope !== 'shared' &&
308
- body.selectedSessionScope !== 'browser-tab'
309
- ) {
310
- return c.text('Invalid selectedSessionScope', 400)
311
- }
312
329
  const attachments = body.attachments ?? []
313
330
  if (!isMessageAttachments(attachments)) return c.text('Invalid attachments', 400)
314
331
  for (const attachment of attachments) {
@@ -317,13 +334,12 @@ one.post('/views/:viewId/submit', async c => {
317
334
  if (!getUpload(ws.id, attachment.uploadId))
318
335
  return c.text('Attachment not found or expired', 400)
319
336
  }
320
- const availability = await workspaceTypeAvailability(ws.type ?? 'claude-code')
337
+ const availability = await harnessTypeAvailability(ws.harness ?? 'claude-code')
321
338
  if (availability.status !== 'available') return c.text(availability.reason, 400)
322
339
  try {
323
340
  const result = await submitView(ws, c.req.param('viewId'), {
324
341
  requirements: body.requirements,
325
342
  sessionId: typeof body.sessionId === 'string' ? body.sessionId : undefined,
326
- selectedSessionScope: body.selectedSessionScope,
327
343
  attachments,
328
344
  optimisticId: body.optimisticId,
329
345
  model: typeof body.model === 'string' ? body.model : undefined,
@@ -331,7 +347,7 @@ one.post('/views/:viewId/submit', async c => {
331
347
  speedMode: isSpeedMode(body.speedMode) ? body.speedMode : undefined,
332
348
  stream: body.stream === true ? true : undefined
333
349
  })
334
- return c.json(result)
350
+ return c.json({ ...result, state: await getWorkspaceState(ws) })
335
351
  } catch (err) {
336
352
  if (err instanceof PendingViewError) return c.text(err.message, err.status)
337
353
  if (err instanceof ViewStartupError)
@@ -345,18 +361,18 @@ one.post('/views/:viewId/submit', async c => {
345
361
  // dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions
346
362
  // are allowed — the workspace holds secrets, and this route is unauthenticated.
347
363
  // localhost binding is NOT the guard.
348
- one.get('/files/*', c => {
364
+ one.get('/files/*', ownerWorkspace, c => {
349
365
  const ws = c.get('ws')
350
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/files/`)[1] ?? ''
366
+ const tail = new URL(c.req.url).pathname.split(`${workspaceApiBase(ws.id)}/files/`)[1] ?? ''
351
367
  return serveWorkspaceFile(ws.path, tail, c.req.header('range'), c.req.header('if-none-match'))
352
368
  })
353
369
 
354
370
  // Applet RPC — the home for server-function calls from a bundle. The bundle's
355
371
  // sentinel base resolves to `/api/workspaces/<id>`, so it POSTs to
356
372
  // `…/rpc/<module>/<fn>`.
357
- one.post('/rpc/*', c => {
373
+ one.post('/rpc/*', ownerWorkspace, c => {
358
374
  const ws = c.get('ws')
359
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/rpc/`)[1] ?? ''
375
+ const tail = new URL(c.req.url).pathname.split(`${workspaceApiBase(ws.id)}/rpc/`)[1] ?? ''
360
376
  return handleFunctionCall(c.req.raw, tail, ws.path)
361
377
  })
362
378
 
@@ -367,7 +383,7 @@ one.post('/rpc/*', c => {
367
383
  // sources (`build`/`rpc` are server-recorded and can't be spoofed by a tab),
368
384
  // pattern-check the applet name, cap the batch size; applets/log.ts caps string
369
385
  // lengths.
370
- one.post('/applet-log', async c => {
386
+ one.post('/applet-log', ownerWorkspace, async c => {
371
387
  let body: { events?: unknown }
372
388
  try {
373
389
  body = await c.req.json()
@@ -410,9 +426,9 @@ one.post('/applet-log', async c => {
410
426
  // Downscaled image preview of a workspace file. The chat's expanded tool rows
411
427
  // use this to show the picture an agent `Read` — same guards as /files/ above,
412
428
  // images only, resized server-side (see server/workspaces/preview.ts).
413
- one.get('/preview/*', c => {
429
+ one.get('/preview/*', personalWorkspace, c => {
414
430
  const ws = c.get('ws')
415
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/preview/`)[1] ?? ''
431
+ const tail = new URL(c.req.url).pathname.split(`${workspaceApiBase(ws.id)}/preview/`)[1] ?? ''
416
432
  return serveWorkspaceImagePreview(ws.path, tail, c.req.header('if-none-match'))
417
433
  })
418
434
 
@@ -421,7 +437,7 @@ one.get('/preview/*', c => {
421
437
  // upload ids the chat WS frame references. Images are downscaled and inlined as
422
438
  // vision blocks at send time; other files are referenced by a temp path. See
423
439
  // server/uploads.ts and dev/file-uploads.md.
424
- one.post('/uploads', async c => {
440
+ one.post('/uploads', personalWorkspace, async c => {
425
441
  const ws = c.get('ws')
426
442
  let form: FormData
427
443
  try {
@@ -456,7 +472,7 @@ one.post('/uploads', async c => {
456
472
  })
457
473
 
458
474
  // Existing workspace documents enter the same upload pipeline without a browser round trip.
459
- one.post('/uploads/from-path', async c => {
475
+ one.post('/uploads/from-path', personalWorkspace, async c => {
460
476
  const body: unknown = await c.req.json().catch(() => null)
461
477
  if (!body || typeof body !== 'object' || !('path' in body) || typeof body.path !== 'string') {
462
478
  return c.text('Choose a file from this workspace', 400)
@@ -482,7 +498,7 @@ one.post('/uploads/from-path', async c => {
482
498
  // base64 data URL so the transcript broadcast / client cache stay small. The id
483
499
  // is content-addressed (sha256), so the response is immutable while it lives —
484
500
  // let the browser cache it for the store's TTL.
485
- one.get('/uploads/:uploadId', c => {
501
+ one.get('/uploads/:uploadId', personalWorkspace, c => {
486
502
  const u = getUpload(c.get('ws').id, c.req.param('uploadId'))
487
503
  if (!u) return c.text('Not found or expired', 404)
488
504
  const body = u.data ? new Uint8Array(u.data) : u.path ? Bun.file(u.path) : null
@@ -496,18 +512,25 @@ one.get('/uploads/:uploadId', c => {
496
512
  })
497
513
  })
498
514
 
499
- // Per-user chat state: pin, the chat each tab shows, per-chat settings and
500
- // fork history, and views being built. Every write below answers with the new
501
- // state; other clients get it as `state:changed`.
502
- one.get('/state', async c => c.json(await getWorkspaceState(c.get('ws'))))
515
+ // Personal state writes return the latest snapshot and publish `state:changed`.
516
+ one.get('/state', personalWorkspace, async c => c.json(await getWorkspaceState(c.get('ws'))))
517
+
518
+ one.put('/state/tabs', personalWorkspace, async c => {
519
+ const body = await c.req.json().catch(() => null)
520
+ const ws = c.get('ws')
521
+ await updateWorkspaceState(ws, state => {
522
+ state.openTabs = normalizeOpenTabs(body?.openTabs)
523
+ })
524
+ return c.json(await getWorkspaceState(ws))
525
+ })
503
526
 
504
527
  // The agent's chats. Tab ownership and settings come from `/state`.
505
- one.get('/sessions', async c => {
528
+ one.get('/sessions', personalWorkspace, async c => {
506
529
  const ws = c.get('ws')
507
530
  return c.json(await harnessFor(ws).listSessions(ws))
508
531
  })
509
532
 
510
- one.put('/sessions/:sessionId/pin', async c => {
533
+ one.put('/sessions/:sessionId/pin', personalWorkspace, async c => {
511
534
  const ws = c.get('ws')
512
535
  const sessionId = c.req.param('sessionId')
513
536
  const harness = harnessFor(ws)
@@ -520,7 +543,7 @@ one.put('/sessions/:sessionId/pin', async c => {
520
543
  return c.json(await getWorkspaceState(ws))
521
544
  })
522
545
 
523
- one.delete('/sessions/:sessionId/pin', async c => {
546
+ one.delete('/sessions/:sessionId/pin', personalWorkspace, async c => {
524
547
  const ws = c.get('ws')
525
548
  await unpinSession(ws, c.req.param('sessionId'))
526
549
  return c.json(await getWorkspaceState(ws))
@@ -528,7 +551,7 @@ one.delete('/sessions/:sessionId/pin', async c => {
528
551
 
529
552
  // Show the chat in a tab. `ifMatch` (a chat id, or null for none) applies the
530
553
  // change only while the tab still shows that chat.
531
- one.put('/sessions/:sessionId/selection', async c => {
554
+ one.put('/sessions/:sessionId/selection', personalWorkspace, async c => {
532
555
  const ws = c.get('ws')
533
556
  const body: unknown = await c.req.json().catch(() => null)
534
557
  if (!body || typeof body !== 'object') return c.text('Bad request', 400)
@@ -549,7 +572,7 @@ one.put('/sessions/:sessionId/selection', async c => {
549
572
 
550
573
  // Stop showing the chat in a tab, which then opens a new chat. A tab showing
551
574
  // another chat is left alone.
552
- one.delete('/sessions/:sessionId/selection', async c => {
575
+ one.delete('/sessions/:sessionId/selection', personalWorkspace, async c => {
553
576
  const ws = c.get('ws')
554
577
  const body: unknown = await c.req.json().catch(() => null)
555
578
  const tabId = (body as { tabId?: unknown } | null)?.tabId
@@ -559,34 +582,39 @@ one.delete('/sessions/:sessionId/selection', async c => {
559
582
  })
560
583
 
561
584
  // Change run settings. Omitted fields stay; null clears one.
562
- one.patch('/sessions/:sessionId/config', async c => {
563
- const body = await c.req.json().catch(() => null)
564
- if (typeof body !== 'object' || body === null) {
565
- return c.text('Expected a JSON object', 400)
566
- }
567
- const patch: SessionConfigPatch = {}
568
- const record = body as Record<string, unknown>
569
- for (const key of ['model', 'effort'] as const) {
570
- if (!(key in record)) continue
571
- const value = record[key]
572
- if (value !== null && typeof value !== 'string') {
573
- return c.text(`${key} must be a string or null`, 400)
585
+ one.on(
586
+ 'PATCH',
587
+ ['/sessions/:sessionId/config', '/state/chat-defaults'],
588
+ personalWorkspace,
589
+ async c => {
590
+ const body = await c.req.json().catch(() => null)
591
+ if (typeof body !== 'object' || body === null) {
592
+ return c.text('Expected a JSON object', 400)
574
593
  }
575
- patch[key] = value
576
- }
577
- if ('speedMode' in record) {
578
- const value = record.speedMode
579
- if (value !== null && !isSpeedMode(value)) {
580
- return c.text('speedMode must be "normal", "fast", "ultrafast", or null', 400)
594
+ const patch: SessionConfigPatch = {}
595
+ const record = body as Record<string, unknown>
596
+ for (const key of ['model', 'effort'] as const) {
597
+ if (!(key in record)) continue
598
+ const value = record[key]
599
+ if (value !== null && typeof value !== 'string') {
600
+ return c.text(`${key} must be a string or null`, 400)
601
+ }
602
+ patch[key] = value
581
603
  }
582
- patch.speedMode = value
604
+ if ('speedMode' in record) {
605
+ const value = record.speedMode
606
+ if (value !== null && !isSpeedMode(value)) {
607
+ return c.text('speedMode must be "normal", "fast", "ultrafast", or null', 400)
608
+ }
609
+ patch.speedMode = value
610
+ }
611
+ const ws = c.get('ws')
612
+ await saveSessionConfig(ws, c.req.param('sessionId'), patch)
613
+ return c.json(await getWorkspaceState(ws))
583
614
  }
584
- const ws = c.get('ws')
585
- await saveSessionConfig(ws, c.req.param('sessionId'), patch)
586
- return c.json(await getWorkspaceState(ws))
587
- })
615
+ )
588
616
 
589
- one.post('/sessions/:sessionId/archive', async c => {
617
+ one.post('/sessions/:sessionId/archive', personalWorkspace, async c => {
590
618
  const ws = c.get('ws')
591
619
  const harness = harnessFor(ws)
592
620
  const sessionId = c.req.param('sessionId')
@@ -605,13 +633,13 @@ one.post('/sessions/:sessionId/archive', async c => {
605
633
  }
606
634
  })
607
635
 
608
- one.get('/sessions/:sessionId/events', async c => {
636
+ one.get('/sessions/:sessionId/events', personalWorkspace, async c => {
609
637
  const ws = c.get('ws')
610
638
  const sessionId = c.req.param('sessionId')
611
639
  return c.json(await harnessFor(ws).sessionEvents(ws, sessionId))
612
640
  })
613
641
 
614
- one.get('/mcp', async c => {
642
+ one.get('/mcp', personalWorkspace, async c => {
615
643
  const ws = c.get('ws')
616
644
  const harness = harnessFor(ws)
617
645
  if (c.req.query('stream') !== 'true') return c.json((await harness.mcpStatus?.(ws)) ?? [])
@@ -645,13 +673,13 @@ one.get('/mcp', async c => {
645
673
  // (Codex: app-server JSON-RPC, both directions; Claude Code: raw SDK messages
646
674
  // + enqueued inputs) and the exact frames the server pushed to chat clients.
647
675
  // `sinceWire`/`sinceBroadcast` are seq cursors so the page can poll deltas.
648
- one.get('/harness/debug', async c => {
676
+ one.get('/harness/debug', personalWorkspace, async c => {
649
677
  const ws = c.get('ws')
650
678
  const harness = harnessFor(ws)
651
679
  const sinceWire = Number(c.req.query('sinceWire') ?? 0) || 0
652
680
  const sinceBroadcast = Number(c.req.query('sinceBroadcast') ?? 0) || 0
653
681
  return c.json({
654
- provider: harness.id,
682
+ harness: harness.id,
655
683
  process: (await harness.debugInfo?.(ws)) ?? null,
656
684
  wire: getWireLog(harness.wireScope?.(ws) ?? ws.id, sinceWire),
657
685
  broadcasts: getClientFrameLog(ws.id, sinceBroadcast)
@@ -660,7 +688,7 @@ one.get('/harness/debug', async c => {
660
688
 
661
689
  // Per-workspace env vars. GET returns the effective view (discovered `.env` + UI
662
690
  // custom secrets + scopes + declared-required keys; values masked).
663
- one.get('/env', async c => {
691
+ one.get('/env', personalWorkspace, async c => {
664
692
  const ws = c.get('ws')
665
693
  // Unawaited on purpose: getWorkspaceEnvView loads it in parallel with the
666
694
  // env stores (manifest reads and env reads are independent).
@@ -671,7 +699,7 @@ one.get('/env', async c => {
671
699
  // then reaps the workspace's function worker and idle agent sessions so the next
672
700
  // call/message picks up the change (env is frozen at spawn — a hard restart is
673
701
  // the only way).
674
- one.put('/env', async c => {
702
+ one.put('/env', personalWorkspace, async c => {
675
703
  const ws = c.get('ws')
676
704
  const patch = parseEnvUpdate(await c.req.json().catch(() => null))
677
705
  if (typeof patch === 'string') return c.text(patch, 400)
@@ -689,24 +717,24 @@ one.put('/env', async c => {
689
717
  return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
690
718
  })
691
719
 
692
- one.get('/skills', async c => {
720
+ one.get('/skills', personalWorkspace, async c => {
693
721
  const ws = c.get('ws')
694
- return c.json(await getWorkspaceSkillsStatus(ws.path, ws.type))
722
+ return c.json(await getWorkspaceSkillsStatus(ws.path, ws.harness))
695
723
  })
696
724
 
697
- one.post('/skills/update', async c => {
725
+ one.post('/skills/update', personalWorkspace, async c => {
698
726
  const ws = c.get('ws')
699
- const result = await updateWorkspaceSkills(ws.path, ws.type ?? 'claude-code')
727
+ const result = await updateWorkspaceSkills(ws.path, ws.harness ?? 'claude-code')
700
728
  return c.json(result.status)
701
729
  })
702
730
 
703
731
  // Workspace configuration and models. Shared account status is served by
704
732
  // /harnesses/status; only workspace overrides and gateways are probed here.
705
- one.get('/harness', async c => {
733
+ one.get('/harness', personalWorkspace, async c => {
706
734
  const ws = c.get('ws')
707
735
  const harness = harnessFor(ws)
708
736
  const capabilities = {
709
- provider: harness.id,
737
+ harness: harness.id,
710
738
  supportsStreaming: harness.capabilities.supportsStreaming,
711
739
  supportsArchiving: Boolean(harness.archiveSession)
712
740
  }
@@ -756,11 +784,11 @@ one.get('/harness', async c => {
756
784
  })
757
785
 
758
786
  // Workspace identity. Uploads use the image route below.
759
- one.get('/config', async c => {
787
+ one.get('/config', ownerWorkspace, async c => {
760
788
  return c.json(await getWorkspaceConfig(c.get('ws').path))
761
789
  })
762
790
 
763
- one.put('/config', async c => {
791
+ one.put('/config', ownerWorkspace, async c => {
764
792
  const ws = c.get('ws')
765
793
  const parsed: unknown = await c.req.json().catch(() => null)
766
794
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
@@ -779,7 +807,7 @@ one.put('/config', async c => {
779
807
  return c.text('Expected a workspace config field', 400)
780
808
  }
781
809
  await setWorkspaceConfig(ws.path, { name, icon })
782
- publishEvent({ type: 'workspace:updated', origin: eventOrigin(body.origin) })
810
+ publishEvent({ type: 'workspace:updated', workspaceId: ws.id, origin: eventOrigin(body.origin) })
783
811
  return c.json(await getWorkspaceConfig(ws.path))
784
812
  })
785
813
 
@@ -789,11 +817,29 @@ one.put('/config', async c => {
789
817
  // `origin` is the writing tab's id — echoed in the broadcast so that tab can
790
818
  // ignore its own save. This is the browser's write path; the agent's draws are
791
819
  // written server-side (see server/scratchpad/executor.ts). See docs/moi-scratchpad.md.
792
- one.get('/scratchpad', async c => {
820
+ one.post('/scratchpad/ops', ownerWorkspace, async c => {
821
+ try {
822
+ const form = await c.req.formData()
823
+ const op = JSON.parse(String(form.get('op'))) as ScratchOp | null
824
+ if (!op || typeof op.kind !== 'string') return c.text('Invalid scratchpad edit', 400)
825
+ let imageBytes: Uint8Array | undefined
826
+ if (op.kind === 'add-image') {
827
+ const image = form.get('image')
828
+ if (!(image instanceof File)) return c.text('Image file is required', 400)
829
+ imageBytes = new Uint8Array(await image.arrayBuffer())
830
+ }
831
+ const ws = c.get('ws')
832
+ return c.json(await executeScratchOp(ws.path, ws.id, op, imageBytes))
833
+ } catch (error) {
834
+ return c.text(error instanceof Error ? error.message : 'Scratchpad edit failed', 400)
835
+ }
836
+ })
837
+
838
+ one.get('/scratchpad', ownerWorkspace, async c => {
793
839
  return c.json(await loadScratchpadDoc(c.get('ws').path))
794
840
  })
795
841
 
796
- one.put('/scratchpad', async c => {
842
+ one.put('/scratchpad', ownerWorkspace, async c => {
797
843
  const ws = c.get('ws')
798
844
  const body = await c.req.json().catch(() => null)
799
845
  if (!body || typeof body !== 'object' || !body.document) {
@@ -813,7 +859,7 @@ one.put('/scratchpad', async c => {
813
859
  // never inlined as base64 in the JSON (see server/scratchpad/assets.ts). The
814
860
  // browser's TLAssetStore POSTs the raw file here on paste and resolves `asset:`
815
861
  // srcs back through the GET when rendering.
816
- one.post('/scratchpad/assets', async c => {
862
+ one.post('/scratchpad/assets', ownerWorkspace, async c => {
817
863
  const length = Number(c.req.header('content-length') ?? 0)
818
864
  if (length > MAX_ASSET_BYTES) {
819
865
  return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
@@ -829,7 +875,7 @@ one.post('/scratchpad/assets', async c => {
829
875
 
830
876
  // The file name is content-addressed (sha256 of the bytes), so a hit is
831
877
  // immutable — let the browser cache it indefinitely.
832
- one.get('/scratchpad/assets/:file', async c => {
878
+ one.get('/scratchpad/assets/:file', ownerWorkspace, async c => {
833
879
  const resolved = scratchpadAssetFile(c.get('ws').path, c.req.param('file'))
834
880
  if (!resolved || !(await resolved.file.exists())) return c.text('Not found', 404)
835
881
  return new Response(resolved.file, {
@@ -847,7 +893,7 @@ one.get('/scratchpad/assets/:file', async c => {
847
893
 
848
894
  // Workspace upload. PUT resizes an image to a 128×128 WebP. DELETE resets any
849
895
  // custom icon to the provider default. Both broadcast for a live refresh.
850
- one.put('/icon', async c => {
896
+ one.put('/icon', ownerWorkspace, async c => {
851
897
  const ws = c.get('ws')
852
898
  const bytes = new Uint8Array(await c.req.arrayBuffer())
853
899
  if (bytes.length === 0) return c.text('Empty image body', 400)
@@ -860,39 +906,55 @@ one.put('/icon', async c => {
860
906
  }
861
907
  const workspaceIcon = { type: 'upload', value: icon } as const
862
908
  await setWorkspaceConfig(ws.path, { icon: workspaceIcon })
863
- publishEvent({ type: 'workspace:updated' })
909
+ publishEvent({ type: 'workspace:updated', workspaceId: c.get('ws').id })
864
910
  return c.json({ icon: workspaceIcon })
865
911
  })
866
912
 
867
- one.delete('/icon', async c => {
913
+ one.delete('/icon', ownerWorkspace, async c => {
868
914
  await setWorkspaceConfig(c.get('ws').path, { icon: null })
869
- publishEvent({ type: 'workspace:updated' })
915
+ publishEvent({ type: 'workspace:updated', workspaceId: c.get('ws').id })
870
916
  return c.body(null, 204)
871
917
  })
872
918
 
873
919
  // All info about a single workspace: its persisted layout (widget grid, layout
874
920
  // mode, theme) plus server-resolved metadata. GET reads, PUT writes the layout,
875
921
  // DELETE unregisters.
876
- one.get('/', async c => {
922
+ one.get('/', personalWorkspace, async c => {
877
923
  const ws = c.get('ws')
878
- const layout = await loadLayout(ws.path)
924
+ const config = await loadWorkspaceFileConfig(ws.path)
925
+ if (config.remote) {
926
+ return c.json({
927
+ version: 2,
928
+ remote: config.remote,
929
+ apiBase: workspaceApiBase(config.remote.workspace_id, config.remote.user_id),
930
+ isRemote: true,
931
+ cwd: ws.path,
932
+ // The agent belongs to this visitor, not to the owner's workspace.
933
+ harness: ws.harness,
934
+ agentId: ws.agentId
935
+ } satisfies WorkspaceInfoResponse)
936
+ }
937
+
938
+ const layout = config
879
939
  return c.json({
880
940
  ...layout,
941
+ apiBase: workspaceApiBase(ws.id),
942
+ isRemote: false,
881
943
  // Resolved display name: the settings override, or the folder name.
882
944
  name: layout.name || basename(ws.path),
883
945
  cwd: ws.path,
884
- provider: ws.type,
946
+ harness: ws.harness,
885
947
  agentId: ws.agentId
886
- })
948
+ } satisfies WorkspaceInfoResponse)
887
949
  })
888
950
 
889
951
  // Thumbnail freshness records, without image bytes — the capture hook compares
890
952
  // these against live bundle revisions. Images are served per-applet below.
891
- one.get('/applet-thumbnails', async c =>
953
+ one.get('/applet-thumbnails', ownerWorkspace, async c =>
892
954
  c.json({ thumbnails: await getAppletThumbnailRecords(c.get('ws').path) })
893
955
  )
894
956
 
895
- one.get('/applet-thumbnails/:kind/:name', c => {
957
+ one.get('/applet-thumbnails/:kind/:name', ownerWorkspace, c => {
896
958
  const kind = c.req.param('kind')
897
959
  if (kind !== 'widget' && kind !== 'view') return c.text('Not found', 404)
898
960
  // `<id>` or `<id>:<version>`. Applet ids never contain `:`, and the version
@@ -908,7 +970,7 @@ one.get('/applet-thumbnails/:kind/:name', c => {
908
970
  })
909
971
 
910
972
  // Settled widget and view visits share one batch endpoint and storage path.
911
- one.put('/applet-thumbnails', async c => {
973
+ one.put('/applet-thumbnails', ownerWorkspace, async c => {
912
974
  const body: unknown = await c.req.json().catch(() => null)
913
975
  if (!body || typeof body !== 'object' || Array.isArray(body)) return c.text('Bad request', 400)
914
976
  const input = body as AppletThumbnailBatch
@@ -933,33 +995,35 @@ one.put('/applet-thumbnails', async c => {
933
995
  return c.body(null, 204)
934
996
  })
935
997
 
936
- one.put('/', async c => {
998
+ one.put('/', personalWorkspace, async c => {
937
999
  const ws = c.get('ws')
1000
+ if (ws.remote) {
1001
+ return c.text(
1002
+ 'Remote references contain only the owner address; save shared content to the owner',
1003
+ 403
1004
+ )
1005
+ }
938
1006
  const body = await c.req.json()
939
- if (!body || body.version !== 1) return c.text('Bad request', 400)
1007
+ if (!body || body.version !== 2) return c.text('Bad request', 400)
940
1008
  // `origin` is the writing tab's id, echoed so that tab skips its own event.
941
- const { origin, harness, ...layout } = body
942
- // Preserve server-owned identity (name/icon) across a grid/theme save so the
943
- // client's PUT can't erase a `moi config`-set name. See mergeLayoutForSave.
1009
+ const { origin } = body
1010
+ // Only widgets and theme are taken from the body, so a grid/theme save can't
1011
+ // erase a `moi config`-set name or icon. See mergeLayoutForSave.
944
1012
  const existing = await loadLayout(ws.path)
945
- const next = mergeLayoutForSave(existing, layout)
946
- if (harness !== undefined && harness !== (ws.type ?? 'claude-code')) {
947
- next.selectedModel = existing.selectedModel
948
- next.selectedEffort = existing.selectedEffort
949
- next.selectedSpeedMode = existing.selectedSpeedMode
950
- }
1013
+ const next = mergeLayoutForSave(existing, body)
951
1014
  await saveLayout(next, ws.path)
952
1015
  if (
953
1016
  JSON.stringify(resolveWorkspaceTheme(existing.theme)) !==
954
1017
  JSON.stringify(resolveWorkspaceTheme(next.theme))
955
1018
  ) {
956
- publishEvent({ type: 'theme:updated', origin: eventOrigin(origin) })
1019
+ publishEvent({ type: 'theme:updated', workspaceId: ws.id, origin: eventOrigin(origin) })
957
1020
  }
958
1021
  return c.body(null, 204)
959
1022
  })
960
1023
 
961
- one.delete('/', async c => {
1024
+ one.delete('/', personalWorkspace, async c => {
962
1025
  const ws = c.get('ws')
1026
+ if (ws.remote) return c.text('Leaving remote workspaces is not available yet', 403)
963
1027
  const ok = await removeWorkspace(ws.id)
964
1028
  if (!ok) return c.text('Workspace not found', 404)
965
1029
  harnessFor(ws).stopWorkspace?.(ws.path)
@@ -970,10 +1034,20 @@ one.delete('/', async c => {
970
1034
  // ---- workspace collection: /api/workspaces ----------------------------------
971
1035
  const workspaces = new Hono<ApiEnv>()
972
1036
 
1037
+ // Standalone Moi lists local workspaces only; remote references need Cloud.
1038
+ function visibleWorkspaces(entries: WorkspaceEntry[]) {
1039
+ return getAppConfig().environment === 'cloud' ? entries : entries.filter(entry => !entry.remote)
1040
+ }
1041
+
973
1042
  async function mergeWorkspaceList(entries: WorkspaceEntry[]) {
974
1043
  return Promise.all(
975
1044
  entries.map(async e => {
976
- const layout = await loadLayout(e.path)
1045
+ const layout = await loadWorkspaceFileConfig(e.path).catch(() => null)
1046
+ if (!layout) return e
1047
+ if (layout.remote) {
1048
+ return { ...e, remote: layout.remote, name: layout.remote.workspace_id }
1049
+ }
1050
+
977
1051
  return {
978
1052
  ...e,
979
1053
  name: layout.name ?? e.name,
@@ -988,7 +1062,7 @@ workspaces.get('/', async c => {
988
1062
  // Merge each workspace's live identity and theme over the registry snapshot
989
1063
  // so app-wide workspace lists render the same presentation as the workspace.
990
1064
  const entries = await listWorkspaces()
991
- return c.json(await mergeWorkspaceList(entries))
1065
+ return c.json(await mergeWorkspaceList(visibleWorkspaces(entries)))
992
1066
  })
993
1067
 
994
1068
  workspaces.put('/order', async c => {
@@ -997,12 +1071,16 @@ workspaces.put('/order', async c => {
997
1071
  return c.text('Expected { ids: string[] }', 400)
998
1072
  }
999
1073
  try {
1000
- const entries = await reorderWorkspaces(body.ids)
1074
+ // Hidden remote references keep their place after the visible ones.
1075
+ const all = await listWorkspaces()
1076
+ const visible = new Set(visibleWorkspaces(all).map(entry => entry.id))
1077
+ const hiddenIds = all.filter(entry => !visible.has(entry.id)).map(entry => entry.id)
1078
+ const entries = await reorderWorkspaces([...body.ids, ...hiddenIds])
1001
1079
  // List-only change: a narrow event so clients refetch just the sidebar
1002
1080
  // list, not every per-workspace query (`workspace:updated` also triggers
1003
1081
  // layout refetches in open workspaces).
1004
1082
  publishEvent({ type: 'workspaces-list:updated', origin: eventOrigin(body.origin) })
1005
- return c.json(await mergeWorkspaceList(entries))
1083
+ return c.json(await mergeWorkspaceList(visibleWorkspaces(entries)))
1006
1084
  } catch (err) {
1007
1085
  const message = err instanceof Error ? err.message : String(err)
1008
1086
  return c.text(message, 400)
@@ -1017,17 +1095,43 @@ const DEMO_CREATE_BLOCKED = 'Workspace creation is not available in the Moi demo
1017
1095
 
1018
1096
  workspaces.post('/', async c => {
1019
1097
  if (getAppConfig().demo) return c.text(DEMO_CREATE_BLOCKED, 403)
1020
- const body = await c.req.json()
1098
+ const body = await c.req.json().catch(() => null)
1099
+ if (body && typeof body === 'object' && 'remote' in body) {
1100
+ if (getAppConfig().environment !== 'cloud')
1101
+ return c.text('Shared workspaces require Cloud mode', 403)
1102
+ if (Object.keys(body).some(key => key !== 'remote' && key !== 'harness'))
1103
+ return c.text('Remote registration expects only remote and harness', 400)
1104
+ let remote
1105
+ try {
1106
+ remote = parseRemoteWorkspaceTarget(body.remote)
1107
+ } catch (error) {
1108
+ return c.text(error instanceof Error ? error.message : 'Invalid remote workspace', 400)
1109
+ }
1110
+ // The visitor's own agent. Omitted, the reference falls back to the same
1111
+ // default as any other workspace without a stored harness.
1112
+ const requested: unknown = body.harness
1113
+ if (requested !== undefined) {
1114
+ if (requested !== 'claude-code' && requested !== 'codex')
1115
+ return c.text('Unknown workspace type', 400)
1116
+ const availability = await harnessTypeAvailability(requested)
1117
+ if (availability.status !== 'available') return c.text(availability.reason, 400)
1118
+ }
1119
+ try {
1120
+ return c.json(await openSharedWorkspace(remote, requested), 201)
1121
+ } catch (error) {
1122
+ return c.text(error instanceof Error ? error.message : 'Could not open shared workspace', 503)
1123
+ }
1124
+ }
1021
1125
  if (!body?.path) return c.text('Missing path', 400)
1022
- const requestedType: unknown = body?.type ?? 'claude-code'
1023
- if (!isHarnessType(requestedType)) return c.text('Unknown workspace type', 400)
1024
- const type: WorkspaceType = requestedType
1025
- const availability = await workspaceTypeAvailability(type)
1126
+ const requestedHarness: unknown = body?.harness ?? 'claude-code'
1127
+ if (!isHarnessType(requestedHarness)) return c.text('Unknown workspace type', 400)
1128
+ const harness: HarnessType = requestedHarness
1129
+ const availability = await harnessTypeAvailability(harness)
1026
1130
  if (availability.status !== 'available') return c.text(availability.reason, 400)
1027
1131
  const path = resolve(String(body.path))
1028
1132
  let metadata: WorkspaceImportMetadata
1029
1133
  try {
1030
- metadata = await resolveWorkspaceImportMetadata(path, type)
1134
+ metadata = await resolveWorkspaceImportMetadata(path, harness)
1031
1135
  } catch (err) {
1032
1136
  const message = err instanceof Error ? err.message : String(err)
1033
1137
  return c.text(message, 400)
@@ -1036,16 +1140,16 @@ workspaces.post('/', async c => {
1036
1140
  // skills dir) and the `.moi/` scaffold, exactly like `moi init` — a workspace
1037
1141
  // added from the UI must be indistinguishable from one added via the CLI.
1038
1142
  try {
1039
- await provisionWorkspace(path, type)
1143
+ await provisionWorkspace(path, harness)
1040
1144
  } catch (err) {
1041
1145
  const message = err instanceof Error ? err.message : String(err)
1042
1146
  return c.text(`Could not initialize workspace: ${message}`, 500)
1043
1147
  }
1044
1148
  const entry = await registerWorkspace(path, {
1045
- type,
1149
+ harness,
1046
1150
  ...metadata
1047
1151
  })
1048
- return c.json(entry, 201)
1152
+ return c.json((await mergeWorkspaceList([entry]))[0], 201)
1049
1153
  })
1050
1154
 
1051
1155
  workspaces.get('/discover', async c => c.json(await discoverWorkspaces()))
@@ -1056,9 +1160,11 @@ workspaces.get('/previews', async c => {
1056
1160
  const entries = await listWorkspaces()
1057
1161
  const previews = await Promise.all(
1058
1162
  entries.map(async ws => {
1163
+ // A remote reference has no local content to preview.
1164
+ if (ws.remote) return [ws.id, { thumbnails: [] }] as const
1059
1165
  const views = await listCompiledViews(ws.path).catch(() => [])
1060
1166
  const preview = await getWorkspacePreview(ws.path, {
1061
- getProviderPreview: includeFirstUserMessage =>
1167
+ getHarnessPreview: includeFirstUserMessage =>
1062
1168
  harnessFor(ws).workspacePreview(ws, includeFirstUserMessage),
1063
1169
  viewIds: views.map(view => view.id),
1064
1170
  // Capture time in base36 keeps the versioned segment short and URL-safe.
@@ -1073,10 +1179,10 @@ workspaces.get('/previews', async c => {
1073
1179
 
1074
1180
  // Backends the create dialog can provision from scratch. OpenClaw workspaces
1075
1181
  // belong to their agents and arrive via discovery.
1076
- const CREATABLE_TYPES = new Set<WorkspaceType>(['claude-code', 'codex'])
1182
+ const CREATABLE_HARNESSES = new Set<HarnessType>(['claude-code', 'codex'])
1077
1183
 
1078
- async function workspaceTypeAvailability(type: WorkspaceType): Promise<HarnessAvailability> {
1079
- return (await harnessFor(type).availability?.()) ?? { status: 'available' }
1184
+ async function harnessTypeAvailability(harness: HarnessType): Promise<HarnessAvailability> {
1185
+ return (await harnessFor(harness).availability?.()) ?? { status: 'available' }
1080
1186
  }
1081
1187
 
1082
1188
  // Create a brand-new workspace: a fresh folder under createdWorkspacesRoot(),
@@ -1084,15 +1190,15 @@ async function workspaceTypeAvailability(type: WorkspaceType): Promise<HarnessAv
1084
1190
  workspaces.post('/create', async c => {
1085
1191
  if (getAppConfig().demo) return c.text(DEMO_CREATE_BLOCKED, 403)
1086
1192
  const body = await c.req.json()
1087
- const requestedType: unknown = body?.type ?? 'claude-code'
1088
- if (!isHarnessType(requestedType)) {
1193
+ const requestedHarness: unknown = body?.harness ?? 'claude-code'
1194
+ if (!isHarnessType(requestedHarness)) {
1089
1195
  return c.text('Unknown workspace type', 400)
1090
1196
  }
1091
- const type: WorkspaceType = requestedType
1092
- if (!CREATABLE_TYPES.has(type)) {
1197
+ const harness: HarnessType = requestedHarness
1198
+ if (!CREATABLE_HARNESSES.has(harness)) {
1093
1199
  return c.text('Workspaces of this type arrive through discovery, not creation', 400)
1094
1200
  }
1095
- const availability = await workspaceTypeAvailability(type)
1201
+ const availability = await harnessTypeAvailability(harness)
1096
1202
  if (availability.status !== 'available') return c.text(availability.reason, 400)
1097
1203
  const name =
1098
1204
  body?.name === undefined
@@ -1104,13 +1210,13 @@ workspaces.post('/create', async c => {
1104
1210
  if (invalid) return c.text(invalid, 400)
1105
1211
  const path = await createWorkspaceDirectory(name, createdWorkspacesRoot())
1106
1212
  try {
1107
- await provisionWorkspace(path, type)
1213
+ await provisionWorkspace(path, harness)
1108
1214
  } catch (err) {
1109
1215
  const message = err instanceof Error ? err.message : String(err)
1110
1216
  return c.text(`Could not create workspace: ${message}`, 500)
1111
1217
  }
1112
1218
  await setWorkspaceConfig(path, { name })
1113
- const entry = await registerWorkspace(path, { id: basename(path), type, name })
1219
+ const entry = await registerWorkspace(path, { id: basename(path), harness, name })
1114
1220
  // Nudge every connected client (the sidebar list) to refetch.
1115
1221
  publishEvent({ type: 'workspaces-list:updated' })
1116
1222
  return c.json(entry, 201)