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
@@ -1,5 +1,6 @@
1
1
  import type { WorkspaceApiTarget } from '../workspaces/api'
2
2
  import { requestWorkspace } from '../workspaces/api'
3
+ import { cloudRoutes } from '../remote/routes'
3
4
  import { readdir } from 'node:fs/promises'
4
5
  import { join } from 'path'
5
6
 
@@ -294,7 +295,7 @@ export async function readScratchpadShapes(
294
295
  async function readSnapshot(workspace: string | WorkspaceApiTarget): Promise<ScratchpadSnapshot> {
295
296
  return typeof workspace === 'string'
296
297
  ? loadScratchpadDoc(workspace)
297
- : (await requestWorkspace(workspace, '/scratchpad')).json()
298
+ : (await requestWorkspace(cloudRoutes.scratchpad.path(workspace.remote))).json()
298
299
  }
299
300
 
300
301
  async function readAsset(
@@ -303,7 +304,7 @@ async function readAsset(
303
304
  ): Promise<Blob | undefined> {
304
305
  if (typeof workspace !== 'string')
305
306
  return (
306
- await requestWorkspace(workspace, `/scratchpad/assets/${encodeURIComponent(fileName)}`)
307
+ await requestWorkspace(cloudRoutes.scratchpadAsset.path(workspace.remote, fileName))
307
308
  ).blob()
308
309
  const asset = scratchpadAssetFile(workspace, fileName)
309
310
  if (!asset || !(await asset.file.exists())) return undefined
@@ -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,8 +1,9 @@
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
+ import { cloudRoutes } from '../remote/routes'
6
7
  import { archiveViewSessions } from './archive'
7
8
 
8
9
  export class PendingViewError extends Error {
@@ -103,10 +104,14 @@ export async function updatePendingView(
103
104
  })
104
105
  }
105
106
 
106
- export async function completeViewBuild(ws: WorkspaceRef, id: string) {
107
- await updateWorkspaceState(ws, state => {
108
- delete state.pendingViews[id]
109
- })
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
+ )
110
115
  }
111
116
 
112
117
  // A remote view compiles on its owner, which cannot reach this Moi's state. The
@@ -114,14 +119,16 @@ export async function completeViewBuild(ws: WorkspaceRef, id: string) {
114
119
  export async function completeRemoteViewBuilds(ws: WorkspaceEntry, request = requestWorkspace) {
115
120
  if (!ws.remote) return
116
121
  if (!Object.keys((await readWorkspaceState(ws)).pendingViews).length) return
117
- const response = await request({ remote: ws.remote }, '/views', { method: 'GET' })
122
+ const response = await request(cloudRoutes.compiledViews.path(ws.remote), { method: 'GET' })
118
123
  if (!response.ok) throw new Error(`Could not list the owner's views (${response.status})`)
119
- const { views } = (await response.json()) as { views: { id: string }[] }
120
- const compiled = new Set(views.map(view => view.id))
121
- await updateWorkspaceState(ws, state => {
122
- for (const id of Object.keys(state.pendingViews))
123
- if (compiled.has(id)) delete state.pendingViews[id]
124
- })
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
+ )
125
132
  }
126
133
 
127
134
  // Follow a temporary id's rename in every build that runs in it.
@@ -0,0 +1,102 @@
1
+ import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition'
2
+ import { IDENTITY_ICON_IDS } from '@/lib/identity-icons'
3
+ import { viewBuildDirectives } from '@/lib/view-build-directives'
4
+ import { viewIdFromTab } from '@/lib/workspace-tabs'
5
+ import type { WorkspaceEntry } from '@/lib/types'
6
+ import { getCollabReferencePath } from '../collab/config'
7
+ import { harnessFor } from '../harness/registry'
8
+ import type { SendMessageInput } from '../harness/types'
9
+ import { getPinnedSession, saveSelectedSession, resolveRenamedSession } from './selected'
10
+ import { getSessionEntry, updateSessionEntry } from './store'
11
+ import {
12
+ getPendingView,
13
+ listPendingViews,
14
+ patchPendingView,
15
+ PendingViewError
16
+ } from './pending-views'
17
+
18
+ // Both ordinary chat and initial build requests use this boundary.
19
+ export async function sendWorkspaceMessage(
20
+ ws: WorkspaceEntry,
21
+ input: SendMessageInput & { viewBuildId?: string }
22
+ ) {
23
+ const release = reserveWorkspaceOperation(ws.id)
24
+ try {
25
+ const { getWorkspace } = await import('../workspaces/registry')
26
+ const current = await getWorkspace(ws.id)
27
+ if (current && (current.harness ?? 'claude-code') !== (ws.harness ?? 'claude-code'))
28
+ throw new HarnessTransitionError('Agent changed. Start a new chat')
29
+ const { prepareWorkspaceHarness } = await import('../workspaces/change-harness')
30
+ await prepareWorkspaceHarness(ws)
31
+ const { viewBuildId, ...message } = input
32
+ const sessionId = resolveRenamedSession(ws.id, input.sessionId)
33
+ const record = await getSessionEntry(ws, sessionId)
34
+ const tabId = input.context?.activeTab?.id ?? record.tabId ?? 'overview'
35
+ const targetViewId = viewBuildId ?? (input.isNew ? viewIdFromTab(tabId) : undefined)
36
+ const ownedViews = targetViewId
37
+ ? []
38
+ : (await listPendingViews(ws)).filter(view => view.buildSessionId === sessionId)
39
+ const pending = targetViewId
40
+ ? await getPendingView(ws, targetViewId)
41
+ : (ownedViews.find(view => view.id === viewIdFromTab(tabId)) ?? ownedViews[0])
42
+ const isBuildRequest = pending && (viewBuildId === pending.id || input.isNew)
43
+ if (
44
+ isBuildRequest &&
45
+ pending.buildSessionId &&
46
+ pending.buildSessionId !== sessionId &&
47
+ (pending.status === 'starting' ||
48
+ harnessFor(ws)
49
+ .activeSessions()
50
+ .some(
51
+ session => session.workspaceId === ws.id && session.sessionId === pending.buildSessionId
52
+ ))
53
+ )
54
+ throw new PendingViewError('This view is already being built in another chat', 409)
55
+ if (input.isNew && record.tabId !== tabId) {
56
+ record.tabId = tabId === 'overview' ? undefined : tabId
57
+ await updateSessionEntry(ws, sessionId, { tabId: record.tabId })
58
+ await saveSelectedSession(ws, sessionId, tabId, null)
59
+ }
60
+ if (isBuildRequest)
61
+ await patchPendingView(ws, pending.id, {
62
+ buildSessionId: sessionId
63
+ })
64
+ const collabReference = await getCollabReferencePath(ws.path, ws.harness)
65
+ const pinnedSessionId = await getPinnedSession(ws)
66
+ await harnessFor(ws).sendMessage({
67
+ ...message,
68
+ sessionId,
69
+ context: {
70
+ ...input.context,
71
+ // Resolve here for both browser messages and programmatic view builds;
72
+ // the agent must not infer file location from its local working directory.
73
+ workspaceMode: ws.remote ? 'remote' : 'local',
74
+ session: {
75
+ id: sessionId,
76
+ tabId: record.tabId,
77
+ pinned: pinnedSessionId === sessionId
78
+ },
79
+ ...(collabReference ? { collabReference } : {}),
80
+ directives: [
81
+ ...(input.context?.directives ?? []),
82
+ ...(isBuildRequest ? viewBuildDirectives(pending.id, IDENTITY_ICON_IDS) : []),
83
+ ...(isBuildRequest && record.fork
84
+ ? [
85
+ 'Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks.'
86
+ ]
87
+ : []),
88
+ ...(pending && input.isNew && pending.requirements !== input.content
89
+ ? [`Original view requirements:\n${pending.requirements}`]
90
+ : []),
91
+ ...(pending && input.attachments?.length
92
+ ? ['Use the attachments as reference material for the intended view.']
93
+ : [])
94
+ ]
95
+ }
96
+ })
97
+ if (pending && pending.status !== 'starting')
98
+ await patchPendingView(ws, pending.id, { status: 'submitted', error: undefined })
99
+ } finally {
100
+ release()
101
+ }
102
+ }
@@ -1,27 +1,19 @@
1
- import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition'
1
+ import { sendWorkspaceMessage } from './send-message'
2
2
  import { IDENTITY_ICON_IDS } from '@/lib/identity-icons'
3
3
  import { viewBuildDirectives } from '@/lib/view-build-directives'
4
- import { viewIdFromTab, viewTabId } from '@/lib/workspace-tabs'
4
+ import { viewTabId } from '@/lib/workspace-tabs'
5
5
  import type { PendingView, WorkspaceEntry, WorkspaceTabId } from '@/lib/types'
6
- import { getCollabReferencePath } from '../collab/config'
7
6
  import { harnessFor } from '../harness/registry'
8
7
  import type { SendMessageInput } from '../harness/types'
9
8
  import { ForkUnsupportedError, inheritedHistoryBoundary } from '../harness/fork'
10
9
  import { updateWorkspaceState } from '../workspace-state'
11
- import {
12
- getPinnedSession,
13
- saveSelectedSession,
14
- resolveRenamedSession,
15
- selectSessionForTab
16
- } from './selected'
17
- import { getSessionEntry, setSessionTab, updateSessionEntry } from './store'
10
+ import { saveSelectedSession, resolveRenamedSession, selectSessionForTab } from './selected'
11
+ import { setSessionTab, updateSessionEntry } from './store'
18
12
  import { getSessionConfig, saveSessionConfig } from './config'
19
13
  import {
20
14
  createPendingView,
21
- getPendingView,
22
15
  listPendingViews,
23
16
  patchPendingView,
24
- PendingViewError,
25
17
  startViewBuild
26
18
  } from './pending-views'
27
19
 
@@ -40,88 +32,6 @@ type BuildSendOptions = Pick<
40
32
  >
41
33
  export type SubmitViewInput = BuildSendOptions & { requirements: string; sessionId?: string }
42
34
 
43
- // Both ordinary chat and initial build requests use this boundary.
44
- export async function sendWorkspaceMessage(
45
- ws: WorkspaceEntry,
46
- input: SendMessageInput & { viewBuildId?: string }
47
- ) {
48
- const release = reserveWorkspaceOperation(ws.id)
49
- try {
50
- const { getWorkspace } = await import('../workspaces/registry')
51
- const current = await getWorkspace(ws.id)
52
- if (current && (current.harness ?? 'claude-code') !== (ws.harness ?? 'claude-code'))
53
- throw new HarnessTransitionError('Agent changed. Start a new chat')
54
- const { prepareWorkspaceHarness } = await import('../workspaces/change-harness')
55
- await prepareWorkspaceHarness(ws)
56
- const { viewBuildId, ...message } = input
57
- const sessionId = resolveRenamedSession(ws.id, input.sessionId)
58
- const record = await getSessionEntry(ws, sessionId)
59
- const tabId = input.context?.activeTab?.id ?? record.tabId ?? 'overview'
60
- const targetViewId = viewBuildId ?? (input.isNew ? viewIdFromTab(tabId) : undefined)
61
- const ownedViews = targetViewId
62
- ? []
63
- : (await listPendingViews(ws)).filter(view => view.buildSessionId === sessionId)
64
- const pending = targetViewId
65
- ? await getPendingView(ws, targetViewId)
66
- : (ownedViews.find(view => view.id === viewIdFromTab(tabId)) ?? ownedViews[0])
67
- const isBuildRequest = pending && (viewBuildId === pending.id || input.isNew)
68
- if (
69
- isBuildRequest &&
70
- pending.buildSessionId &&
71
- pending.buildSessionId !== sessionId &&
72
- (pending.status === 'starting' ||
73
- harnessFor(ws)
74
- .activeSessions()
75
- .some(
76
- session => session.workspaceId === ws.id && session.sessionId === pending.buildSessionId
77
- ))
78
- )
79
- throw new PendingViewError('This view is already being built in another chat', 409)
80
- if (input.isNew && record.tabId !== tabId) {
81
- record.tabId = tabId === 'overview' ? undefined : tabId
82
- await attachSession(ws, tabId, sessionId, null)
83
- }
84
- if (isBuildRequest)
85
- await patchPendingView(ws, pending.id, {
86
- buildSessionId: sessionId
87
- })
88
- const collabReference = await getCollabReferencePath(ws.path, ws.harness)
89
- const pinnedSessionId = await getPinnedSession(ws)
90
- await harnessFor(ws).sendMessage({
91
- ...message,
92
- sessionId,
93
- context: {
94
- ...input.context,
95
- session: {
96
- id: sessionId,
97
- tabId: record.tabId,
98
- pinned: pinnedSessionId === sessionId
99
- },
100
- ...(collabReference ? { collabReference } : {}),
101
- directives: [
102
- ...(input.context?.directives ?? []),
103
- ...(isBuildRequest ? viewBuildDirectives(pending.id, IDENTITY_ICON_IDS) : []),
104
- ...(isBuildRequest && record.fork
105
- ? [
106
- 'Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks.'
107
- ]
108
- : []),
109
- ...(pending && input.isNew && pending.requirements !== input.content
110
- ? [`Original view requirements:\n${pending.requirements}`]
111
- : []),
112
- ...(pending && input.attachments?.length
113
- ? ['Use the attachments as reference material for the intended view.']
114
- : [])
115
- ]
116
- }
117
- })
118
- if (pending && pending.status !== 'starting')
119
- await patchPendingView(ws, pending.id, { status: 'submitted', error: undefined })
120
- } finally {
121
- release()
122
- }
123
- }
124
-
125
35
  async function attachSession(
126
36
  ws: WorkspaceEntry,
127
37
  tabId: WorkspaceTabId,
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'
@@ -25,7 +25,8 @@ import { navigationRelay } from './navigation-relay'
25
25
  import { resolveScratchOp } from './scratchpad/relay'
26
26
  import { allHarnesses, harnessFor } from './harness/registry'
27
27
  import { getWorkspace, listWorkspaces } from './workspaces/registry'
28
- import { failInterruptedViewStarts, sendWorkspaceMessage } from './sessions/view-sessions'
28
+ import { failInterruptedViewStarts } from './sessions/view-sessions'
29
+ import { sendWorkspaceMessage } from './sessions/send-message'
29
30
  import { prepareWorkspaceStates } from './workspace-state'
30
31
  import {
31
32
  addClient,
@@ -41,11 +42,12 @@ import { renderStatus } from './status'
41
42
  import { serveVendorEmojibase, serveVendorReact } from './vendor'
42
43
 
43
44
  type WsData = {
44
- channel: 'chat' | 'events' | 'collab'
45
+ channel: 'chat' | 'events' | 'workspace'
45
46
  workspaceId: string
46
47
  workspacePath?: string
47
48
  // The collab profile a proxy (Cloudflare Access) verified for the upgrade.
48
49
  verifiedProfile?: UserProfile
50
+ presence?: boolean
49
51
  }
50
52
 
51
53
  function isClientMessage(value: unknown): value is ClientMessage {
@@ -80,7 +82,6 @@ function isClientMessage(value: unknown): value is ClientMessage {
80
82
  (v.attachments === undefined || isMessageAttachments(v.attachments))
81
83
  )
82
84
  if (v.type === 'stop') return typeof v.workspaceId === 'string' && typeof v.sessionId === 'string'
83
- if (v.type === 'scratchpad:op-result') return typeof v.opId === 'string'
84
85
  return false
85
86
  }
86
87
 
@@ -93,7 +94,10 @@ const shell = prebuilt ? distShell : index
93
94
  // connect and re-broadcast periodically (below) so a spinner whose terminal
94
95
  // status frame was lost self-heals without a reconnect.
95
96
  function statusSnapshot(): StatusSnapshotMessage {
96
- 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
+ }
97
101
  }
98
102
 
99
103
  type Upgradable = { upgrade(req: Request, opts: { data: WsData }): boolean }
@@ -104,7 +108,7 @@ function upgrade(server: Upgradable, req: Request, data: WsData) {
104
108
  : new Response('Upgrade failed', { status: 500 })
105
109
  }
106
110
 
107
- // 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
108
112
  // WebSocket channels (which need Bun's native `server.upgrade` + pub/sub). Every
109
113
  // HTTP API route is delegated to the Hono app (`./api`) via `fetch`.
110
114
  const registeredWorkspaces = await listWorkspaces()
@@ -167,29 +171,25 @@ export const app = Bun.serve<WsData>({
167
171
 
168
172
  // Chat websocket — app-wide (one per client, not per workspace). Each chat
169
173
  // frame carries its own workspaceId.
170
- '/ws': (req: Request, server: Bun.Server<WsData>) =>
174
+ '/api/harness/events': (req: Request, server: Bun.Server<WsData>) =>
171
175
  upgrade(server, req, { channel: 'chat', workspaceId: '' }),
172
176
 
173
- // Live widget-event stream (build/refresh pushes). A static path, so Bun
174
- // routes it ahead of the Hono-served `/api/workspaces/:id`; the upgrade
175
- // happens in-handler via the route's `server` argument.
176
- '/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>) =>
177
179
  upgrade(server, req, { channel: 'events', workspaceId: '' }),
178
180
 
179
- '/api/workspaces/:id/collab': async (req: Request, server: Bun.Server<WsData>) => {
181
+ '/api/workspaces/:id/events': async (req: Request, server: Bun.Server<WsData>) => {
180
182
  const workspaceId = decodeURIComponent(new URL(req.url).pathname.split('/')[3] ?? '')
181
183
  const workspace = await getWorkspace(workspaceId)
182
184
  if (!workspace) return new Response('Workspace not found', { status: 404 })
183
- if (getAppConfig().environment !== 'cloud') {
184
- return new Response('Collab is not enabled for this workspace', { status: 403 })
185
- }
185
+ if (workspace.remote) return new Response('Use the owner workspace address', { status: 404 })
186
186
  // Behind Cloudflare Access, presence is joined only as the verified viewer.
187
187
  const { provider, profile } = await proxyUserState(req)
188
188
  if (provider && !profile) {
189
189
  return new Response('Sign in through Cloudflare Access to join', { status: 401 })
190
190
  }
191
191
  return upgrade(server, req, {
192
- channel: 'collab',
192
+ channel: 'workspace',
193
193
  workspaceId,
194
194
  workspacePath: workspace.path,
195
195
  ...(profile ? { verifiedProfile: profile } : {})
@@ -210,11 +210,10 @@ export const app = Bun.serve<WsData>({
210
210
  },
211
211
  websocket: {
212
212
  open(ws) {
213
- if (ws.data.channel === 'collab') {
214
- if (ws.data.workspacePath)
215
- collabManager.open(ws, ws.data.workspacePath, ws.data.verifiedProfile)
216
- else ws.close(1008, 'Missing workspace')
213
+ if (ws.data.channel === 'workspace') {
214
+ ws.subscribe(workspaceEventsTopic(ws.data.workspaceId))
217
215
  } else if (ws.data.channel === 'chat') {
216
+ ws.subscribe(HARNESS_EVENTS_TOPIC)
218
217
  addClient(ws)
219
218
  // Authoritative snapshot of every non-idle session across all
220
219
  // harnesses so the client can light/clear spinners correctly even for
@@ -225,13 +224,26 @@ export const app = Bun.serve<WsData>({
225
224
  }
226
225
  },
227
226
  async message(ws, message) {
228
- if (ws.data.channel === 'collab') {
229
- 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
+ }
230
237
  return
231
238
  }
232
239
  if (ws.data.channel === 'events') {
233
240
  try {
234
- 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
+ }
235
247
  } catch {}
236
248
  return
237
249
  }
@@ -273,17 +285,16 @@ export const app = Bun.serve<WsData>({
273
285
  .interrupt(data.workspaceId, data.sessionId)
274
286
  .catch(() => {})
275
287
  }
276
- // A tab's reply to a relayed Scratchpad op — settle the pending CLI
277
- // request (first reply wins; later/duplicate replies are ignored).
278
- if (data.type === 'scratchpad:op-result') {
279
- resolveScratchOp(data.opId, data.result, data.error)
280
- }
281
288
  } catch {}
282
289
  },
283
290
  close(ws) {
284
- if (ws.data.channel === 'collab') collabManager.close(ws)
285
- else if (ws.data.channel === 'chat') removeClient(ws)
286
- 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 {
287
298
  navigationRelay.remove(ws)
288
299
  ws.unsubscribe(EVENTS_TOPIC)
289
300
  }
@@ -4,6 +4,7 @@ import { dirname } from 'node:path'
4
4
 
5
5
  import type { PendingView, SessionFork, WorkspaceSessionState } from '@/lib/types'
6
6
  import { isWorkspaceTabId } from '@/lib/workspace-tabs'
7
+ import { normalizeOpenTabs } from '@/lib/workspace-layout'
7
8
  import { LockTimeoutError, type Lease } from './lock'
8
9
  import { WORKSPACE_STATE_VERSION, type StoredWorkspaceState } from './types'
9
10
 
@@ -95,6 +96,7 @@ export function normalizeWorkspaceState(
95
96
  workspacePath: string
96
97
  ): StoredWorkspaceState {
97
98
  const state = emptyWorkspaceState(optionalString(value.workspacePath) ?? workspacePath)
99
+ if (Array.isArray(value.openTabs)) state.openTabs = normalizeOpenTabs(value.openTabs)
98
100
  if (typeof value.revision === 'number' && Number.isSafeInteger(value.revision))
99
101
  state.revision = value.revision
100
102
  if (isRecord(value.chatDefaults))
@@ -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,16 +1,12 @@
1
1
  import type { RemoteWorkspaceTarget } from '@/lib/workspace-config'
2
- import { workspaceRequest } from '../remote/client'
2
+ import { remoteRequest } from '../remote/client'
3
3
 
4
4
  export type WorkspaceApiTarget = { remote: RemoteWorkspaceTarget }
5
5
 
6
6
  // CLI requests for a linked folder's shared content go to the owner's workspace API.
7
7
  // Local workspaces never come through here; their handlers read the folder directly.
8
- export async function requestWorkspace(
9
- workspace: WorkspaceApiTarget,
10
- path: string,
11
- init?: RequestInit
12
- ): Promise<Response> {
13
- const { remote } = workspace
8
+ // `path` comes from `cloudRoutes` (server/remote/routes.ts).
9
+ export async function requestWorkspace(path: string, init?: RequestInit): Promise<Response> {
14
10
  // Serialize multipart bodies once so the signature and content type match the bytes sent.
15
11
  const payload = new Request('http://workspace.local', {
16
12
  method: init?.method ?? 'POST',
@@ -19,7 +15,7 @@ export async function requestWorkspace(
19
15
  })
20
16
  // Bun materializes multipart headers lazily; read the boundary before consuming the body.
21
17
  const contentType = payload.headers.get('content-type') ?? undefined
22
- return workspaceRequest(remote.user_id, remote.workspace_id, path, {
18
+ return remoteRequest(path, {
23
19
  method: init?.method,
24
20
  body: init?.body == null ? undefined : new Uint8Array(await payload.arrayBuffer()),
25
21
  signal: init?.signal ?? undefined,
@@ -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
  }