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,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
  }
@@ -1,3 +1,4 @@
1
+ import { viewTabId } from '@/lib/workspace-tabs'
1
2
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/workspace-layout-context'
2
3
  import type { SpeedMode } from '@/lib/types'
3
4
  import type {
@@ -13,9 +14,10 @@ import { jsonRequest, requestJson, requestVoid } from '@/client/api/http'
13
14
  import { workspaceKeys } from '@/client/api/workspace-keys'
14
15
  import {
15
16
  getCachedWorkspaceState,
16
- useWorkspaceState
17
+ useWorkspaceState,
18
+ useWorkspaceStateWrite
17
19
  } from '@/client/features/workspace/workspace-state'
18
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
20
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
19
21
 
20
22
  // Compiled views from `.moi/views/`. Build and layout events refetch the list;
21
23
  // mounts within 30 s reuse it.
@@ -59,15 +61,14 @@ const selectPendingViews = (state: WorkspaceState) => state.pendingViews
59
61
  export function useViews(workspaceId: string) {
60
62
  const { apiBase } = useWorkspaceLayoutCtx()
61
63
  const queryClient = useQueryClient()
62
- useWorkspaceEvent(event => {
63
- if (event.type === 'view-layout:updated' && event.workspaceId === workspaceId) {
64
+ useWorkspaceEvent(workspaceId, event => {
65
+ if (event.type === 'views-list:changed') {
64
66
  const queryKey = workspaceKeys.views(workspaceId)
65
- // The event is newer than an in-flight list request. Apply it immediately
66
- // so the following state:changed can safely remove the pending view.
67
+ // A stale list request must not overwrite the owner’s update.
67
68
  void queryClient.cancelQueries({ queryKey })
68
69
  queryClient.setQueryData(queryKey, event.views)
69
70
  }
70
- if (event.type === 'view:deleted' && event.workspaceId === workspaceId) {
71
+ if (event.type === 'view:deleted') {
71
72
  void queryClient.invalidateQueries({ queryKey: workspaceKeys.views(workspaceId) })
72
73
  void queryClient.invalidateQueries({ queryKey: workspaceKeys.sessions(workspaceId) })
73
74
  }
@@ -153,12 +154,35 @@ export type SubmitViewInput = {
153
154
  }
154
155
  export function useSubmitView(workspaceId: string) {
155
156
  const { local } = useViewBase(workspaceId)
156
- return useViewMutation(workspaceId, ({ viewId, ...input }: SubmitViewInput) =>
157
- requestJson<{ viewId: string; sessionId: string }>(
158
- `${local}/views/${viewId}/submit`,
159
- jsonRequest('POST', input),
160
- 'Couldn’t start view chat'
161
- )
162
- )
157
+ return useWorkspaceStateWrite<
158
+ SubmitViewInput,
159
+ {
160
+ viewId: string
161
+ sessionId: string
162
+ state: WorkspaceState
163
+ }
164
+ >(workspaceId, {
165
+ request: ({ viewId, ...input }) =>
166
+ requestJson(
167
+ `${local}/views/${viewId}/submit`,
168
+ jsonRequest('POST', input),
169
+ 'Couldn’t start view chat'
170
+ ),
171
+ optimistic: (draft, { viewId, sessionId, requirements }) => {
172
+ const tabId = viewTabId(viewId)
173
+ if (!draft.pinnedSessionId) {
174
+ draft.selected[tabId] = sessionId
175
+ draft.sessions[sessionId] = { ...draft.sessions[sessionId], tabId }
176
+ }
177
+ const view = draft.pendingViews[viewId]
178
+ if (view?.status === 'draft')
179
+ Object.assign(view, {
180
+ status: 'starting',
181
+ requirements,
182
+ buildSessionId: draft.pinnedSessionId ?? sessionId
183
+ })
184
+ },
185
+ errorTitle: 'Couldn’t start view chat'
186
+ })
163
187
  }
164
188
  export const useDiscardView = useDeleteView
@@ -12,13 +12,9 @@ import {
12
12
  } from '@/client/features/chat/chat-send'
13
13
  import {
14
14
  renameSelectedSessionInCache,
15
- setSelectedSessionInCache,
16
15
  usePinnedSession
17
16
  } from '@/client/features/chat/sessions/use-selected-session'
18
- import {
19
- changeWorkspaceStateCache,
20
- getCachedWorkspaceState
21
- } from '@/client/features/workspace/workspace-state'
17
+ import { getCachedWorkspaceState } from '@/client/features/workspace/workspace-state'
22
18
  import { useWorkspaceHarness } from '@/client/features/workspace/api'
23
19
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/workspace-layout-context'
24
20
  import {
@@ -55,17 +51,13 @@ export function useViewActions() {
55
51
 
56
52
  if (!pinnedSessionId)
57
53
  startOptimisticSession({
58
- tabId: viewTabId(pendingView.id),
59
54
  queryClient,
60
55
  workspaceId,
61
56
  sessionId,
62
57
  text,
63
58
  filenames: attachments.map(attachment => attachment.label)
64
59
  })
65
- if (!pinnedSessionId) {
66
- moveChatDraft(workspaceId, draftId, sessionId)
67
- setSelectedSessionInCache(queryClient, workspaceId, sessionId, viewTabId(pendingView.id))
68
- }
60
+ if (!pinnedSessionId) moveChatDraft(workspaceId, draftId, sessionId)
69
61
  const prepared = prepareOptimisticSend(
70
62
  { queryClient, workspaceId, sessionId, text },
71
63
  attachments
@@ -81,12 +73,6 @@ export function useViewActions() {
81
73
  config?.speedMode ?? defaults?.speedMode
82
74
  )
83
75
 
84
- changeWorkspaceStateCache(queryClient, workspaceId, draft => {
85
- const view = draft.pendingViews[pendingView.id]
86
- if (view?.status === 'draft')
87
- Object.assign(view, { status: 'starting', requirements: text, buildSessionId: sessionId })
88
- })
89
-
90
76
  try {
91
77
  const result = await submitMutation.mutateAsync({
92
78
  viewId: pendingView.id,
@@ -105,13 +91,6 @@ export function useViewActions() {
105
91
  })
106
92
  moveChatDraft(workspaceId, sessionId, result.sessionId)
107
93
  renameSelectedSessionInCache(queryClient, workspaceId, sessionId, result.sessionId)
108
- if (!pinnedSessionId)
109
- setSelectedSessionInCache(
110
- queryClient,
111
- workspaceId,
112
- result.sessionId,
113
- viewTabId(pendingView.id)
114
- )
115
94
  finishComposerSend(workspaceId, attachments)
116
95
  const draftKey = composerDraftKey(workspaceId, result.sessionId)
117
96
  const ui = useUiStore.getState()
@@ -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
  })
@@ -1,12 +1,5 @@
1
- // Pure tab-state derivation for the workspace screen. The URL is the live
2
- // address for the active tab (`/workspace/:id/views/<id>`, etc.); personal state
3
- // keeps the open set and active tab in sync across windows. These helpers
4
- // turn (URL segment + layout + what actually exists) into the rendered state.
5
1
  import type { ViewInfo, WorkspaceTabId, WorkspaceTabsState } from '@/lib/types'
6
2
  import { viewIdFromTab } from '@/lib/workspace-tabs'
7
- import { createDefaultWorkspaceTabs } from '@/lib/workspace-layout'
8
-
9
- const DEFAULT_TABS = createDefaultWorkspaceTabs()
10
3
 
11
4
  // Whether a tab id points at something that exists: static tabs always do,
12
5
  // view tabs only while their pending or compiled view exists.
@@ -20,7 +13,7 @@ export function tabAvailable(tab: WorkspaceTabId, views: ViewInfo[]) {
20
13
  // back to the defaults when nothing survives.
21
14
  export function effectiveOpenTabs(tabs: WorkspaceTabsState, views: ViewInfo[]): WorkspaceTabId[] {
22
15
  const open = tabs.open.filter(tab => tabAvailable(tab, views))
23
- return open.length > 0 ? open : DEFAULT_TABS.open
16
+ return open.length > 0 ? open : ['overview']
24
17
  }
25
18
 
26
19
  // An explicit URL keeps its destination, including a missing view so the host