moi-computer 0.13.1-next.3 → 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 (82) 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/collab/presence/client.ts +63 -83
  13. package/client/features/collab/presence/provider.tsx +8 -2
  14. package/client/features/dev/chat-states-page.tsx +1 -1
  15. package/client/features/dev/harness-debug-page.tsx +2 -2
  16. package/client/features/scratchpad/scratchpad.tsx +29 -20
  17. package/client/features/views/api.ts +5 -6
  18. package/client/features/workspace/api.ts +6 -11
  19. package/client/features/workspace/harness-transition.ts +3 -5
  20. package/client/features/workspace/remote.ts +9 -0
  21. package/client/features/workspace/settings/use-env-vars.ts +4 -4
  22. package/client/features/workspace/use-workspace-navigation.ts +1 -1
  23. package/client/features/workspace/use-workspace-socket.ts +51 -0
  24. package/client/features/workspace/workspace-content.tsx +3 -7
  25. package/client/features/workspace/workspace-layout-context.tsx +6 -13
  26. package/client/features/workspace/workspace-state.ts +17 -6
  27. package/client/runtime/app-context.ts +2 -2
  28. package/client/runtime/app-events.ts +75 -0
  29. package/client/runtime/reconnecting-socket.ts +115 -0
  30. package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
  31. package/dist/{chunk-f44cs6mw.js → chunk-0t8m1ehd.js} +2 -2
  32. package/dist/chunk-851bx8ss.js +72 -0
  33. package/dist/{chunk-xj1pjhng.js → chunk-c8g5x288.js} +1 -1
  34. package/dist/chunk-cty37f3v.js +1 -0
  35. package/dist/chunk-dy6f6h3e.js +5 -0
  36. package/dist/chunk-j6928pwm.js +1 -0
  37. package/dist/{chunk-r95acex1.js → chunk-k32585ne.js} +70 -70
  38. package/dist/chunk-qtkv7hp8.js +2 -0
  39. package/dist/chunk-rh58dc0y.js +2 -0
  40. package/dist/{chunk-a865c7x4.js → chunk-wjbejzek.js} +1 -1
  41. package/dist/index.html +1 -1
  42. package/lib/events.ts +61 -0
  43. package/lib/ids.ts +2 -8
  44. package/lib/types.ts +12 -15
  45. package/package.json +1 -1
  46. package/server/AGENTS.md +3 -3
  47. package/server/README.md +29 -15
  48. package/server/api/index.ts +54 -35
  49. package/server/applets/views.ts +15 -14
  50. package/server/applets/widgets.ts +4 -3
  51. package/server/cli/commands/refresh.ts +2 -5
  52. package/server/control.ts +24 -33
  53. package/server/events.ts +14 -13
  54. package/server/harness/README.md +7 -7
  55. package/server/harness/acp/session.ts +9 -5
  56. package/server/harness/auth.ts +7 -30
  57. package/server/harness/claude-code/session.ts +8 -4
  58. package/server/harness/codex/NOTES.md +1 -1
  59. package/server/harness/codex/session.ts +18 -10
  60. package/server/harness/hermes/NOTES.md +3 -3
  61. package/server/harness/openclaw/session.ts +9 -5
  62. package/server/onboarding/jobs.ts +7 -7
  63. package/server/operations/commands.ts +1 -1
  64. package/server/scratchpad/executor.ts +2 -2
  65. package/server/scratchpad/relay.ts +3 -3
  66. package/server/sessions/archive.ts +1 -1
  67. package/server/sessions/lifecycle.ts +1 -1
  68. package/server/sessions/pending-views.ts +17 -11
  69. package/server/web.ts +40 -30
  70. package/server/workspace-state/index.ts +15 -4
  71. package/server/workspaces/config.ts +14 -13
  72. package/server/workspaces/env-apply.ts +1 -1
  73. package/server/workspaces/layout.ts +40 -7
  74. package/server/workspaces/shared.ts +1 -1
  75. package/client/features/scratchpad/scratch-executor.ts +0 -20
  76. package/client/runtime/workspace-events.ts +0 -168
  77. package/dist/chunk-0h4zypgf.js +0 -1
  78. package/dist/chunk-1tksq43z.js +0 -72
  79. package/dist/chunk-6gxf0xr8.js +0 -5
  80. package/dist/chunk-h3qag4a6.js +0 -2
  81. package/dist/chunk-q2tpy0h7.js +0 -2
  82. package/dist/chunk-w5h9grdr.js +0 -1
