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
@@ -1,6 +1,6 @@
1
- import { getWorkspaceApiBase } from '@/client/features/workspace/remote'
1
+ import { isSharedWorkspaceEvent } from '@/lib/events'
2
+ import { createWorkspaceSocket } from '@/client/features/workspace/remote'
2
3
  import { getWorkspaceDirectory, subscribeWorkspaceDirectory } from '../members/store'
3
- import { wsUrl } from '@/client/lib/ws-url'
4
4
  import { COLLAB_PROTOCOL_VERSION } from '@/lib/collab/protocol'
5
5
  import type {
6
6
  CollabClientMessage,
@@ -58,25 +58,26 @@ export const NO_ENGINE: CollabEngineApi = {
58
58
  deletePresence: noop
59
59
  }
60
60
 
61
- // One presence connection per mounted workspace with an explicit profile.
61
+ // Presence for one mounted workspace with an explicit profile. It rides the
62
+ // workspace socket: holding the socket and joining is being present.
62
63
  export class CollabClient implements CollabEngineApi {
63
64
  readonly store = new CollabStore()
64
- private socket: WebSocket | null = null
65
+ private release: (() => void) | undefined
65
66
  private retry: ReturnType<typeof setTimeout> | undefined
66
- private heartbeat: ReturnType<typeof setInterval> | undefined
67
+ private unsubscribeSocket: (() => void) | undefined
67
68
  private unsubscribeMembers: (() => void) | undefined
68
69
  private unsubscribeCurrentUser: (() => void) | undefined
69
70
  private presenceTimer: ReturnType<typeof setTimeout> | undefined
70
71
  private queuedPresence = new Map<string, CollabClientMessage>()
71
72
  private stopped = true
72
73
  private attempts = 0
73
- private lastMessageAt = 0
74
74
  private localDirectory: readonly UserProfile[] | undefined
75
75
  private userId = getCurrentUser()?.id
76
76
 
77
77
  constructor(
78
78
  readonly workspaceId: string,
79
- readonly enabled = true
79
+ readonly enabled = true,
80
+ private readonly socket = createWorkspaceSocket(workspaceId)
80
81
  ) {
81
82
  this.store.setSender(message => this.send(message))
82
83
  }
@@ -127,18 +128,18 @@ export class CollabClient implements CollabEngineApi {
127
128
  const profile = getCurrentUser()
128
129
  if (profile?.id !== this.userId) {
129
130
  this.userId = profile?.id
130
- this.store.disconnect()
131
- clearTimeout(this.retry)
132
- if (this.socket) this.socket.close()
133
- else this.connect()
131
+ this.leave()
132
+ this.connect()
134
133
  } else if (profile) this.send({ type: 'profile', profile })
135
134
  })
136
135
  this.unsubscribeMembers = subscribeWorkspaceDirectory(() => {
137
- if (!this.wantsConnection()) {
138
- clearTimeout(this.retry)
139
- this.socket?.close()
140
- this.store.disconnect()
141
- } else this.connect()
136
+ if (this.wantsConnection()) this.connect()
137
+ else this.leave()
138
+ })
139
+ this.unsubscribeSocket = this.socket.subscribe({
140
+ open: () => this.join(),
141
+ message: message => this.receive(message),
142
+ close: () => this.reset()
142
143
  })
143
144
  this.connect()
144
145
  return () => this.stop()
@@ -158,59 +159,50 @@ export class CollabClient implements CollabEngineApi {
158
159
  this.store.disconnect()
159
160
  return
160
161
  }
161
- if (this.socket) return
162
- clearTimeout(this.retry)
162
+ if (this.release) return
163
163
  this.store.connecting()
164
- const socket = new WebSocket(wsUrl(`${getWorkspaceApiBase(this.workspaceId)}/collab`))
165
- this.socket = socket
166
- socket.onopen = () => {
167
- if (socket !== this.socket) return
168
- this.lastMessageAt = Date.now()
169
- const profile = getCurrentUser()
170
- if (!profile) {
171
- socket.close()
172
- return
173
- }
174
- this.heartbeat = setInterval(() => {
175
- if (Date.now() - this.lastMessageAt > 45_000) socket.close()
176
- else this.rawSend({ type: 'ping' })
177
- }, 15_000)
178
- this.rawSend({
179
- type: 'join',
180
- version: COLLAB_PROTOCOL_VERSION,
181
- profile,
182
- location: this.store.getLocation()
183
- })
184
- }
185
- socket.onmessage = event => {
186
- if (socket !== this.socket) return
187
- this.lastMessageAt = Date.now()
188
- try {
189
- const message = JSON.parse(String(event.data)) as CollabServerMessage
190
- if (message.type === 'welcome') this.attempts = 0
191
- const rejectedJoin =
192
- message.type === 'error' && this.store.getSnapshot().status !== 'connected'
193
- this.store.receive(message)
194
- if (rejectedJoin) socket.close()
195
- } catch {
196
- this.store.disconnect('The collaboration connection returned an invalid message.')
197
- socket.close()
198
- }
199
- }
200
- socket.onerror = () => socket.close()
201
- socket.onclose = () => {
202
- if (socket !== this.socket) return
203
- clearInterval(this.heartbeat)
204
- clearTimeout(this.presenceTimer)
205
- this.presenceTimer = undefined
206
- this.queuedPresence.clear()
207
- this.socket = null
208
- this.store.disconnect()
209
- if (this.wantsConnection()) {
210
- const delay = Math.min(500 * 2 ** this.attempts++, 10_000)
211
- this.retry = setTimeout(() => this.connect(), delay)
212
- }
213
- }
164
+ this.release = this.socket.start()
165
+ this.join()
166
+ }
167
+
168
+ private join(): void {
169
+ const profile = getCurrentUser()
170
+ if (!this.release || !profile || !this.socket.isOpen) return
171
+ this.socket.send({
172
+ type: 'join',
173
+ version: COLLAB_PROTOCOL_VERSION,
174
+ profile,
175
+ location: this.store.getLocation()
176
+ })
177
+ }
178
+
179
+ private receive(message: { type?: unknown }): void {
180
+ if (!this.release || isSharedWorkspaceEvent(message)) return
181
+ const reply = message as CollabServerMessage
182
+ if (reply.type === 'welcome') this.attempts = 0
183
+ const rejectedJoin = reply.type === 'error' && this.store.getSnapshot().status !== 'connected'
184
+ this.store.receive(reply)
185
+ if (!rejectedJoin) return
186
+ // Shared updates keep flowing on this socket; only the join is retried.
187
+ this.store.disconnect()
188
+ const delay = Math.min(500 * 2 ** this.attempts++, 10_000)
189
+ this.retry = setTimeout(() => this.join(), delay)
190
+ }
191
+
192
+ private reset(): void {
193
+ clearTimeout(this.retry)
194
+ clearTimeout(this.presenceTimer)
195
+ this.presenceTimer = undefined
196
+ this.queuedPresence.clear()
197
+ this.store.disconnect()
198
+ }
199
+
200
+ private leave(): void {
201
+ this.reset()
202
+ if (!this.release) return
203
+ this.socket.reconnect()
204
+ this.release()
205
+ this.release = undefined
214
206
  }
