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,37 +1,31 @@
1
- import type { HarnessStatuses } from '@/lib/types'
2
- import { useQueryClient } from '@tanstack/react-query'
3
1
  import { type ReactNode, useEffect, useState } from 'react'
2
+ import { useQueryClient } from '@tanstack/react-query'
4
3
 
5
4
  import { wsUrl } from '@/client/lib/ws-url'
6
5
  import { AppContext, type AppContextValue } from '@/client/runtime/app-context'
7
- import { WorkspaceEventsClient } from '@/client/runtime/workspace-events'
6
+ import { AppEventsClient } from '@/client/runtime/app-events'
8
7
 
9
8
  type AppProviderProps = {
10
9
  children: ReactNode
11
10
  }
12
11
 
13
- // App-wide services, mounted once at the root (main.tsx). Opens the workspace
14
- // events socket when the app mounts and closes it when the app unmounts, so
15
- // the connection outlives every route.
12
+ // App-wide events outlive workspace routes.
16
13
  export function AppProvider({ children }: AppProviderProps) {
17
- const client = useQueryClient()
14
+ const queryClient = useQueryClient()
18
15
  const [value] = useState<AppContextValue>(() => ({
19
- events: new WorkspaceEventsClient(wsUrl('/api/workspaces/ws'))
16
+ events: new AppEventsClient(wsUrl('/api/events'))
20
17
  }))
21
18
 
22
19
  useEffect(() => {
23
20
  const unsubscribe = value.events.subscribe(event => {
24
- if (event.type === 'harness-status:changed') {
25
- const queryKey = ['harness-status']
26
- void client.cancelQueries({ queryKey })
27
- client.setQueryData<HarnessStatuses>(queryKey, previous =>
28
- previous ? { ...previous, [event.harness]: event.status } : undefined
29
- )
30
- if (!client.getQueryData(queryKey)) void client.invalidateQueries({ queryKey })
31
- if (event.status.availability.status === 'available')
32
- void client.invalidateQueries({ queryKey: ['workspaces', 'harness'] })
33
- } else if (event.type === 'connection:opened' || event.type === 'harness:updated') {
34
- void client.invalidateQueries({ queryKey: ['harness-status'] })
21
+ if (event.type === 'app:connected') {
22
+ for (const queryKey of [
23
+ ['workspaces'],
24
+ ['workspaces', 'state'],
25
+ ['workspaces', 'env'],
26
+ ['app-settings']
27
+ ])
28
+ void queryClient.invalidateQueries({ queryKey, exact: queryKey.length === 1 })
35
29
  }
36
30
  })
37
31
  value.events.connect()
@@ -39,7 +33,7 @@ export function AppProvider({ children }: AppProviderProps) {
39
33
  unsubscribe()
40
34
  value.events.close()
41
35
  }
42
- }, [value, client])
36
+ }, [value, queryClient])
43
37
 
44
38
  return <AppContext value={value}>{children}</AppContext>
45
39
  }
@@ -1,10 +1,10 @@
1
1
  import { OnboardingRoute } from './routes/onboarding-route'
2
- import { Suspense, lazy, useEffect } from 'react'
2
+ import { Suspense, lazy } from 'react'
3
3
 
4
4
  import { Redirect, Route, Switch, useLocation } from 'wouter'
5
5
 
6
6
  import { homePath } from '@/client/api/app-config'
7
- import { setWorkspaceSwitchHandler } from '@/client/features/chat/connection/chat-connection'
7
+ import { useClientEvent } from '@/client/runtime/use-client-events'
8
8
  import { useWorkspaceStateSync } from '@/client/features/workspace/workspace-state'
9
9
 
10
10
  import { SettingsRoute } from './routes/settings-route'
