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
@@ -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'
@@ -46,7 +46,7 @@ type UseWorkspaceNavigationOptions = {
46
46
  export function useWorkspaceNavigation({ views, onOpenChat }: UseWorkspaceNavigationOptions) {
47
47
  const queryClient = useQueryClient()
48
48
  const { workspaceId, apiBase } = useWorkspaceLayoutCtx()
49
- const [tabsState, saveTabs] = useWorkspaceTabs()
49
+ const [tabsState, saveTabs, saveActiveTab] = useWorkspaceTabs(views)
50
50
  const latest = useRef({ views, tabsState, onOpenChat })
51
51
  useLayoutEffect(() => {
52
52
  latest.current = { views, tabsState, onOpenChat }
@@ -219,8 +219,9 @@ export function useWorkspaceNavigation({ views, onOpenChat }: UseWorkspaceNaviga
219
219
  remembered.set(activeTab, `moi:/${activeTab}${search}`)
220
220
  const current = latest.current.tabsState
221
221
  const open = current.open.includes(activeTab) ? current.open : [...current.open, activeTab]
222
- if (open !== current.open || current.active !== activeTab) setTabs({ open, active: activeTab })
223
- }, [activeTab, isAvailableTab, latest, remembered, search, setTabs])
222
+ if (open !== current.open) setTabs({ open, active: activeTab })
223
+ else if (current.active !== activeTab) saveActiveTab(activeTab)
224
+ }, [activeTab, isAvailableTab, latest, remembered, search, setTabs, saveActiveTab])
224
225
 
225
226
  // React bubbling includes applet/chat portals. Native modified clicks and
226
227
  // downloads keep a real href, so the browser can handle them normally.
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import { useFloatingChatOpen } from './workspace-preferences'
1
2
  import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'
2
3
 
3
4
  import { AnimatePresence } from 'motion/react'
@@ -48,7 +49,7 @@ import { useWorkspaceLayoutCtx } from '@/client/features/workspace/workspace-lay
48
49
  import { WorkspaceMenu } from '@/client/features/workspace/workspace-menu'
49
50
  import { effectiveOpenTabs, tabAvailable } from '@/client/features/workspace/tab-resolution'
50
51
  import { useWorkspaceNavigation } from '@/client/features/workspace/use-workspace-navigation'
51
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
52
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
52
53
  import { useUiStore } from '@/client/store/ui'
53
54
  import {
54
55
  type CreateWorkspaceTabItem,
@@ -126,7 +127,7 @@ export function WorkspaceContent({ widgets, views: allViews }: WorkspaceContentP
126
127
  const frame = useWorkspaceFrame()
127
128
  const { mode, canUseSplit, setMode } = frame
128
129
  const [widgetMode, setWidgetMode] = useState<WidgetMode>('idle')
129
- const [floatingChatOpen, setFloatingChatOpen] = useState(false)
130
+ const [floatingChatOpen, setFloatingChatOpen] = useFloatingChatOpen()
130
131
  const [chatFocusRequest, setChatFocusRequest] = useState(0)
131
132
  const pendingViewRefs = useRef(new Map<string, PendingViewHandle>())
132
133
  const sessionActivity = useLive(state => state.activity)
@@ -238,16 +239,6 @@ export function WorkspaceContent({ widgets, views: allViews }: WorkspaceContentP
238
239
  openPopup: () => setFloatingChatOpen(true)
239
240
  })
240
241
 
241
- useEffect(() => {
242
- const open = tabsState.open.filter(tab => tabAvailable(tab, allViews))
243
- if (open.length === tabsState.open.length) return
244
- const nextOpen = effectiveOpenTabs(tabsState, allViews)
245
- setTabs({
246
- open: nextOpen,
247
- active: nextOpen.includes(tabsState.active) ? tabsState.active : nextOpen[0]
248
- })
249
- }, [allViews, setTabs, tabsState])
250
-
251
242
  useEffect(() => {
252
243
  if (!activeDraftViewId) return
253
244
  if (mode === 'fullscreen') setFloatingChatOpen(true)
@@ -272,12 +263,8 @@ export function WorkspaceContent({ widgets, views: allViews }: WorkspaceContentP
272
263
  setFloatingChatOpen(false)
273
264
  }
274
265
 
275
- useWorkspaceEvent(event => {
276
- if (
277
- event.type === 'view:deleted' &&
278
- event.workspaceId === workspaceId &&
279
- activeTab === viewTabId(event.name)
280
- ) {
266
+ useWorkspaceEvent(workspaceId, event => {
267
+ if (event.type === 'view:deleted' && activeTab === viewTabId(event.name)) {
281
268
  openTab('overview')
282
269
  }
283
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
@@ -1,8 +1,18 @@
1
1
  import { useCallback, useMemo } from 'react'
2
+ import { useQueryClient } from '@tanstack/react-query'
3
+ import { jsonRequest, requestJson } from '@/client/api/http'
2
4
  import { useUiStore, defaultWorkspaceUi, type WorkspaceUi } from '@/client/store/ui'
3
- import { normalizeWorkspaceTabs } from '@/lib/workspace-layout'
4
- import type { WorkspaceTabsState } from '@/lib/types'
5
+ import { useWorkspaceSessionStore } from '@/client/store/workspace-session'
6
+ import { normalizeOpenTabs } from '@/lib/workspace-layout'
7
+ import type { ViewInfo, WorkspaceState, WorkspaceTabId, WorkspaceTabsState } from '@/lib/types'
5
8
  import { useWorkspaceLayoutCtx } from './workspace-layout-context'
9
+ import {
10
+ getCachedWorkspaceState,
11
+ useWorkspaceState,
12
+ useWorkspaceStateWrite
13
+ } from './workspace-state'
14
+ import { tabAvailable } from './tab-resolution'
15
+ import { viewTabId } from '@/lib/workspace-tabs'
6
16
 
7
17
  // Per-browser preferences for one workspace, local or remote. See client/store/ui.ts.
8
18
  export function useWorkspaceUi() {
@@ -18,17 +28,64 @@ export function useWorkspaceUi() {
18
28
  return [ui, save] as const
19
29
  }
20
30
 
21
- export function useWorkspaceTabs() {
31
+ export function useFloatingChatOpen() {
22
32
  const { workspaceId } = useWorkspaceLayoutCtx()
23
- const tabs = useUiStore(state => state.workspaces[workspaceId]?.tabs ?? defaultWorkspaceUi.tabs)
24
- const setWorkspaceUi = useUiStore(state => state.setWorkspaceUi)
33
+ const open = useWorkspaceSessionStore(state => state.workspaces[workspaceId]?.chatOpen ?? false)
34
+ const save = useWorkspaceSessionStore(state => state.setWorkspaceSession)
35
+ const setOpen = useCallback(
36
+ (chatOpen: boolean) => save(workspaceId, { chatOpen }),
37
+ [workspaceId, save]
38
+ )
39
+ return [open, setOpen] as const
40
+ }
41
+
42
+ function sameTabs(a: WorkspaceTabId[] | undefined, b: WorkspaceTabId[]) {
43
+ return a?.length === b.length && a.every((tab, index) => tab === b[index])
44
+ }
45
+
46
+ // Requires loaded personal state and views.
47
+ export function useWorkspaceTabs(views: ViewInfo[]) {
48
+ const { workspaceId } = useWorkspaceLayoutCtx()
49
+ const queryClient = useQueryClient()
50
+ const { data } = useWorkspaceState(workspaceId)
51
+ const active = useWorkspaceSessionStore(
52
+ state => state.workspaces[workspaceId]?.activeTab ?? 'overview'
53
+ )
54
+ const saveSession = useWorkspaceSessionStore(state => state.setWorkspaceSession)
55
+ const setActiveTab = useCallback(
56
+ (activeTab: WorkspaceTabId) => saveSession(workspaceId, { activeTab }),
57
+ [workspaceId, saveSession]
58
+ )
59
+ const { mutate } = useWorkspaceStateWrite<WorkspaceTabId[]>(workspaceId, {
60
+ request: openTabs =>
61
+ requestJson<WorkspaceState>(
62
+ `/api/workspaces/${workspaceId}/state/tabs`,
63
+ jsonRequest('PUT', { openTabs })
64
+ ),
65
+ optimistic: (draft, openTabs) => {
66
+ draft.openTabs = openTabs
67
+ },
68
+ errorTitle: 'Couldn’t save workspace tabs'
69
+ })
70
+ // Deleted views leave the saved list on the next tab change.
71
+ const open = useMemo(() => {
72
+ const all: WorkspaceTabId[] = ['scratchpad', ...views.map(view => viewTabId(view.id))]
73
+ return [
74
+ 'overview',
75
+ ...normalizeOpenTabs(data?.openTabs ?? all).filter(tab => tabAvailable(tab, views))
76
+ ] satisfies WorkspaceTabId[]
77
+ }, [data?.openTabs, views])
78
+ const tabs = useMemo(() => ({ open, active }), [open, active])
79
+
25
80
  const setTabs = useCallback(
26
81
  (tabs: WorkspaceTabsState) => {
27
- const next = normalizeWorkspaceTabs(tabs)
28
- setWorkspaceUi(workspaceId, { tabs: next })
29
- return next
82
+ const openTabs = normalizeOpenTabs(tabs.open)
83
+ setActiveTab(tabs.active)
84
+ if (!sameTabs(getCachedWorkspaceState(queryClient, workspaceId)?.openTabs, openTabs))
85
+ mutate(openTabs)
86
+ return tabs
30
87
  },
31
- [workspaceId, setWorkspaceUi]
88
+ [workspaceId, setActiveTab, queryClient, mutate]
32
89
  )
33
- return [tabs, setTabs] as const
90
+ return [tabs, setTabs, setActiveTab] as const
34
91
  }
@@ -3,12 +3,12 @@ import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tansta
3
3
  import { requestJson } from '@/client/api/http'
4
4
  import { workspaceKeys } from '@/client/api/workspace-keys'
5
5
  import { toast } from '@/client/components/ui/toast'
6
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
7
- import type { WorkspaceState } from '@/lib/types'
6
+ import { useClientEvent } from '@/client/runtime/use-client-events'
7
+ import type { CompiledView, WorkspaceState } from '@/lib/types'
8
8
 
9
9
  // Personal state for one workspace: tabs, pin, selected chats, chat
10
10
  // settings and fork history, and views being built. One cache, kept current by
11
- // write replies and `state:changed` events instead of refetches.
11
+ // write replies and `personal-state:changed` events instead of refetches.
12
12
 
13
13
  export function workspaceStateKey(workspaceId: string) {
14
14
  return workspaceKeys.state(workspaceId)
@@ -24,6 +24,15 @@ function writesInFlight(queryClient: QueryClient, workspaceId: string): number {
24
24
  return queryClient.isMutating({ mutationKey: writeKey(workspaceId) })
25
25
  }
26
26
 
27
+ // The newest server update received while an optimistic write is visible.
28
+ const deferredStates = new WeakMap<QueryClient, Map<string, WorkspaceState>>()
29
+
30
+ function deferWorkspaceState(client: QueryClient, workspaceId: string, state: WorkspaceState) {
31
+ let states = deferredStates.get(client)
32
+ if (!states) deferredStates.set(client, (states = new Map()))
33
+ states.set(workspaceId, newer(states.get(workspaceId), state))
34
+ }
35
+
27
36
  // Keep the newer copy. A reply or event can arrive after a newer one.
28
37
  function newer(current: WorkspaceState | undefined, next: WorkspaceState): WorkspaceState {
29
38
  return current && current.revision > next.revision ? current : next
@@ -40,7 +49,10 @@ export function workspaceStateOptions(queryClient: QueryClient, workspaceId: str
40
49
  const current = queryClient.getQueryData<WorkspaceState>(queryKey)
41
50
  // A write in flight already shows its change; its reply brings the
42
51
  // server's copy.
43
- if (current && writesInFlight(queryClient, workspaceId) > 0) return current
52
+ if (current && writesInFlight(queryClient, workspaceId) > 0) {
53
+ deferWorkspaceState(queryClient, workspaceId, next)
54
+ return current
55
+ }
44
56
  return newer(current, next)
45
57
  },
46
58
  // Events keep the cache current, so new observers never refetch. A focus
@@ -87,27 +99,33 @@ export function receiveWorkspaceState(
87
99
  workspaceId: string,
88
100
  next: WorkspaceState
89
101
  ): void {
102
+ if (writesInFlight(queryClient, workspaceId) > 0) {
103
+ deferWorkspaceState(queryClient, workspaceId, next)
104
+ return
105
+ }
90
106
  queryClient.setQueryData<WorkspaceState>(workspaceStateKey(workspaceId), current =>
91
107
  newer(current, next)
92
108
  )
93
109
  }
94
110
 
95
- type WorkspaceStateWriteOptions<Input> = {
96
- request: (input: Input) => Promise<WorkspaceState>
111
+ type StateReply = WorkspaceState | { state: WorkspaceState }
112
+
113
+ type WorkspaceStateWriteOptions<Input, Result extends StateReply> = {
114
+ request: (input: Input) => Promise<Result>
97
115
  optimistic?: (draft: WorkspaceState, input: Input) => void
98
- onSuccess?: (state: WorkspaceState, input: Input) => void
116
+ onSuccess?: (state: Result, input: Input) => void
99
117
  errorTitle: string
100
118
  }
101
119
 
102
120
  // A write that answers with the new state. Writes to one workspace run in
103
- // order; the last reply becomes the cache, and a failure refetches it.
104
- export function useWorkspaceStateWrite<Input>(
121
+ // order; the newest reply or event becomes the cache, and a failure refetches it.
122
+ export function useWorkspaceStateWrite<Input, Result extends StateReply = WorkspaceState>(
105
123
  workspaceId: string,
106
- { request, optimistic, onSuccess, errorTitle }: WorkspaceStateWriteOptions<Input>
124
+ { request, optimistic, onSuccess, errorTitle }: WorkspaceStateWriteOptions<Input, Result>
107
125
  ) {
108
126
  const queryClient = useQueryClient()
109
127
  const queryKey = workspaceStateKey(workspaceId)
110
- return useMutation<WorkspaceState, Error, Input>({
128
+ return useMutation<Result, Error, Input>({
111
129
  mutationKey: writeKey(workspaceId),
112
130
  scope: { id: `workspace-state:${workspaceId}` },
113
131
  mutationFn: request,
@@ -116,15 +134,23 @@ export function useWorkspaceStateWrite<Input>(
116
134
  await queryClient.cancelQueries({ queryKey, exact: true })
117
135
  changeWorkspaceStateCache(queryClient, workspaceId, draft => optimistic(draft, input))
118
136
  },
119
- onSuccess: (state, input) => {
120
- // This write still counts as in flight; a later one owns the cache.
121
- if (writesInFlight(queryClient, workspaceId) === 1)
122
- receiveWorkspaceState(queryClient, workspaceId, state)
123
- onSuccess?.(state, input)
137
+ onSuccess: (result, input) => {
138
+ receiveWorkspaceState(queryClient, workspaceId, 'state' in result ? result.state : result)
139
+ onSuccess?.(result, input)
124
140
  },
125
141
  onError: error => {
126
142
  toast.add({ title: errorTitle, description: error.message, type: 'error' })
127
- void queryClient.invalidateQueries({ queryKey, exact: true })
143
+ },
144
+ onSettled: (_result, error) => {
145
+ // This mutation still counts as pending until onSettled returns.
146
+ if (writesInFlight(queryClient, workspaceId) === 1) {
147
+ const states = deferredStates.get(queryClient)
148
+ const latest = states?.get(workspaceId)
149
+ states?.delete(workspaceId)
150
+ if (latest)
151
+ queryClient.setQueryData<WorkspaceState>(queryKey, current => newer(current, latest))
152
+ }
153
+ if (error) void queryClient.invalidateQueries({ queryKey, exact: true })
128
154
  }
129
155
  })
130
156
  }
@@ -133,10 +159,20 @@ export function useWorkspaceStateWrite<Input>(
133
159
  // changes, so cached states stay current even while their workspace is closed.
134
160
  export function useWorkspaceStateSync(): void {
135
161
  const queryClient = useQueryClient()
136
- useWorkspaceEvent(event => {
137
- if (event.type !== 'state:changed') return
138
- if (!getCachedWorkspaceState(queryClient, event.workspaceId)) return
139
- if (writesInFlight(queryClient, event.workspaceId) > 0) return
162
+ useClientEvent(event => {
163
+ if (event.type !== 'personal-state:changed') return
164
+ const current = getCachedWorkspaceState(queryClient, event.workspaceId)
165
+ if (!current || current.revision > event.state.revision) return
166
+ // The personal socket can deliver completion before the owner sends its views list.
167
+ const key = workspaceKeys.views(event.workspaceId)
168
+ const views = queryClient.getQueryData<CompiledView[]>(key)
169
+ const missing = event.completedViews?.filter(
170
+ view => current.pendingViews[view.id] && !views?.some(old => old.id === view.id)
171
+ )
172
+ if (views && missing?.length) {
173
+ void queryClient.cancelQueries({ queryKey: key })
174
+ queryClient.setQueryData(key, [...views, ...missing])
175
+ }
140
176
  receiveWorkspaceState(queryClient, event.workspaceId, event.state)
141
177
  })
142
178
  }
@@ -1,6 +1,6 @@
1
1
  import { createContext, useContext } from 'react'
2
2
 
3
- import type { WorkspaceEventsClient } from './workspace-events'
3
+ import type { AppEventsClient } from './app-events'
4
4
 
5
5
  // App-wide state that lives exactly as long as the app: created by
6
6
  // `AppProvider` (app/app-provider.tsx) when the app mounts and shut down when
@@ -8,7 +8,7 @@ import type { WorkspaceEventsClient } from './workspace-events'
8
8
  // app itself.
9
9
  export type AppContextValue = {
10
10
  // The page's workspace events socket.
11
- events: WorkspaceEventsClient
11
+ events: AppEventsClient
12
12
  }
13
13
 
14
14
  export const AppContext = createContext<AppContextValue | undefined>(undefined)
@@ -0,0 +1,75 @@
1
+ import type { ClientEvent } from '@/lib/events'
2
+
3
+ import { ReconnectingSocket } from './reconnecting-socket'
4
+ export type { ClientEvent } from '@/lib/events'
5
+
6
+ export type ClientEventHandler = (event: ClientEvent) => void
7
+
8
+ export type AppEventsClientOptions = {
9
+ reconnectBaseDelayMs?: number
10
+ }
11
+
12
+ // The app's event bus, fed by the machine's `/api/events` socket. Workspace
13
+ // sockets emit into it too, so listeners see one stream. `AppProvider` opens
14
+ // the socket when the app mounts and closes it when the app unmounts.
15
+ export class AppEventsClient {
16
+ private readonly listeners = new Set<ClientEventHandler>()
17
+ private readonly socket: ReconnectingSocket
18
+ private release: (() => void) | undefined
19
+ private shownWorkspace: string | undefined
20
+
21
+ constructor(url: string, options: AppEventsClientOptions = {}) {
22
+ this.socket = new ReconnectingSocket(() => url, { baseDelayMs: options.reconnectBaseDelayMs })
23
+ this.socket.subscribe({
24
+ open: () => {
25
+ this.sendNavigationPresence()
26
+ this.emit({ type: 'app:connected' })
27
+ },
28
+ message: message => this.emit(message as ClientEvent)
29
+ })
30
+ }
31
+
32
+ connect() {
33
+ this.release ??= this.socket.start()
34
+ }
35
+
36
+ close() {
37
+ this.release?.()
38
+ this.release = undefined
39
+ }
40
+
41
+ subscribe(handler: ClientEventHandler): () => void {
42
+ this.listeners.add(handler)
43
+ return () => {
44
+ this.listeners.delete(handler)
45
+ }
46
+ }
47
+
48
+ emit(event: ClientEvent) {
49
+ for (const handler of this.listeners) handler(event)
50
+ }
51
+
52
+ send(message: object) {
53
+ this.socket.send(message)
54
+ }
55
+
56
+ // The workspace this tab shows, for the server's navigation relay. Sent now
57
+ // and again on every reconnect.
58
+ get navigationWorkspace(): string | undefined {
59
+ return this.shownWorkspace
60
+ }
61
+
62
+ setNavigationWorkspace(workspaceId: string | undefined) {
63
+ this.shownWorkspace = workspaceId
64
+ this.sendNavigationPresence()
65
+ }
66
+
67
+ sendNavigationPresence() {
68
+ this.send({
69
+ type: 'navigation:presence',
70
+ // The wire format uses `null` for "no workspace".
71
+ workspaceId: this.shownWorkspace ?? null,
72
+ focused: document.visibilityState === 'visible' && document.hasFocus()
73
+ })
74
+ }
75
+ }
@@ -0,0 +1,115 @@
1
+ export type SocketListener = {
2
+ open?: () => void
3
+ message?: (message: { type?: unknown }) => void
4
+ close?: () => void
5
+ }
6
+
7
+ export type ReconnectingSocketOptions = {
8
+ // Ping the server and drop a connection that has gone silent.
9
+ ping?: boolean
10
+ // Delay before reopening after a drop. It doubles on repeated drops, up to
11
+ // ten seconds, and resets once a socket opens.
12
+ baseDelayMs?: number
13
+ }
14
+
15
+ // The one WebSocket wrapper for the app, harness and workspace connections.
16
+ // It stays open while anything holds it and reopens on its own after a drop.
17
+ export class ReconnectingSocket {
18
+ private readonly listeners = new Set<SocketListener>()
19
+ private socket: WebSocket | undefined
20
+ private holders = 0
21
+ private attempts = 0
22
+ private lastMessageAt = 0
23
+ private retry: ReturnType<typeof setTimeout> | undefined
24
+ private heartbeat: ReturnType<typeof setInterval> | undefined
25
+
26
+ // The address is read on every connect.
27
+ constructor(
28
+ private readonly url: () => string,
29
+ private readonly options: ReconnectingSocketOptions = {}
30
+ ) {}
31
+
32
+ get isOpen(): boolean {
33
+ return this.socket?.readyState === WebSocket.OPEN
34
+ }
35
+
36
+ subscribe(listener: SocketListener): () => void {
37
+ this.listeners.add(listener)
38
+ return () => {
39
+ this.listeners.delete(listener)
40
+ }
41
+ }
42
+
43
+ start(): () => void {
44
+ let held = true
45
+ if (this.holders++ === 0) this.open()
46
+ return () => {
47
+ if (!held) return
48
+ held = false
49
+ if (--this.holders === 0) this.drop()
50
+ }
51
+ }
52
+
53
+ // Replace the connection, so the server forgets what this one had joined.
54
+ reconnect() {
55
+ this.drop()
56
+ if (this.holders) this.retry = setTimeout(() => this.open(), 0)
57
+ }
58
+
59
+ send(message: object) {
60
+ if (!this.isOpen) return
61
+ try {
62
+ this.socket?.send(JSON.stringify(message))
63
+ } catch {
64
+ this.socket?.close()
65
+ }
66
+ }
67
+
68
+ private open() {
69
+ if (this.socket || !this.holders) return
70
+ const socket = new WebSocket(this.url())
71
+ this.socket = socket
72
+ socket.onopen = () => {
73
+ if (socket !== this.socket) return
74
+ this.attempts = 0
75
+ this.lastMessageAt = Date.now()
76
+ if (this.options.ping)
77
+ this.heartbeat = setInterval(() => {
78
+ if (Date.now() - this.lastMessageAt > 45_000) socket.close()
79
+ else this.send({ type: 'ping' })
80
+ }, 15_000)
81
+ for (const listener of this.listeners) listener.open?.()
82
+ }
83
+ socket.onmessage = event => {
84
+ if (socket !== this.socket) return
85
+ this.lastMessageAt = Date.now()
86
+ let message: { type?: unknown }
87
+ try {
88
+ message = JSON.parse(String(event.data))
89
+ } catch {
90
+ return
91
+ }
92
+ for (const listener of this.listeners) listener.message?.(message)
93
+ }
94
+ socket.onerror = () => socket.close()
95
+ socket.onclose = () => {
96
+ if (socket !== this.socket) return
97
+ clearInterval(this.heartbeat)
98
+ this.socket = undefined
99
+ for (const listener of this.listeners) listener.close?.()
100
+ const maxDelay = Math.min((this.options.baseDelayMs ?? 500) * 2 ** this.attempts++, 10_000)
101
+ const delay = maxDelay * (0.5 + Math.random() * 0.5)
102
+ this.retry = setTimeout(() => this.open(), delay)
103
+ }
104
+ }
105
+
106
+ private drop() {
107
+ clearTimeout(this.retry)
108
+ clearInterval(this.heartbeat)
109
+ const socket = this.socket
110
+ if (!socket) return
111
+ this.socket = undefined
112
+ socket.close()
113
+ for (const listener of this.listeners) listener.close?.()
114
+ }
115
+ }