215
207
 
216
208
  private send(message: CollabClientMessage): void {
@@ -237,26 +229,14 @@ export class CollabClient implements CollabEngineApi {
237
229
  }
238
230
 
239
231
  private rawSend(message: CollabClientMessage): void {
240
- if (this.socket?.readyState === WebSocket.OPEN) {
241
- try {
242
- this.socket.send(JSON.stringify(message))
243
- } catch {
244
- this.socket.close()
245
- }
246
- }
232
+ if (this.release) this.socket.send(message)
247
233
  }
248
234
 
249
235
  private stop(): void {
250
236
  this.stopped = true
251
237
  this.unsubscribeCurrentUser?.()
252
238
  this.unsubscribeMembers?.()
253
- clearTimeout(this.retry)
254
- clearTimeout(this.presenceTimer)
255
- this.presenceTimer = undefined
256
- clearInterval(this.heartbeat)
257
- this.queuedPresence.clear()
258
- this.socket?.close()
259
- this.socket = null
260
- this.store.disconnect()
239
+ this.unsubscribeSocket?.()
240
+ this.leave()
261
241
  }
262
242
  }
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
3
3
  import { useRouter } from 'wouter'
4
4
  import { usePathname } from 'wouter/use-browser-location'
5
5
 
6
+ import type { ReconnectingSocket } from '@/client/runtime/reconnecting-socket'
6
7
  import { tabFromPath } from '@/lib/workspace-tabs'