@@ -35,12 +35,9 @@ export function AppRouter() {
35
35
  const [, navigate] = useLocation()
36
36
  useWorkspaceStateSync()
37
37
 
38
- // When the server broadcasts a workspace:switch (e.g. from `moi start`),
39
- // navigate to that workspace
40
- useEffect(() => {
41
- setWorkspaceSwitchHandler(id => navigate(`/workspace/${id}`))
42
- return () => setWorkspaceSwitchHandler(null)
43
- }, [navigate])
38
+ useClientEvent(event => {
39
+ if (event.type === 'workspace:open-requested') navigate(`/workspace/${event.workspaceId}`)
40
+ })
44
41
 
45
42
  return (
46
43
  <Switch>
@@ -6,6 +6,8 @@ import { useWorkspaceHarnessChanges } from '@/client/features/workspace/harness-
6
6
  import { useWorkspaceTheme } from '@/client/runtime/workspace-theme'
7
7
  import { CollabProvider } from '@/client/features/collab'
8
8
  import { useQueryClient } from '@tanstack/react-query'
9
+ import type { ReactNode } from 'react'
10
+ import { useWorkspaceSocket } from '@/client/features/workspace/use-workspace-socket'
9
11
 
10
12
  import { workspaceKeys } from '@/client/api/workspace-keys'
11
13
  import { useAppConfig } from '@/client/api/app-config'
@@ -20,7 +22,7 @@ import {
20
22
  import { WorkspaceScreen } from '@/client/features/workspace/workspace-screen'
21
23
  import { useViews } from '@/client/features/views/api'
22
24
  import { useWidgets } from '@/client/features/overview/api'
23
- import { useWorkspaceScopedEvent } from '@/client/runtime/use-workspace-events'
25
+ import { useWorkspaceEvent } from '@/client/runtime/use-client-events'
24
26
  import { BROWSER_TAB_ID } from '@/client/lib/browser-tab-id'
25
27
 
26
28
  type WorkspaceRouteProps = {
@@ -30,7 +32,6 @@ type WorkspaceRouteProps = {
30
32
  // Navigation reads the raw browser address so encoded paths and query params
31
33
  // are decoded exactly once; the route only owns the workspace ID.
32
34
  export function WorkspaceRoute({ id }: WorkspaceRouteProps) {
33
- const { environment } = useAppConfig()
34
35
  const separator = id.indexOf(':')
35
36
  if (separator !== -1)
36
37
  return (
@@ -42,16 +43,32 @@ export function WorkspaceRoute({ id }: WorkspaceRouteProps) {
42
43
  return (
43
44
  <SidebarLayout>
44
45
  <Workspace id={id}>
45
- <WorkspaceLayoutProvider id={id}>
46
- <CollabProvider workspaceId={id} enabled={environment === 'cloud'}>
46
+ <WorkspaceLayoutProvider key={id} id={id}>
47
+ <WorkspaceLive id={id}>
47
48
  <WorkspaceContent id={id} />
48
- </CollabProvider>
49
+ </WorkspaceLive>
49
50
  </WorkspaceLayoutProvider>
50
51
  </Workspace>
51
52
  </SidebarLayout>
52
53
  )
53
54
  }
54
55
 
56
+ type WorkspaceLiveProps = {
57
+ id: string
58
+ children: ReactNode
59
+ }
60
+
61
+ // One owner connection carries shared updates always and presence on Cloud.
62
+ function WorkspaceLive({ id, children }: WorkspaceLiveProps) {
63
+ const { environment } = useAppConfig()
64
+ const socket = useWorkspaceSocket(id)
65
+ return (
66
+ <CollabProvider workspaceId={id} enabled={environment === 'cloud'} socket={socket}>
67
+ {children}
68
+ </CollabProvider>
69
+ )
70
+ }
71
+
55
72
  function WorkspaceContent({ id }: WorkspaceRouteProps) {
56
73
  useWorkspaceMembers(id)
57
74
  const queryClient = useQueryClient()
@@ -63,18 +80,18 @@ function WorkspaceContent({ id }: WorkspaceRouteProps) {
63
80
  const views = useViews(id)
64
81
  useAppletCacheInvalidation()
65
82
 
66
- useWorkspaceScopedEvent(id, event => {
67
- if (event.type === 'theme:updated' || event.type === 'workspace:updated') {
83
+ useWorkspaceEvent(id, event => {
84
+ if (event.type === 'workspace-config:changed') {
68
85
  // Skip our own save: the cache already holds it, and the refetch could
69
86
  // land an older value over a newer optimistic change.
70
87
  if (event.origin === BROWSER_TAB_ID) return
71
88
  queryClient.invalidateQueries({ queryKey: workspaceKeys.layout(id) })
72
- } else if (event.type === 'widget-layout:updated' || event.type === 'widget:updated') {
73
- // widget:updated too: a rebundle bumps the widget's content revision, and
89
+ } else if (event.type === 'widgets-list:changed' || event.type === 'widget:changed') {
90
+ // widget:changed too: a rebundle bumps the widget's content revision, and
74
91
  // the thumbnail invalidation hook reads it off this query.
75
92
  queryClient.invalidateQueries({ queryKey: workspaceKeys.widgets(id) })
76
- } else if (event.type === 'view:updated') {
77
- // view:updated also bumps the built bundle revision used by thumbnail
93
+ } else if (event.type === 'view:changed') {
94
+ // view:changed also bumps the built bundle revision used by thumbnail
78
95
  // freshness checks.
79
96
  queryClient.invalidateQueries({ queryKey: workspaceKeys.views(id) })
80
97
  }
@@ -16,7 +16,7 @@ import {
16
16
  useUpdateControl
17
17
  } from '@/client/features/update/update-control'
18
18
  import { workspaceKeys } from '@/client/api/workspace-keys'
19
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
19
+ import { useClientEvent } from '@/client/runtime/use-client-events'
20
20
  import { CreateWorkspaceDialog } from '@/client/features/workspace/add/create-workspace-dialog'
21
21
  import { useAccount } from '@/client/features/account/account-provider'
22
22
  import { AccountMenu } from '@/client/features/account/account-menu'
@@ -61,15 +61,10 @@ export function SidebarLayout({ children, showWorkspaces = true }: SidebarLayout
61
61
  // prefix of every workspace query — a prefix invalidation would refetch
62
62
  // transcripts, widgets, and MCP probes in every connected client.
63
63
  const qc = useQueryClient()
64
- useWorkspaceEvent(e => {
65
- if (
66
- e.type === 'workspace:updated' ||
67
- e.type === 'theme:updated' ||
68
- e.type === 'workspaces-list:updated'
69
- ) {
70
- // Our own icon and order changes are already in the list cache. Own theme
71
- // saves still refetch: only the layout cache holds those optimistically.
72
- if (e.type !== 'theme:updated' && e.origin === BROWSER_TAB_ID) return
64
+ useClientEvent(e => {
65
+ if (e.type === 'workspace-config:changed' || e.type === 'workspaces-list:changed') {
66
+ // Shared config saves update the layout cache; the sidebar list still needs a refetch.
67
+ if (e.type !== 'workspace-config:changed' && e.origin === BROWSER_TAB_ID) return
73
68
  qc.invalidateQueries({ queryKey: workspaceKeys.all, exact: true })
74
69
  }
75
70
  })
@@ -1,6 +1,6 @@
1
1
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
2
2
  import { jsonRequest, requestJson } from '@/client/api/http'
3
- import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
3
+ import { useClientEvent } from '@/client/runtime/use-client-events'
4
4
  import type { AppSettings } from '@/lib/types'
5
5
 
6
6
  export const appSettingsKey = ['app-settings'] as const
@@ -9,8 +9,8 @@ export function useAppSettings() {
9
9
  const queryClient = useQueryClient()
10
10
  // Another client can change settings; the server broadcasts the new value
11
11
  // over the live-events socket so every open client stays in sync.
12
- useWorkspaceEvent(event => {
13
- if (event.type === 'settings:updated') {
12
+ useClientEvent(event => {
13
+ if (event.type === 'app-settings:changed') {
14
14
  queryClient.setQueryData<AppSettings>(appSettingsKey, event.settings)
15
15
  }
16
16
  })
@@ -80,8 +80,7 @@ export function invalidateApplet(segment: AppletSegment, workspaceId: string, na
80
80
  disposeAppletBridge(key)
81
81
  }
82
82
 
83
- // Invalidate every applet of one kind in this workspace — the
84
- // `applets:refresh` path, which names no specific applet. Only keys that have
83
+ // Invalidate every applet of one kind in this workspace. Only keys that have
85
84
  // ever been loaded (or bumped) exist in the maps; anything else already loads
86
85
  // fresh on first mount.
87
86
  export function invalidateAppletSegment(segment: AppletSegment, workspaceId?: string): void {
@@ -18,7 +18,7 @@ import {
18
18
  import { attachAppletBridge } from '@/client/features/applets/applet-runtime'
19
19
  import { reportAppletError } from '@/client/features/applets/applet-log'
20
20
  import { useWorkspaceId } from '@/client/features/workspace/workspace-context'
21
- import { type WorkspaceEvent, useWorkspaceScopedEvent } from '@/client/runtime/use-workspace-events'
21
+ import { type ClientEvent, useWorkspaceEvent } from '@/client/runtime/use-client-events'
22
22
  import type { AppletKind } from '@/lib/types'
23
23
 
24
24
  // Views receive URL query params. Widgets mount without params; applets must
@@ -40,23 +40,23 @@ type AppletKindSpec = {
40
40
  kind: AppletKind
41
41
  segment: AppletSegment
42
42
  // True when this MEI event means the named applet should cache-bust + reload.
43
- shouldReload: (event: WorkspaceEvent, name: string) => boolean
43
+ shouldReload: (event: ClientEvent, name: string) => boolean
44
44
  }
45
45
 
46
46
  const WIDGET_KIND: AppletKindSpec = {
47
47
  kind: 'widget',
48
48
  segment: 'widgets',
49
49
  shouldReload: (e, name) =>
50
- (e.type === 'widget:updated' && e.name === name) ||
51
- (e.type === 'applets:refresh' && e.only !== 'views')
50
+ (e.type === 'widget:changed' && e.name === name) ||
51
+ (e.type === 'applets:refresh' && e.only !== 'views' && (!e.name || e.name === name))
52
52
  }
53
53
 
54
54
  const VIEW_KIND: AppletKindSpec = {
55
55
  kind: 'view',
56
56
  segment: 'views',
57
57
  shouldReload: (e, name) =>
58
- (e.type === 'view:updated' && e.name === name) ||
59
- (e.type === 'applets:refresh' && e.only !== 'widgets')
58
+ (e.type === 'view:changed' && e.name === name) ||
59
+ (e.type === 'applets:refresh' && e.only !== 'widgets' && (!e.name || e.name === name))
60
60
  }
61
61
 
62
62
  function loadApplet(
@@ -143,16 +143,14 @@ function useApplet(kind: AppletKindSpec, name: string, revision?: string): Apple
143
143
  // unmounted case, but doing it here keeps this self-sufficient and
144
144
  // order-independent. The bumped version remounts the component and re-runs its
145
145
  // `rpc()` calls.
146
- useWorkspaceScopedEvent(workspaceId, event => {
146
+ useWorkspaceEvent(workspaceId, event => {
147
147
  if (kind.shouldReload(event, name)) {
148
148
  invalidateApplet(kind.segment, workspaceId, name)
149
149
  load()
150
150
  }
151
151
  })
152
152
 
153
- // Owner events don't reach visitors yet. The applet lists refetch on window
154
- // focus and carry each bundle's revision, so a remote applet reloads only when
155
- // its build changed: a reload remounts it and keeps the old module in memory.
153
+ // Revisions catch rebuilds missed while the owner's socket was disconnected.
156
154
  const remote = isRemoteWorkspace(workspaceId)
157
155
  const seen = useRef({ key, revision })
158
156
  useEffect(() => {
@@ -183,14 +181,13 @@ export function useView(name: string, revision?: string): AppletState {
183
181
  export function useAppletCacheInvalidation(): void {
184
182
  const workspaceId = useWorkspaceId()
185
183
  const queryClient = useQueryClient()
186
- useWorkspaceScopedEvent(workspaceId, event => {
187
- // Owner build events don't reach visitors. `moi refresh` from the visitor's
188
- // agent does, so it also re-reads the owner's lists for new or removed applets.
184
+ useWorkspaceEvent(workspaceId, event => {
185
+ // Refresh the owner lists too, so new or removed applets become visible.
189
186
  if (
190
187
  isRemoteWorkspace(workspaceId, queryClient) &&
191
188
  (event.type === 'applets:refresh' ||
192
- event.type === 'view:updated' ||
193
- event.type === 'widget:updated')
189
+ event.type === 'view:changed' ||
190
+ event.type === 'widget:changed')
194
191
  ) {
195
192
  void queryClient.invalidateQueries({
196
193
  queryKey: workspaceKeys.views(workspaceId)
@@ -199,12 +196,13 @@ export function useAppletCacheInvalidation(): void {
199
196
  queryKey: workspaceKeys.widgets(workspaceId)
200
197
  })
201
198
  }
202
- if (event.type === 'view:updated') invalidateApplet('views', workspaceId, event.name)
203
- else if (event.type === 'widget:updated') invalidateApplet('widgets', workspaceId, event.name)
199
+ if (event.type === 'view:changed') invalidateApplet('views', workspaceId, event.name)
200
+ else if (event.type === 'widget:changed') invalidateApplet('widgets', workspaceId, event.name)
204
201
  else if (event.type === 'applets:refresh') {
205
- // Segment-wide: `moi refresh` names no applet, so every cached module in
206
- // the targeted kind(s) is stale — including ones whose tabs are
207
- // backgrounded right now.
202
+ if (event.only && event.name) {
203
+ invalidateApplet(event.only, workspaceId, event.name)
204
+ return
205
+ }
208
206
  if (event.only !== 'views') invalidateAppletSegment('widgets', event.workspaceId)
209
207
  if (event.only !== 'widgets') invalidateAppletSegment('views', event.workspaceId)
210
208
  }
@@ -91,7 +91,7 @@ export type LiveStore = {
91
91
  attachments: Record<string, StagedAttachment[]>
92
92
 
93
93
  setActivity: (workspaceId: string, sessionId: string, value: SessionActivity) => void
94
- // Authoritative reconcile from a server `status_snapshot`: exactly the listed
94
+ // Authoritative reconcile from a server `sessions:status-snapshot`: exactly the listed
95
95
  // sessions are active; everything else is cleared to idle (fixes a spinner
96
96
  // whose terminal status frame was lost while we were disconnected).
97
97
  reconcileActivity: (
@@ -1,6 +1,7 @@
1
1
  import type { QueryClient } from '@tanstack/react-query'
2
2
 
3
3
  import { wsUrl } from '@/client/lib/ws-url'
4
+ import { ReconnectingSocket } from '@/client/runtime/reconnecting-socket'
4
5
  import { liveStore } from '@/client/features/chat/chat-store'
5
6
  import { reduceChatFrame } from '@/client/features/chat/connection/chat-frames'
6
7
  import type { ClientMessage } from '@/lib/types'
@@ -10,97 +11,53 @@ import type { ClientMessage } from '@/lib/types'
10
11
  // `workspaceId`, so a single socket serves every workspace and the client routes
11
12
  // each frame to the right `(workspaceId, sessionId)` slice — live transcript
12
13
  // deltas into the React Query cache, status/error/rename into the live store.
13
- //
14
- // Socket identity is tracked by a monotonic `generation`: each socket captures
15
- // the generation at creation and every callback bails if it's no longer current,
16
- // so a delayed close/open from a superseded socket can't corrupt live state.
17
14
 
18
15
  let qc: QueryClient | null = null
19
- let socket: WebSocket | null = null
20
- let generation = 0
21
- let reconnectTimer: ReturnType<typeof setTimeout> | null = null
16
+ let started = false
17
+ // Messages sent while disconnected, delivered on the next open.
22
18
  const queue: ClientMessage[] = []
23
- let onWorkspaceSwitch: ((workspaceId: string) => void) | null = null
24
- let sweepTimer: ReturnType<typeof setInterval> | null = null
25
19
 
26
- // TTL backstop for live previews. Every clear path (turn arrival, run end,
27
- // reconnect) is exact and should fire first; this only reaps a preview whose
28
- // clear was somehow missed, so it can be generous.
29
- const PREVIEW_TTL_MS = 15_000
30
-
31
- export function initConnection(queryClient: QueryClient) {
32
- qc = queryClient
33
- if (!sweepTimer) {
34
- sweepTimer = setInterval(
35
- () => liveStore.getState().sweepPreviews(PREVIEW_TTL_MS, Date.now()),
36
- 5_000
37
- )
38
- }
39
- if (socket) return // already connected (mount/StrictMode re-invoke safety)
40
- connect()
41
- }
42
-
43
- function connect() {
44
- const myGen = ++generation
45
- if (reconnectTimer) {
46
- clearTimeout(reconnectTimer)
47
- reconnectTimer = null
48
- }
49
-
50
- const s = new WebSocket(wsUrl('/ws'))
51
- socket = s
52
-
53
- s.onopen = () => {
54
- if (generation !== myGen) {
55
- s.close()
56
- return
57
- }
58
- for (const m of queue) s.send(JSON.stringify(m))
59
- queue.length = 0
20
+ const socket = new ReconnectingSocket(() => wsUrl('/api/harness/events'))
21
+ socket.subscribe({
22
+ open: () => {
23
+ for (const message of queue.splice(0)) socket.send(message)
60
24
  // Heal any deltas missed while disconnected: refetch every live transcript.
61
25
  // No-op on the first connect (nothing cached yet).
62
26
  qc?.invalidateQueries({ queryKey: ['workspaces', 'events'] })
27
+ qc?.invalidateQueries({ queryKey: ['harness-status'] })
28
+ qc?.invalidateQueries({ queryKey: ['workspaces', 'harness'] })
63
29
  // Any in-flight preview from before the drop is superseded by that refetch
64
30
  // (which returns the authoritative disk state) — drop them all so a frozen
65
31
  // half-streamed preview can't linger over the healed transcript.
66
32
  liveStore.getState().clearAllPreviews()
67
- }
68
-
69
- s.onmessage = e => {
70
- if (generation !== myGen) return
71
- let data: unknown
72
- try {
73
- data = JSON.parse(e.data)
74
- } catch {
75
- return
76
- }
77
- handleFrame(data as Record<string, unknown>)
78
- }
33
+ },
34
+ message: message => handleFrame(message as Record<string, unknown>)
35
+ })
79
36
 
80
- s.onclose = () => {
81
- if (generation !== myGen) return
82
- socket = null
83
- reconnectTimer = setTimeout(connect, 1000)
84
- }
37
+ // TTL backstop for live previews. Every clear path (turn arrival, run end,
38
+ // reconnect) is exact and should fire first; this only reaps a preview whose
39
+ // clear was somehow missed, so it can be generous.
40
+ const PREVIEW_TTL_MS = 15_000
85
41
 
86
- s.onerror = () => s.close()
42
+ export function initConnection(queryClient: QueryClient) {
43
+ qc = queryClient
44
+ if (started) return // mount/StrictMode re-invoke safety
45
+ started = true
46
+ setInterval(() => liveStore.getState().sweepPreviews(PREVIEW_TTL_MS, Date.now()), 5_000)
47
+ socket.start()
87
48
  }
88
49
 
89
50
  export function handleFrame(data: Record<string, unknown>) {
90
- reduceChatFrame(data, { queryClient: qc, sendMessage, onWorkspaceSwitch })
51
+ reduceChatFrame(data, { queryClient: qc })
91
52
  }
92
53
 
93
54
  export function sendMessage(msg: ClientMessage) {
94
- if (socket && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(msg))
55
+ if (socket.isOpen) socket.send(msg)
95
56
  else queue.push(msg)
96
57
  }
97
58
 
98
- export function setWorkspaceSwitchHandler(fn: ((workspaceId: string) => void) | null) {
99
- onWorkspaceSwitch = fn
100
- }
101
-
102
59
  // Test seam: inject the QueryClient the frame handler reads, without opening a
103
- // socket (the browser-only `connect()` path). Production always goes through
60
+ // socket. Production always goes through
104
61
  // `initConnection`.
105
62
  export function __setQueryClientForTests(client: QueryClient | null) {
106
63
  qc = client
@@ -1,16 +1,15 @@
1
+ import type { ClientEvent } from '@/lib/events'
2
+ import { receiveWorkspaceHarness } from '@/client/features/workspace/harness-transition'
1
3
  import type { QueryClient } from '@tanstack/react-query'
2
4
 
3
5
  import { workspaceKeys } from '@/client/api/workspace-keys'
4
- import { getScratchExecutor } from '@/client/features/scratchpad/scratch-executor'
5
6
  import { liveStore } from '@/client/features/chat/chat-store'
6
7
  import { bufferSessionEvent } from '@/client/features/chat/sessions/session-view'
7
8
  import { renameSelectedSessionInCache } from '@/client/features/chat/sessions/use-selected-session'
8
9
  import { applyArchivedSession } from '@/client/features/chat/sessions/api'
9
10
  import { applyEvent } from '@/lib/format'
10
11
  import type {
11
- ClientMessage,
12
12
  PreviewFrame,
13
- ScratchOp,
14
13
  SessionActivity,
15
14
  SessionSummary,
16
15
  StreamEvent,
@@ -19,15 +18,24 @@ import type {
19
18
 
20
19
  type ChatFrameContext = {
21
20
  queryClient: QueryClient | null
22
- sendMessage: (message: ClientMessage) => void
23
- onWorkspaceSwitch: ((workspaceId: string) => void) | null
24
21
  }
25
22
 
26
23
  export function reduceChatFrame(data: Record<string, unknown>, context: ChatFrameContext) {
27
- const { queryClient, sendMessage, onWorkspaceSwitch } = context
24
+ const { queryClient } = context
28
25
  const store = liveStore.getState()
29
26
 
30
- if (data.type === 'status_snapshot') {
27
+ if (data.type === 'harness:changed') {
28
+ void queryClient?.invalidateQueries({ queryKey: ['harness-status'] })
29
+ void queryClient?.invalidateQueries({ queryKey: ['workspaces', 'harness'] })
30
+ return
31
+ }
32
+ if (data.type === 'workspace-harness:switched') {
33
+ const event = data as Extract<ClientEvent, { type: 'workspace-harness:switched' }>
34
+ if (queryClient) void receiveWorkspaceHarness(queryClient, event.workspaceId, event.harness)
35
+ return
36
+ }
37
+
38
+ if (data.type === 'sessions:status-snapshot') {
31
39
  store.reconcileActivity(
32
40
  (data.sessions as
33
41
  | { workspaceId: string; sessionId: string; activity: SessionActivity }[]
@@ -35,7 +43,7 @@ export function reduceChatFrame(data: Record<string, unknown>, context: ChatFram
35
43
  )
36
44
  return
37
45
  }
38
- if (data.type === 'status') {
46
+ if (data.type === 'session:status') {
39
47
  const workspaceId = data.workspaceId as string
40
48
  const sessionId = data.sessionId as string
41
49
  const activity = data.activity as SessionActivity
@@ -43,7 +51,7 @@ export function reduceChatFrame(data: Record<string, unknown>, context: ChatFram
43
51
  if (activity !== 'running') store.clearPreviewsForSession(workspaceId, sessionId)
44
52
  return
45
53
  }
46
- if (data.type === 'preview') {
54
+ if (data.type === 'session:preview') {
47
55
  const frame = data as unknown as PreviewFrame
48
56
  const key = workspaceKeys.events(frame.workspaceId, frame.sessionId)
49
57
  if (queryClient?.getQueryData(key) === undefined) return
@@ -56,7 +64,7 @@ export function reduceChatFrame(data: Record<string, unknown>, context: ChatFram
56
64
  })
57
65
  return
58
66
  }
59
- if (data.type === 'session_renamed') {
67
+ if (data.type === 'session:renamed') {
60
68
  const workspaceId = data.workspaceId as string
61
69
  const from = data.from as string
62
70
  const to = data.to as string
@@ -94,35 +102,15 @@ export function reduceChatFrame(data: Record<string, unknown>, context: ChatFram
94
102
  queryClient?.invalidateQueries({ queryKey: workspaceKeys.previews })
95
103
  return
96
104
  }
97
- if (data.type === 'sessions_changed' || data.type === 'session_archived') {
105
+ if (data.type === 'sessions:changed' || data.type === 'session:archived') {
98
106
  const workspaceId = data.workspaceId as string
99
- if (queryClient && data.type === 'session_archived' && typeof data.sessionId === 'string')
107
+ if (queryClient && data.type === 'session:archived' && typeof data.sessionId === 'string')
100
108
  applyArchivedSession(queryClient, workspaceId, data.sessionId)
101
109
  const sessionsKey = workspaceKeys.sessions(workspaceId)
102
110
  queryClient?.invalidateQueries({ queryKey: sessionsKey })
103
111
  queryClient?.invalidateQueries({ queryKey: workspaceKeys.previews })
104
112
  return
105
113
  }
106
- if (data.type === 'workspace:switch') {
107
- onWorkspaceSwitch?.(data.workspaceId as string)
108
- return
109
- }
110
- if (data.type === 'scratchpad:op') {
111
- const run = getScratchExecutor(data.workspaceId as string)
112
- if (!run) return
113
- const opId = data.opId as string
114
- run(data.op as ScratchOp).then(
115
- result => sendMessage({ type: 'scratchpad:op-result', opId, result }),
116
- error =>
117
- sendMessage({
118
- type: 'scratchpad:op-result',
119
- opId,
120
- error: error instanceof Error ? error.message : String(error)
121
- })
122
- )
123
- return
124
- }
125
-
126
114
  const workspaceId = data.workspaceId as string | undefined
127
115
  const sessionId = data.sessionId as string | undefined
128
116
  if (!workspaceId || !sessionId) return
@@ -25,7 +25,7 @@ import type {
25
25
  } from '@/lib/types'
26
26
 
27
27
  // The agent's chat list. Reading it makes the harness scan transcripts, so
28
- // mounts within 30 s reuse it; harness `sessions_changed` frames refetch it,
28
+ // mounts within 30 s reuse it; harness `sessions:changed` frames refetch it,
29
29
  // and focus picks up chats made outside Moi.
30
30
  export function workspaceSessionsOptions(workspaceId: string) {
31
31
  return {
@@ -113,7 +113,7 @@ export function removeArchivedSession<T extends SessionSummary>(
113
113
  }
114
114
 
115
115
  // Drop an archived chat everywhere this browser keeps it. The server's state
116
- // arrives with the archive reply or a `state:changed` event.
116
+ // arrives with the archive reply or a `personal-state:changed` event.
117
117
  export function applyArchivedSession(
118
118
  queryClient: QueryClient,
119
119
  workspaceId: string,
@@ -70,19 +70,6 @@ function selectionChange(
70
70
  return { sessionId, tabId, show: true, ifMatch: current }
71
71
  }
72
72
 
73
- // Show a chat in a tab before the server confirms it, without a request: for
74
- // flows whose own request makes the server select it (view submission).
75
- export function setSelectedSessionInCache(
76
- queryClient: QueryClient,
77
- workspaceId: string,
78
- sessionId: string,
79
- tabId: WorkspaceTabId
80
- ): void {
81
- changeWorkspaceStateCache(queryClient, workspaceId, draft => {
82
- draft.selected[tabId] = sessionId
83
- })
84
- }
85
-
86
73
  // A harness replaced a temporary chat id with its real one.
87
74
  export function renameSelectedSessionInCache(
88
75
  queryClient: QueryClient,