@@ -222,7 +222,7 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
222
222
  else armIdleTimer(rec)
223
223
  if (existing?.processing === processing) return
224
224
  broadcast(rec.workspaceId, {
225
- type: 'status',
225
+ type: 'session:status',
226
226
  sessionId: rec.sessionId,
227
227
  activity: processing ? 'running' : 'idle'
228
228
  })
@@ -286,7 +286,11 @@ export function teardownOpenClawSession(rec: SessionRecord): void {
286
286
  // If it was mid-run, mirror setProcessing(rec, false, null)'s client-visible
287
287
  // effect so no spinner is left hanging.
288
288
  if (wasProcessing) {
289
- broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, activity: 'idle' })
289
+ broadcast(rec.workspaceId, {
290
+ type: 'session:status',
291
+ sessionId: rec.sessionId,
292
+ activity: 'idle'
293
+ })
290
294
  }
291
295
  }
292
296
 
@@ -607,7 +611,7 @@ export function claimPreviewSource(
607
611
 
608
612
  function broadcastPreview(rec: SessionRecord, messageId: string, blocks: PreviewBlock[]): void {
609
613
  broadcast(rec.workspaceId, {
610
- type: 'preview',
614
+ type: 'session:preview',
611
615
  sessionId: rec.sessionId,
612
616
  messageId,
613
617
  parentToolUseId: null,
@@ -906,7 +910,7 @@ function broadcastSessionsChanged(rec: SessionRecord): void {
906
910
  entry.trailing = setTimeout(
907
911
  () => {
908
912
  lastListRefresh.set(rec.workspaceId, { at: Date.now() })
909
- broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
913
+ broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
910
914
  },
911
915
  LIST_REFRESH_MIN_MS - (now - entry.at)
912
916
  )
@@ -915,7 +919,7 @@ function broadcastSessionsChanged(rec: SessionRecord): void {
915
919
  }
916
920
  if (entry?.trailing) clearTimeout(entry.trailing)
917
921
  lastListRefresh.set(rec.workspaceId, { at: now })
918
- broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
922
+ broadcast(rec.workspaceId, { type: 'sessions:changed', sessionId: rec.sessionId })
919
923
  }
920
924
 
921
925
  // Exported for tests (the live subscription is the only production caller).
@@ -8,7 +8,7 @@ import { createdWorkspacesRoot } from '../app-config'
8
8
  import { createWorkspaceDirectory, provisionWorkspace } from '../workspaces/init'
9
9
  import { getWorkspace, registerWorkspace } from '../workspaces/registry'
10
10
  import { setWorkspaceConfig } from '../workspaces/config'
11
- import { saveLayout } from '../workspaces/layout'
11
+ import { updateLayout } from '../workspaces/layout'
12
12
  import { resolveWorkspaceTheme } from '@/lib/themes'
13
13
  import { publishEvent } from '../events'
14
14
  import { harnessFor } from '../harness/registry'
@@ -197,14 +197,14 @@ export function createOnboardingJobs(overrides: Partial<typeof defaults> = {}) {
197
197
  const path = job.workspacePath
198
198
  await deps.provisionWorkspace(path, progress.harness)
199
199
  if (!job.workspaceId) {
200
- const layout = await deps.setWorkspaceConfig(path, {
200
+ await deps.setWorkspaceConfig(path, {
201
201
  name: idea.name,
202
202
  icon: { type: 'glyph', value: idea.icon, background: 'theme' }
203
203
  })
204
- await saveLayout(
205
- { ...layout, theme: resolveWorkspaceTheme({ ...layout.theme, ...idea.theme }) },
206
- path
207
- )
204
+ await updateLayout(path, layout => ({
205
+ ...layout,
206
+ theme: resolveWorkspaceTheme({ ...layout.theme, ...idea.theme })
207
+ }))
208
208
  }
209
209
  const ws = await deps.registerWorkspace(path, {
210
210
  id: job.workspaceId ?? basename(path),
@@ -217,7 +217,7 @@ export function createOnboardingJobs(overrides: Partial<typeof defaults> = {}) {
217
217
  // Reconciliation must compare against the exact message originally submitted.
218
218
  const brief = job.stage ? await Bun.file(briefPath).text() : composeBuildBrief(idea)
219
219
  await Bun.write(briefPath, brief)
220
- deps.publishEvent({ type: 'workspaces-list:updated' })
220
+ deps.publishEvent({ type: 'workspaces-list:changed' })
221
221
  const harness = deps.harnessFor(ws)
222
222
  if (job.stage === 'sending' || job.stage === 'accepted') {
223
223
  // The provider may have accepted before a response/save was lost. This
@@ -40,7 +40,7 @@ export function spawnWorkspaceCommand(root: string, command: string, args: strin
40
40
  stdout: 'pipe',
41
41
  stderr: 'pipe',
42
42
  detached: true,
43
- env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0', MOI_REMOTE_WORKSPACE: root }
43
+ env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' }
44
44
  }
45
45
  )
46
46
  }
@@ -36,7 +36,7 @@ import { SHAPE_DEFAULTS } from './shape-defaults'
36
36
 
37
37
  // Server-side Scratchpad writer. The browser is no longer required to draw: we run
38
38
  // the same ops against a *headless* tldraw store here, persist the snapshot, and
39
- // broadcast `scratchpad:updated` so any open tab reloads from disk. Only `view`
39
+ // broadcast `scratchpad:changed` so any open tab reloads from disk. Only `view`
40
40
  // (rendering pixels) still needs a live tab; `read` is served straight off disk.
41
41
  // See docs/moi-scratchpad.md.
42
42
  //
@@ -493,7 +493,7 @@ export function executeScratchOp(
493
493
  : applyOp(store, op)
494
494
  const next = store.getStoreSnapshot() as unknown as ScratchpadDoc
495
495
  await saveScratchpadDoc(next, workspacePath)
496
- publishEvent({ type: 'scratchpad:updated', workspaceId })
496
+ publishEvent({ type: 'scratchpad:changed', workspaceId })
497
497
  return result
498
498
  })
499
499
  }
@@ -1,10 +1,10 @@
1
1
  import type { ScratchOp, ScratchOpResult } from '@/lib/types'
2
2
 
3
- import { broadcastAll } from '../state'
3
+ import { publishEvent } from '../events'
4
4
 
5
5
  // Bridges `moi scratch` (control port) to a live tldraw editor in a browser tab.
6
6
  // The control server runs in the same process as the app server, so it calls
7
- // `relayScratchOp` directly: we broadcast the op over the app chat socket tagged
7
+ // `relayScratchOp` directly: we broadcast the op over the machine events socket tagged
8
8
  // with `workspaceId`, the tab showing that workspace's canvas runs it against
9
9
  // tldraw, and replies with a `scratchpad:op-result` that settles our promise.
10
10
 
@@ -28,7 +28,7 @@ export function relayScratchOp(workspaceId: string, op: ScratchOp): Promise<Scra
28
28
  reject(new Error('No live canvas — open the Scratchpad tab for this workspace.'))
29
29
  }, RELAY_TIMEOUT_MS)
30
30
  pendingOps.set(opId, { resolve, reject, timer })
31
- broadcastAll({ type: 'scratchpad:op', workspaceId, opId, op })
31
+ publishEvent({ type: 'scratchpad:op', workspaceId, opId, op })
32
32
  })
33
33
  }
34
34
 
@@ -11,7 +11,7 @@ export async function archiveWorkspaceSession(ws: WorkspaceEntry, sessionId: str
11
11
  await harness.interrupt(ws.id, sessionId)
12
12
  await harness.archiveSession(ws, sessionId)
13
13
  await clearSelectedSession(ws, sessionId)
14
- broadcast(ws.id, { type: 'session_archived', sessionId })
14
+ broadcast(ws.id, { type: 'session:archived', sessionId })
15
15
  }
16
16
 
17
17
  export async function archiveViewSessions(ws: WorkspaceEntry, viewId: string) {
@@ -15,5 +15,5 @@ export async function renameSessionReferences(ws: WorkspaceRef, from: string, to
15
15
  renameSessionSelection(state, from, to)
16
16
  renameBuildSession(state, from, to)
17
17
  })
18
- broadcast(ws.id, { type: 'session_renamed', from, to })
18
+ broadcast(ws.id, { type: 'session:renamed', from, to })
19
19
  }
@@ -1,6 +1,6 @@
1
1
  import { isIdentityIconId } from '@/lib/identity-icons'
2
2
  import { newViewId } from '@/lib/ids'
3
- import type { PendingView, WorkspaceEntry, WorkspaceState } from '@/lib/types'
3
+ import type { CompiledView, PendingView, WorkspaceEntry, WorkspaceState } from '@/lib/types'
4
4
  import { readWorkspaceState, updateWorkspaceState, type WorkspaceRef } from '../workspace-state'
5
5
  import { requestWorkspace } from '../workspaces/api'
6
6
  import { cloudRoutes } from '../remote/routes'
@@ -104,10 +104,14 @@ export async function updatePendingView(
104
104
  })