7
8
 
8
9
  import { CollabClient, NO_ENGINE } from './client'
@@ -21,10 +22,15 @@ export function pageFromPath(path: string, workspaceId: string, base = ''): stri
21
22
  export type CollabProviderProps = {
22
23
  workspaceId: string
23
24
  enabled: boolean
25
+ // The workspace's live connection; presence opens its own when none is shared.
26
+ socket?: ReconnectingSocket
24
27
  children: ReactNode
25
28
  }
26
- export function CollabProvider({ workspaceId, enabled, children }: CollabProviderProps) {
27
- const engine = useMemo(() => new CollabClient(workspaceId, enabled), [workspaceId, enabled])
29
+ export function CollabProvider({ workspaceId, enabled, socket, children }: CollabProviderProps) {
30
+ const engine = useMemo(
31
+ () => new CollabClient(workspaceId, enabled, socket),
32
+ [workspaceId, enabled, socket]
33
+ )
28
34
  const router = useRouter()
29
35
  const path = usePathname(router)
30
36
  const { base } = router
@@ -263,7 +263,7 @@ export function ChatStatesPage() {
263
263
  const [showError, setShowError] = useState(false)
264
264
 
265
265
  // The running selector row's spinner reads the live activity store. Seed it,
266
- // and re-seed after any server status_snapshot reconcile (which rebuilds the
266
+ // and re-seed after any server sessions:status-snapshot reconcile (which rebuilds the
267
267
  // activity map and would drop this fixture entry).
268
268
  useEffect(() => {
269
269
  const seed = () => {
@@ -276,13 +276,13 @@ export function HarnessDebugPage() {
276
276
  // Live client frames: our own chat socket, same protocol as the real UI.
277
277
  useEffect(() => {
278
278
  if (!workspaceId) return
279
- const sock = new WebSocket(wsUrl('/ws'))
279
+ const sock = new WebSocket(wsUrl('/api/harness/events'))
280
280
  wsRef.current = sock
281
281
  sock.onmessage = e => {
282
282
  try {
283
283
  const frame = JSON.parse(String(e.data)) as Record<string, unknown>
284
284
  if (frame.workspaceId && frame.workspaceId !== workspaceId) return
285
- if (frame.type === 'session_renamed' && frame.from === sessionRef.current) {
285
+ if (frame.type === 'session:renamed' && frame.from === sessionRef.current) {
286
286
  setSessionId(frame.to as string)
287
287
  setIsNew(false)
288
288
  }
@@ -21,10 +21,10 @@ import {
21
21
  import 'tldraw/tldraw.css'
22
22
 
23
23
  import { useWorkspaceId } from '@/client/features/workspace/workspace-context'
24
- import { setScratchExecutor } from '@/client/features/scratchpad/scratch-executor'
24
+ import { useAppContext } from '@/client/runtime/app-context'
25
25
  import { persistScratchSession } from '@/client/features/scratchpad/scratch-session'
26
26
  import { BROWSER_TAB_ID } from '@/client/lib/browser-tab-id'
27
- import { type WorkspaceEvent, useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
27
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
28
28
  import type { ScratchOp, ScratchOpResult } from '@/lib/types'
29
29
  import {
30
30
  type ScratchpadFetch,
@@ -49,20 +49,18 @@ const LICENSE_KEY = process.env.PUBLIC_TLDRAW_LICENSE_KEY || undefined
49
49
  // canvas to a PNG needs the browser (`editor.toImageDataUrl`); every mutation runs
50
50
  // server-side against the disk snapshot (see server/scratchpad/executor.ts), so a
51
51
  // non-view op arriving here is unexpected.
52
- function makeExecutor(editor: Editor) {
53
- return async (op: ScratchOp): Promise<ScratchOpResult> => {
54
- if (op.kind !== 'view') {
55
- throw new Error(`Scratchpad op "${op.kind}" runs on the server, not the browser.`)
56
- }
57
- const ids = [...editor.getCurrentPageShapeIds()]
58
- if (ids.length === 0) throw new Error('Canvas is empty — nothing to view.')
59
- const { url } = await editor.toImageDataUrl(ids, {
60
- format: 'png',
61
- background: true,
62
- padding: 32
63
- })
64
- return { image: url }
52
+ async function runScratchOp(editor: Editor, op: ScratchOp): Promise<ScratchOpResult> {
53
+ if (op.kind !== 'view') {
54
+ throw new Error(`Scratchpad op "${op.kind}" runs on the server, not the browser.`)
65
55
  }
56
+ const ids = [...editor.getCurrentPageShapeIds()]
57
+ if (ids.length === 0) throw new Error('Canvas is empty — nothing to view.')
58
+ const { url } = await editor.toImageDataUrl(ids, {
59
+ format: 'png',
60
+ background: true,
61
+ padding: 32
62
+ })
63
+ return { image: url }
66
64
  }
67
65
 
68
66
  // File-backed assets: without this, tldraw inlines every pasted/dropped image as
@@ -190,6 +188,7 @@ export function Scratchpad() {
190
188
 
191
189
  function WorkspaceScratchpad({ workspaceId }: { workspaceId: string }) {
192
190
  const { apiBase } = useWorkspaceLayoutCtx()
191
+ const events = useAppContext()?.events
193
192
  const editorRef = useRef<Editor | null>(null)
194
193
  // The whole scratchpad region (canvas + tool bar + style bar). Focus is driven
195
194
  // off whether a pointerdown lands inside this, so clicking a tool keeps the
@@ -224,15 +223,27 @@ function WorkspaceScratchpad({ workspaceId }: { workspaceId: string }) {
224
223
  }).catch(() => {})
225
224
  }, [apiBase])
226
225
 
226
+ useWorkspaceEvent(workspaceId, async event => {
227
+ const editor = editorRef.current
228
+ if (event.type !== 'scratchpad:op' || !editor || !events) return
229
+ const reply = { type: 'scratchpad:op-result', opId: event.opId }
230
+ try {
231
+ const result = await runScratchOp(editor, event.op)
232
+ events.send({ ...reply, result })
233
+ } catch (error) {
234
+ events.send({ ...reply, error: error instanceof Error ? error.message : String(error) })
235
+ }
236
+ })
237
+
227
238
  // A remote save (another tab, or an agent draw landing in another tab) — pull
228
239
  // the new snapshot and load it into the live store. Skip our own echo. The
229
240
  // fetched document is pre-flighted like the initial load: if the server was
230
241
  // swapped for a newer Moi mid-session, `loadSnapshot` here would throw — flip
231
242
  // the skew notice instead (unmounting the editor, which also stops the
232
243
  // autosave timer) so this stale tab can't save over the newer file.
233
- useWorkspaceEvent((e: WorkspaceEvent) => {
234
- if (e.type !== 'scratchpad:updated' || e.workspaceId !== workspaceId) return
235
- if (e.origin && e.origin === BROWSER_TAB_ID) return
244
+ useWorkspaceEvent(workspaceId, e => {
245
+ if (e.type !== 'scratchpad:changed' && e.type !== 'workspace:connected') return
246
+ if ('origin' in e && e.origin === BROWSER_TAB_ID) return
236
247
  if (!editorRef.current) return
237
248
  fetch(`${apiBase}/scratchpad`)
238
249
  .then(r => r.json())
@@ -280,7 +291,6 @@ function WorkspaceScratchpad({ workspaceId }: { workspaceId: string }) {
280
291
  },
281
292
  { source: 'user', scope: 'document' }
282
293
  )
283
- setScratchExecutor(workspaceId, makeExecutor(editor))
284
294
  // Focus management: tldraw only fires keyboard shortcuts while the editor's
285
295
  // instance `isFocused` is set, but with `autoFocus={false}` it never flips
286
296
  // that on its own. We drive it from where the pointer lands — a pointerdown
@@ -311,7 +321,6 @@ function WorkspaceScratchpad({ workspaceId }: { workspaceId: string }) {
311
321
  stopSessionSave()
312
322
  doc.removeEventListener('pointerdown', onPointerDown, true)
313
323
  if (saveTimer.current) clearTimeout(saveTimer.current)
314
- setScratchExecutor(workspaceId, null)
315
324
  setEditor(null)
316
325
  editorRef.current = null
317
326
  }
@@ -17,7 +17,7 @@ import {
17
17
  useWorkspaceState,
18
18
  useWorkspaceStateWrite
19
19
  } from '@/client/features/workspace/workspace-state'
20
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
20
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
21
21
 
22
22
  // Compiled views from `.moi/views/`. Build and layout events refetch the list;
23
23
  // mounts within 30 s reuse it.
@@ -61,15 +61,14 @@ const selectPendingViews = (state: WorkspaceState) => state.pendingViews
61
61
  export function useViews(workspaceId: string) {
62
62
  const { apiBase } = useWorkspaceLayoutCtx()
63
63
  const queryClient = useQueryClient()
64
- useWorkspaceEvent(event => {
65
- if (event.type === 'view-layout:updated' && event.workspaceId === workspaceId) {
64
+ useWorkspaceEvent(workspaceId, event => {
65
+ if (event.type === 'views-list:changed') {
66
66
  const queryKey = workspaceKeys.views(workspaceId)
67
- // The event is newer than an in-flight list request. Apply it immediately
68
- // so the following state:changed can safely remove the pending view.
67
+ // A stale list request must not overwrite the owner’s update.
69
68
  void queryClient.cancelQueries({ queryKey })
70
69
  queryClient.setQueryData(queryKey, event.views)
71
70
  }
72
- if (event.type === 'view:deleted' && event.workspaceId === workspaceId) {
71
+ if (event.type === 'view:deleted') {
73
72
  void queryClient.invalidateQueries({ queryKey: workspaceKeys.views(workspaceId) })
74
73
  void queryClient.invalidateQueries({ queryKey: workspaceKeys.sessions(workspaceId) })
75
74
  }
@@ -7,13 +7,13 @@ import { jsonRequest, requestJson, requestVoid } from '@/client/api/http'
7
7
  import { WORKSPACE_RESOURCE_OPTIONS } from '@/client/api/query-options'
8
8
  import { workspaceKeys } from '@/client/api/workspace-keys'
9
9
  import { BROWSER_TAB_ID } from '@/client/lib/browser-tab-id'
10
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
10
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
11
11
  import type {
12
12
  WorkspaceEntry,
13
13
  WorkspaceHarness,
14
14
  WorkspaceLayoutResponse,
15
15
  WorkspaceInfoResponse,
16
- WorkspaceLayout,
16
+ WorkspaceLayoutPatch,
17
17
  WorkspaceSkillsStatus,
18
18
  WorkspaceSkillsUpdateFailure,
19
19
  HarnessType
@@ -63,15 +63,9 @@ export function useWorkspaceLayout(workspaceId: string) {
63
63
  // Workspace models, capabilities, and readiness for credential overrides or gateways.
64
64
  export function useWorkspaceHarness(workspaceId: string) {
65
65
  const queryClient = useQueryClient()
66
- useWorkspaceEvent(event => {
67
- if (event.type === 'harness:updated' && event.workspaceId === workspaceId) {
68
- void queryClient.cancelQueries({ queryKey: workspaceKeys.harness(workspaceId) })
69
- queryClient.setQueryData<WorkspaceHarness>(workspaceKeys.harness(workspaceId), prev =>
70
- prev ? { ...prev, availability: event.availability } : prev
71
- )
72
- }
66
+ useWorkspaceEvent(workspaceId, event => {
73
67
  // Env can swap credentials; the server dropped its cache — refetch.
74
- if (event.type === 'env:updated' && event.workspaceId === workspaceId) {
68
+ if (event.type === 'env:changed') {
75
69
  queryClient.invalidateQueries({ queryKey: workspaceKeys.harness(workspaceId) })
76
70
  }
77
71
  })
@@ -144,7 +138,7 @@ export function useUpdateWorkspaceSkills(workspaceId: string) {
144
138
 
145
139
  export function useSaveLayout(workspaceId: string) {
146
140
  const queryClient = useQueryClient()
147
- return useMutation<void, Error, WorkspaceLayout>({
141
+ return useMutation<void, Error, WorkspaceLayoutPatch>({
148
142
  mutationFn: layout =>
149
143
  requestVoid(
150
144
  getWorkspaceApiBase(workspaceId, queryClient),
@@ -164,6 +158,7 @@ export function useSaveLayout(workspaceId: string) {
164
158
  void queryClient.invalidateQueries({
165
159
  queryKey: workspaceInfoOptions(getWorkspaceApiBase(workspaceId, queryClient)).queryKey
166
160
  })
161
+ void queryClient.invalidateQueries({ queryKey: workspaceKeys.layout(workspaceId) })
167
162
  void queryClient.invalidateQueries({ queryKey: workspaceKeys.all, exact: true })
168
163
  queryClient.invalidateQueries({ queryKey: workspaceKeys.previews })
169
164
  }
@@ -1,6 +1,6 @@
1
1
  import { useEffect } from 'react'
2
2
  import { matchQuery, useQueryClient, type QueryClient, type Query } from '@tanstack/react-query'
3
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
3
+ import { useClientEvent } from '@/client/runtime/use-client-events'
4
4
  import type { WorkspaceLayoutResponse, HarnessType } from '@/lib/types'
5
5
  import { workspaceKeys } from '@/client/api/workspace-keys'
6
6
  import { liveStore } from '@/client/features/chat/chat-store'
@@ -73,11 +73,9 @@ export function useWorkspaceHarnessChanges(id: string, harness: HarnessType | nu
73
73
  useEffect(() => {
74
74
  if (harness) void receiveWorkspaceHarness(queryClient, id, harness)
75
75
  }, [harness, id, queryClient])
76
- useWorkspaceEvent(event => {
77
- if (event.type === 'connection:opened') {
76
+ useClientEvent(event => {
77
+ if (event.type === 'app:connected') {
78
78
  void queryClient.invalidateQueries({ queryKey: workspaceKeys.layout(id) })
79
- } else if (event.type === 'workspace-harness:switched' && event.workspaceId === id) {
80
- void receiveWorkspaceHarness(queryClient, id, event.harness)
81
79
  }
82
80
  })
83
81
  }
@@ -1,5 +1,7 @@
1
1
  import { queryClient as appQueryClient } from '@/client/api/query-client'
2
2
  import { workspaceKeys } from '@/client/api/workspace-keys'
3
+ import { wsUrl } from '@/client/lib/ws-url'
4
+ import { ReconnectingSocket } from '@/client/runtime/reconnecting-socket'
3
5
  import type { QueryClient } from '@tanstack/react-query'
4
6
  import type { WorkspaceLayoutResponse } from '@/lib/types'
5
7
 
@@ -23,3 +25,10 @@ export function getWorkspaceAddress(localId: string, client: QueryClient = appQu
23
25
  const apiBase = workspaceInfo(localId, client)?.apiBase
24
26
  return apiBase ? decodeURIComponent(apiBase.slice('/api/workspaces/'.length)) : localId
25
27
  }
28
+
29
+ // The address is read on every connect: a remote workspace resolves to its owner.
30
+ export function createWorkspaceSocket(workspaceId: string): ReconnectingSocket {
31
+ return new ReconnectingSocket(() => wsUrl(`${getWorkspaceApiBase(workspaceId)}/events`), {
32
+ ping: true
33
+ })
34
+ }
@@ -2,17 +2,17 @@ import { useQueryClient } from '@tanstack/react-query'
2
2
 
3
3
  import { workspaceKeys } from '@/client/api/workspace-keys'
4
4
  import { useUpdateEnv, useWorkspaceEnv } from '@/client/features/workspace/settings/api'
5
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
5
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
6
6
 
7
7
  // Workspace env state in one hook: the masked env view (query), the patch
8
8
  // mutation, and live tracking — anything that changes the env outside this
9
9
  // client (the `moi env` CLI, another tab) makes the server broadcast
10
- // `env:updated`, which invalidates the query so consumers stay fresh without
10
+ // `env:changed`, which invalidates the query so consumers stay fresh without
11
11
  // wiring the subscription themselves.
12
12
  export function useEnvVars(workspaceId: string) {
13
13
  const qc = useQueryClient()
14
- useWorkspaceEvent(e => {
15
- if (e.type === 'env:updated' && e.workspaceId === workspaceId) {
14
+ useWorkspaceEvent(workspaceId, e => {
15
+ if (e.type === 'env:changed') {
16
16
  qc.invalidateQueries({ queryKey: workspaceKeys.env(workspaceId) })
17
17
  }
18
18
  })
@@ -11,7 +11,7 @@ import { useAppletEvent } from '@/client/features/applets/applet-runtime'
11
11
  import { useWorkspaceTabs } from '@/client/features/workspace/workspace-preferences'
12
12
  import { resolveActiveTab, tabAvailable } from './tab-resolution'
13
13
  import { useWorkspaceLayoutCtx } from './workspace-layout-context'
14
- import { useNavigationClient } from '@/client/runtime/use-workspace-events'
14
+ import { useNavigationClient } from '@/client/runtime/use-client-events'
15
15
  import { useSelectLinkedChat } from '@/client/features/chat/sessions/api'
16
16
  import { getCachedViews } from '@/client/features/views/api'
17
17
  import type { ViewInfo, WorkspaceTabId, WorkspaceTabsState } from '@/lib/types'
@@ -0,0 +1,51 @@
1
+ import { useEffect, useMemo } from 'react'
2
+ import { useQueryClient } from '@tanstack/react-query'
3
+
4
+ import { workspaceKeys } from '@/client/api/workspace-keys'
5
+ import { useAppContext } from '@/client/runtime/app-context'
6
+ import type { ReconnectingSocket } from '@/client/runtime/reconnecting-socket'
7
+ import { isSharedWorkspaceEvent } from '@/lib/events'
8
+
9
+ import { createWorkspaceSocket, getWorkspaceAddress } from './remote'
10
+
11
+ // The owner's live connection for the shown workspace. Shared updates join the
12
+ // app's event stream under this browser's workspace ID, so listeners treat
13
+ // local and remote workspaces alike.
14
+ export function useWorkspaceSocket(workspaceId: string): ReconnectingSocket {
15
+ const events = useAppContext()?.events
16
+ const queryClient = useQueryClient()
17
+ const socket = useMemo(() => createWorkspaceSocket(workspaceId), [workspaceId])
18
+ useEffect(() => {
19
+ if (!events) return
20
+ // Mark the owner's snapshot stale before the visitor's layout refetch reads it.
21
+ const refreshOwnerInfo = () => {
22
+ const address = getWorkspaceAddress(workspaceId, queryClient)
23
+ if (address !== workspaceId)
24
+ void queryClient.invalidateQueries({ queryKey: workspaceKeys.layout(address) })
25
+ }
26
+ const unsubscribe = socket.subscribe({
27
+ // Catch up on anything missed while disconnected.
28
+ open: () => {
29
+ refreshOwnerInfo()
30
+ for (const queryKey of [
31
+ workspaceKeys.layout(workspaceId),
32
+ workspaceKeys.widgets(workspaceId),
33
+ workspaceKeys.views(workspaceId)
34
+ ])
35
+ void queryClient.invalidateQueries({ queryKey })
36
+ events.emit({ type: 'workspace:connected', workspaceId })
37
+ },
38
+ message: message => {
39
+ if (!isSharedWorkspaceEvent(message)) return
40
+ if (message.type === 'workspace-config:changed') refreshOwnerInfo()
41
+ events.emit({ ...message, workspaceId })
42
+ }
43
+ })
44
+ const stop = socket.start()
45
+ return () => {
46
+ unsubscribe()
47
+ stop()
48
+ }
49
+ }, [events, queryClient, socket, workspaceId])
50
+ return socket
51
+ }
@@ -49,7 +49,7 @@ import { useWorkspaceLayoutCtx } from '@/client/features/workspace/workspace-lay
49
49
  import { WorkspaceMenu } from '@/client/features/workspace/workspace-menu'
50
50
  import { effectiveOpenTabs, tabAvailable } from '@/client/features/workspace/tab-resolution'
51
51
  import { useWorkspaceNavigation } from '@/client/features/workspace/use-workspace-navigation'
52
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
52
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
53
53
  import { useUiStore } from '@/client/store/ui'
54
54
  import {
55
55
  type CreateWorkspaceTabItem,
@@ -263,12 +263,8 @@ export function WorkspaceContent({ widgets, views: allViews }: WorkspaceContentP
263
263
  setFloatingChatOpen(false)
264
264
  }
265
265
 
266
- useWorkspaceEvent(event => {
267
- if (
268
- event.type === 'view:deleted' &&
269
- event.workspaceId === workspaceId &&
270
- activeTab === viewTabId(event.name)
271
- ) {
266
+ useWorkspaceEvent(workspaceId, event => {
267
+ if (event.type === 'view:deleted' && activeTab === viewTabId(event.name)) {
272
268
  openTab('overview')
273
269
  }
274
270
  })
@@ -11,7 +11,7 @@ import {
11
11
  } from '@/client/features/workspace/api'
12
12
  import { workspaceKeys } from '@/client/api/workspace-keys'
13
13
  import { useLatestRef } from '@/client/lib/use-latest-ref'
14
- import type { WorkspaceLayout, HarnessType } from '@/lib/types'
14
+ import type { WorkspaceLayout, WorkspaceLayoutPatch, HarnessType } from '@/lib/types'
15
15
  import { createDefaultWorkspaceLayout } from '@/lib/workspace-layout'
16
16
 
17
17
  import { useWorkspaceState } from './workspace-state'
@@ -22,7 +22,7 @@ export type WorkspaceLayoutContextValue = {
22
22
  layout: WorkspaceLayout
23
23
  // Merge a partial update into the layout: updates the query cache immediately
24
24
  // (optimistic) then debounces a PUT to the server via the save mutation.
25
- setLayout: (update: Partial<WorkspaceLayout>) => void
25
+ setLayout: (update: WorkspaceLayoutPatch) => void
26
26
  // Workspace metadata that rides along on the layout endpoint.
27
27
  name: string | null
28
28
  cwd: string | null
@@ -56,8 +56,7 @@ export function useWorkspaceThemeSetting(): WorkspaceLayout['theme'] {
56
56
  return useContext(WorkspaceLayoutContext)?.layout.theme
57
57
  }
58
58
 
59
- // Strip the server-only metadata so what we PUT back (and expose as `layout`)
60
- // is just the persisted `WorkspaceLayout`.
59
+ // Expose the layout separately from its routing metadata.
61
60
  function stripMeta(data: WorkspaceLayoutResponse): WorkspaceLayout {
62
61
  const {
63
62
  cwd: _cwd,
@@ -88,10 +87,10 @@ export function WorkspaceLayoutProvider({ id, children }: WorkspaceLayoutProvide
88
87
  // reconcile), so reach the latest mutate via a ref instead of closing over it.
89
88
  const saveRef = useLatestRef(save.mutate)
90
89
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
91
- const pendingSave = useRef<WorkspaceLayout | null>(null)
90
+ const pendingSave = useRef<WorkspaceLayoutPatch | null>(null)
92
91
 
93
92
  const setLayout = useCallback(
94
- (update: Partial<WorkspaceLayout>) => {
93
+ (update: WorkspaceLayoutPatch) => {
95
94
  const key = workspaceKeys.layout(id)
96
95
  const prev = qc.getQueryData<WorkspaceLayoutResponse>(key)
97
96
  if (!prev) return
@@ -100,15 +99,9 @@ export function WorkspaceLayoutProvider({ id, children }: WorkspaceLayoutProvide
100
99
  // Optimistic: the grid/theme reflects the change before the PUT lands.
101
100
  const next = { ...prev, ...update }
102
101
  qc.setQueryData<WorkspaceLayoutResponse>(key, next)
103
- pendingSave.current = stripMeta(next)
102
+ pendingSave.current = { ...pendingSave.current, ...update }
104
103
 
105
104
  if (timer.current) clearTimeout(timer.current)
106
- // Persist the value captured at call time, NOT the cache at fire time: a
107
- // `workspace:updated` broadcast can invalidate + refetch this query inside
108
- // the debounce window, and reading the cache then would PUT the server's
109
- // pre-change layout back (reverting the user's edit on disk). Rapid calls
110
- // still coalesce — each call's `prev` already includes the previous
111
- // optimistic write.
112
105
  timer.current = setTimeout(() => {
113
106
  timer.current = null
114
107
  const payload = pendingSave.current