105
105
  }
106
106
 
107
- export async function completeViewBuild(ws: WorkspaceRef, id: string) {
108
- await updateWorkspaceState(ws, state => {
109
- delete state.pendingViews[id]
110
- })
107
+ export async function completeViewBuild(ws: WorkspaceRef, id: string, compiled?: CompiledView) {
108
+ await updateWorkspaceState(
109
+ ws,
110
+ state => {
111
+ delete state.pendingViews[id]
112
+ },
113
+ compiled && [compiled]
114
+ )
111
115
  }
112
116
 
113
117
  // A remote view compiles on its owner, which cannot reach this Moi's state. The
@@ -117,12 +121,14 @@ export async function completeRemoteViewBuilds(ws: WorkspaceEntry, request = req
117
121
  if (!Object.keys((await readWorkspaceState(ws)).pendingViews).length) return
118
122
  const response = await request(cloudRoutes.compiledViews.path(ws.remote), { method: 'GET' })
119
123
  if (!response.ok) throw new Error(`Could not list the owner's views (${response.status})`)
120
- const { views } = (await response.json()) as { views: { id: string }[] }
121
- const compiled = new Set(views.map(view => view.id))
122
- await updateWorkspaceState(ws, state => {
123
- for (const id of Object.keys(state.pendingViews))
124
- if (compiled.has(id)) delete state.pendingViews[id]
125
- })
124
+ const { views } = (await response.json()) as { views: CompiledView[] }
125
+ await updateWorkspaceState(
126
+ ws,
127
+ state => {
128
+ for (const view of views) delete state.pendingViews[view.id]
129
+ },
130
+ views
131
+ )
126
132
  }
127
133
 
128
134
  // Follow a temporary id's rename in every build that runs in it.
package/server/web.ts CHANGED
@@ -17,7 +17,7 @@ import { PORT } from './constants'
17
17
  import { control } from './control'
18
18
  import { proxyUserState } from './collab/cloudflare-access'
19
19
  import { collabManager } from './collab/manager'
20
- import { EVENTS_TOPIC, setEventServer } from './events'
20
+ import { EVENTS_TOPIC, HARNESS_EVENTS_TOPIC, workspaceEventsTopic, setEventServer } from './events'
21
21
  import { killBuildWorkers } from './applets/build-worker'
22
22
  import { killAllWorkers } from './applets/functions'
23
23
  import { startScratchpadSweeper } from './scratchpad/document'
@@ -42,11 +42,12 @@ import { renderStatus } from './status'
42
42
  import { serveVendorEmojibase, serveVendorReact } from './vendor'
43
43
 
44
44
  type WsData = {
45
- channel: 'chat' | 'events' | 'collab'
45
+ channel: 'chat' | 'events' | 'workspace'
46
46
  workspaceId: string
47
47
  workspacePath?: string
48
48
  // The collab profile a proxy (Cloudflare Access) verified for the upgrade.
49
49
  verifiedProfile?: UserProfile
50
+ presence?: boolean
50
51
  }
51
52
 
52
53
  function isClientMessage(value: unknown): value is ClientMessage {
@@ -81,7 +82,6 @@ function isClientMessage(value: unknown): value is ClientMessage {
81
82
  (v.attachments === undefined || isMessageAttachments(v.attachments))
82
83
  )
83
84
  if (v.type === 'stop') return typeof v.workspaceId === 'string' && typeof v.sessionId === 'string'
84
- if (v.type === 'scratchpad:op-result') return typeof v.opId === 'string'
85
85
  return false
86
86
  }
87
87
 
@@ -94,7 +94,10 @@ const shell = prebuilt ? distShell : index
94
94
  // connect and re-broadcast periodically (below) so a spinner whose terminal
95
95
  // status frame was lost self-heals without a reconnect.
96
96
  function statusSnapshot(): StatusSnapshotMessage {
97
- return { type: 'status_snapshot', sessions: allHarnesses().flatMap(h => h.activeSessions()) }
97
+ return {
98
+ type: 'sessions:status-snapshot',
99
+ sessions: allHarnesses().flatMap(h => h.activeSessions())
100
+ }
98
101
  }
99
102
 
100
103
  type Upgradable = { upgrade(req: Request, opts: { data: WsData }): boolean }
@@ -105,7 +108,7 @@ function upgrade(server: Upgradable, req: Request, data: WsData) {
105
108
  : new Response('Upgrade failed', { status: 500 })
106
109
  }
107
110
 
108
- // Bun owns the fullstack surface: the HTML shell + dev bundler/HMR, and the two
111
+ // Bun owns the fullstack surface: the HTML shell + dev bundler/HMR and
109
112
  // WebSocket channels (which need Bun's native `server.upgrade` + pub/sub). Every
110
113
  // HTTP API route is delegated to the Hono app (`./api`) via `fetch`.
111
114
  const registeredWorkspaces = await listWorkspaces()
@@ -168,29 +171,25 @@ export const app = Bun.serve<WsData>({
168
171
 
169
172
  // Chat websocket — app-wide (one per client, not per workspace). Each chat
170
173
  // frame carries its own workspaceId.
171
- '/ws': (req: Request, server: Bun.Server<WsData>) =>
174
+ '/api/harness/events': (req: Request, server: Bun.Server<WsData>) =>
172
175
  upgrade(server, req, { channel: 'chat', workspaceId: '' }),
173
176
 
174
- // Live widget-event stream (build/refresh pushes). A static path, so Bun
175
- // routes it ahead of the Hono-served `/api/workspaces/:id`; the upgrade
176
- // happens in-handler via the route's `server` argument.
177
- '/api/workspaces/ws': (req: Request, server: Bun.Server<WsData>) =>
177
+ // App settings, personal workspace state, and navigation stay on this machine.
178
+ '/api/events': (req: Request, server: Bun.Server<WsData>) =>
178
179
  upgrade(server, req, { channel: 'events', workspaceId: '' }),
179
180
 
180
- '/api/workspaces/:id/collab': async (req: Request, server: Bun.Server<WsData>) => {
181
+ '/api/workspaces/:id/events': async (req: Request, server: Bun.Server<WsData>) => {
181
182
  const workspaceId = decodeURIComponent(new URL(req.url).pathname.split('/')[3] ?? '')
182
183
  const workspace = await getWorkspace(workspaceId)
183
184
  if (!workspace) return new Response('Workspace not found', { status: 404 })
184
- if (getAppConfig().environment !== 'cloud') {
185
- return new Response('Collab is not enabled for this workspace', { status: 403 })
186
- }
185
+ if (workspace.remote) return new Response('Use the owner workspace address', { status: 404 })
187
186
  // Behind Cloudflare Access, presence is joined only as the verified viewer.
188
187
  const { provider, profile } = await proxyUserState(req)
189
188
  if (provider && !profile) {
190
189
  return new Response('Sign in through Cloudflare Access to join', { status: 401 })
191
190
  }
192
191
  return upgrade(server, req, {
193
- channel: 'collab',
192
+ channel: 'workspace',
194
193
  workspaceId,
195
194
  workspacePath: workspace.path,
196
195
  ...(profile ? { verifiedProfile: profile } : {})
@@ -211,11 +210,10 @@ export const app = Bun.serve<WsData>({
211
210
  },
212
211
  websocket: {
213
212
  open(ws) {
214
- if (ws.data.channel === 'collab') {
215
- if (ws.data.workspacePath)
216
- collabManager.open(ws, ws.data.workspacePath, ws.data.verifiedProfile)
217
- else ws.close(1008, 'Missing workspace')
213
+ if (ws.data.channel === 'workspace') {
214
+ ws.subscribe(workspaceEventsTopic(ws.data.workspaceId))
218
215
  } else if (ws.data.channel === 'chat') {
216
+ ws.subscribe(HARNESS_EVENTS_TOPIC)
219
217
  addClient(ws)
220
218
  // Authoritative snapshot of every non-idle session across all
221
219
  // harnesses so the client can light/clear spinners correctly even for
@@ -226,13 +224,26 @@ export const app = Bun.serve<WsData>({
226
224
  }
227
225
  },
228
226
  async message(ws, message) {
229
- if (ws.data.channel === 'collab') {
230
- collabManager.message(ws, message)
227
+ if (ws.data.channel === 'workspace') {
228
+ // Presence starts with the first presence message; until then the socket only pings.
229
+ if (!ws.data.presence && String(message) === '{"type":"ping"}') {
230
+ ws.send('{"type":"pong"}')
231
+ } else if (getAppConfig().environment === 'cloud' && ws.data.workspacePath) {
232
+ if (!ws.data.presence)
233
+ collabManager.open(ws, ws.data.workspacePath, ws.data.verifiedProfile)
234
+ ws.data.presence = true
235
+ collabManager.message(ws, message)
236
+ }
231
237
  return
232
238
  }
233
239
  if (ws.data.channel === 'events') {
234
240
  try {
235
- navigationRelay.receive(ws, JSON.parse(String(message)))
241
+ const data = JSON.parse(String(message))
242
+ if (data?.type === 'scratchpad:op-result' && typeof data.opId === 'string') {
243
+ resolveScratchOp(data.opId, data.result, data.error)
244
+ } else {
245
+ navigationRelay.receive(ws, data)
246
+ }
236
247
  } catch {}
237
248
  return
238
249
  }
@@ -274,17 +285,16 @@ export const app = Bun.serve<WsData>({
274
285
  .interrupt(data.workspaceId, data.sessionId)
275
286
  .catch(() => {})
276
287
  }
277
- // A tab's reply to a relayed Scratchpad op — settle the pending CLI
278
- // request (first reply wins; later/duplicate replies are ignored).
279
- if (data.type === 'scratchpad:op-result') {
280
- resolveScratchOp(data.opId, data.result, data.error)
281
- }
282
288
  } catch {}
283
289
  },
284
290
  close(ws) {
285
- if (ws.data.channel === 'collab') collabManager.close(ws)
286
- else if (ws.data.channel === 'chat') removeClient(ws)
287
- else {
291
+ if (ws.data.channel === 'workspace') {
292
+ collabManager.close(ws)
293
+ ws.unsubscribe(workspaceEventsTopic(ws.data.workspaceId))
294
+ } else if (ws.data.channel === 'chat') {
295
+ removeClient(ws)
296
+ ws.unsubscribe(HARNESS_EVENTS_TOPIC)
297
+ } else {
288
298
  navigationRelay.remove(ws)
289
299
  ws.unsubscribe(EVENTS_TOPIC)
290
300
  }
@@ -3,12 +3,12 @@
3
3
  // the only process that writes these files (the CLI goes through the control
4
4
  // port), so the cache never goes stale. Writes for one workspace run one at a
5
5
  // time, each as a synchronous change applied to a copy and saved atomically.
6
- // Every saved change is published to browsers as `state:changed`.
6
+ // Every saved change is published to browsers as `personal-state:changed`.
7
7
  import { existsSync } from 'node:fs'
8
8
  import { readdir, rm } from 'node:fs/promises'
9
9
  import { join } from 'node:path'
10
10
 
11
- import type { WorkspaceState } from '@/lib/types'
11
+ import type { CompiledView, WorkspaceState } from '@/lib/types'
12
12
  import { DATA_DIR } from '../data-dir'
13
13
  import { publishEvent } from '../events'
14
14
  import {
@@ -83,7 +83,8 @@ export async function getWorkspaceState(ws: WorkspaceRef): Promise<WorkspaceStat
83
83
  // a change that leaves the state as it was skips the write.
84
84
  export async function updateWorkspaceState<T>(
85
85
  ws: WorkspaceRef,
86
- change: (draft: StoredWorkspaceState) => T
86
+ change: (draft: StoredWorkspaceState) => T,
87
+ completedViews?: CompiledView[]
87
88
  ): Promise<T> {
88
89
  return withLock(ws.id, async lease => {
89
90
  const loaded = await load(ws)
@@ -98,8 +99,18 @@ export async function updateWorkspaceState<T>(
98
99
  if (!loaded.writable) throw new WorkspaceStateVersionError(statePath(ws.id))
99
100
  draft.revision++
100
101
  await writeStateFile(statePath(ws.id), draft, lease)
102
+ const previousPending = loaded.state.pendingViews
101
103
  loaded.state = draft
102
- publishEvent({ type: 'state:changed', workspaceId: ws.id, state: toWorkspaceState(draft) })
104
+ publishEvent({
105
+ type: 'personal-state:changed',
106
+ workspaceId: ws.id,
107
+ state: toWorkspaceState(draft),
108
+ ...(completedViews?.length && {
109
+ completedViews: completedViews.filter(
110
+ view => previousPending[view.id] && !draft.pendingViews[view.id]
111
+ )
112
+ })
113
+ })
103
114
  return result
104
115
  })
105
116
  }
@@ -1,6 +1,6 @@
1
1
  import type { WorkspaceIcon, WorkspaceLayout } from '@/lib/types'
2
2
 
3
- import { loadLayout, saveLayout } from './layout'
3
+ import { loadLayout, updateLayout } from './layout'
4
4
 
5
5
  // Workspace identity stored in the layout: a display-name override, an icon,
6
6
  // and its optional host-painted background.
@@ -26,16 +26,17 @@ export async function setWorkspaceConfig(
26
26
  workspacePath: string,
27
27
  patch: WorkspaceConfigPatch
28
28
  ): Promise<WorkspaceLayout> {
29
- const layout = await loadLayout(workspacePath)
30
- const next: WorkspaceLayout = { ...layout }
31
- if (patch.name !== undefined) {
32
- if (patch.name) next.name = patch.name
33
- else delete next.name
34
- }
35
- if (patch.icon !== undefined) {
36
- if (patch.icon) next.icon = patch.icon
37
- else delete next.icon
38
- }
39
- await saveLayout(next, workspacePath)
40
- return next
29
+ const { layout } = await updateLayout(workspacePath, current => {
30
+ const next = { ...current }
31
+ if (patch.name !== undefined) {
32
+ if (patch.name) next.name = patch.name
33
+ else delete next.name
34
+ }
35
+ if (patch.icon !== undefined) {
36
+ if (patch.icon) next.icon = patch.icon
37
+ else delete next.icon
38
+ }
39
+ return next
40
+ })
41
+ return layout
41
42
  }
@@ -16,5 +16,5 @@ export function applyEnvChanged(workspace: { id: string; path: string }): void {
16
16
  // Env can carry credentials (ANTHROPIC_API_KEY, provider config) — drop the
17
17
  // cached availability so the next agent snapshot re-probes.
18
18
  harnessStore.invalidate(workspace)
19
- publishEvent({ type: 'env:updated', workspaceId: workspace.id })
19
+ publishEvent({ type: 'env:changed', workspaceId: workspace.id })
20
20
  }
@@ -1,4 +1,4 @@
1
- import { mkdir, writeFile } from 'node:fs/promises'
1
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
2
2
  import {
3
3
  parseRemoteWorkspaceConfig,
4
4
  parseRemoteWorkspaceTarget,
@@ -7,7 +7,12 @@ import {
7
7
  } from '@/lib/workspace-config'
8
8
  import { join } from 'path'
9
9
 
10
- import type { AppletKind, WorkspaceLayout, WorkspacePreview } from '@/lib/types'
10
+ import type {
11
+ AppletKind,
12
+ WorkspaceLayout,
13
+ WorkspaceLayoutPatch,
14
+ WorkspacePreview
15
+ } from '@/lib/types'
11
16
  import { createDefaultWorkspaceLayout } from '@/lib/workspace-layout'
12
17
  import { isWorkspaceIcon } from '@/lib/workspace-icon'
13
18
 
@@ -49,17 +54,45 @@ export async function loadLayout(workspacePath: string): Promise<WorkspaceLayout
49
54
  return config
50
55
  }
51
56
 
57
+ const pendingWrites = new Map<string, Promise<unknown>>()
58
+
59
+ export async function updateLayout(
60
+ workspacePath: string,
61
+ update: (current: WorkspaceLayout) => WorkspaceLayout
62
+ ) {
63
+ const path = getLayoutPath(workspacePath)
64
+ const write = async () => {
65
+ const current = await loadWorkspaceFileConfig(workspacePath)
66
+ if (current.remote)
67
+ throw new Error('Cannot replace a remote workspace reference with a local layout')
68
+ const layout = update(current)
69
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`
70
+ try {
71
+ await Bun.write(temporary, JSON.stringify(layout, null, 2))
72
+ await rename(temporary, path)
73
+ } finally {
74
+ await rm(temporary, { force: true })
75
+ }
76
+ return { layout, changed: JSON.stringify(current) !== JSON.stringify(layout) }
77
+ }
78
+ const previous = pendingWrites.get(path) ?? Promise.resolve()
79
+ const run = previous.then(write, write)
80
+ pendingWrites.set(path, run)
81
+ try {
82
+ return await run
83
+ } finally {
84
+ if (pendingWrites.get(path) === run) pendingWrites.delete(path)
85
+ }
86
+ }
87
+
52
88
  export async function saveLayout(layout: WorkspaceLayout, workspacePath: string): Promise<void> {
53
- const existing = await loadWorkspaceFileConfig(workspacePath)
54
- if (existing.remote)
55
- throw new Error('Cannot replace a remote workspace reference with a local layout')
56
- await Bun.write(getLayoutPath(workspacePath), JSON.stringify(layout, null, 2))
89
+ await updateLayout(workspacePath, () => layout)
57
90
  }
58
91
 
59
92
  // The editor owns widgets and theme; identity changes use the config API.
60
93
  export function mergeLayoutForSave(
61
94
  existing: WorkspaceLayout,
62
- body: WorkspaceLayout
95
+ body: WorkspaceLayoutPatch
63
96
  ): WorkspaceLayout {
64
97
  return normalizeLayout({
65
98
  ...existing,
@@ -46,7 +46,7 @@ export async function openSharedWorkspace(remote: RemoteWorkspaceTarget, harness
46
46
  await rm(path, { recursive: true, force: true })
47
47
  throw error
48
48
  }
49
- publishEvent({ type: 'workspaces-list:updated' })
49
+ publishEvent({ type: 'workspaces-list:changed' })
50
50
  return entry
51
51
  })
52
52
  }
@@ -1,20 +0,0 @@
1
- import type { ScratchOp, ScratchOpResult } from '@/lib/types'
2
-
3
- // A live Scratchpad editor registers an executor here while it's mounted, keyed
4
- // by workspace id. The chat-socket frame handler (connection.ts) looks one up
5
- // when a `scratchpad:op` arrives and runs it against the tab's tldraw editor.
6
- // Only the tab actually showing a workspace's canvas has an entry, so ops from
7
- // `moi scratch` reach the right editor (and no-op everywhere else).
8
-
9
- type ScratchExecutor = (op: ScratchOp) => Promise<ScratchOpResult>
10
-
11
- const executors = new Map<string, ScratchExecutor>()
12
-
13
- export function setScratchExecutor(workspaceId: string, fn: ScratchExecutor | null) {
14
- if (fn) executors.set(workspaceId, fn)
15
- else executors.delete(workspaceId)
16
- }
17
-
18
- export function getScratchExecutor(workspaceId: string): ScratchExecutor | undefined {
19
- return executors.get(workspaceId)
20
- }