moi-computer 0.11.1-next.5 → 0.12.1-next.0

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 (141) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/app-ui-keys.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -3
  5. package/client/app/routes/WorkspaceRoute.tsx +2 -8
  6. package/client/features/applets/applet-runtime.ts +11 -13
  7. package/client/features/chat/ChatPanel.tsx +70 -49
  8. package/client/features/chat/ChatPopup.tsx +81 -8
  9. package/client/features/chat/applet-chat-intents.ts +31 -12
  10. package/client/features/chat/chat-send.ts +33 -1
  11. package/client/features/chat/chat-store.ts +10 -0
  12. package/client/features/chat/composer/ChatComposer.tsx +24 -27
  13. package/client/features/chat/composer/ModelPicker.tsx +3 -3
  14. package/client/features/chat/composer/attachments/draft-attachments.ts +21 -4
  15. package/client/features/chat/composer/useWorkspaceComposerState.tsx +3 -3
  16. package/client/features/chat/connection/chat-frames.ts +14 -7
  17. package/client/features/chat/messages/ChatEmptyState.tsx +33 -19
  18. package/client/features/chat/messages/MarkdownContent.tsx +3 -3
  19. package/client/features/chat/messages/fork-history.ts +14 -0
  20. package/client/features/chat/sessions/ChatSelector.tsx +138 -79
  21. package/client/features/chat/sessions/api.ts +109 -19
  22. package/client/features/chat/sessions/browser-tab-state.ts +30 -7
  23. package/client/features/chat/sessions/useSelectedSession.ts +217 -51
  24. package/client/features/chat/useChat.ts +43 -45
  25. package/client/features/collab/client.ts +10 -11
  26. package/client/features/collab/hooks.tsx +6 -11
  27. package/client/features/collab/host-state.ts +57 -128
  28. package/client/features/collab/provider.tsx +3 -3
  29. package/client/features/collab/testing/fake-engine.ts +6 -27
  30. package/client/features/collab/workspace-users-menu.tsx +3 -7
  31. package/client/features/drawings/{useViewBuilderSketch.ts → useViewSketch.ts} +7 -7
  32. package/client/features/home/HomePage.tsx +2 -2
  33. package/client/features/overview/Overview.tsx +3 -6
  34. package/client/features/overview/default/ViewsWidget.tsx +5 -12
  35. package/client/features/overview/default/registry.tsx +2 -4
  36. package/client/features/views/PendingViewScreen.tsx +279 -0
  37. package/client/features/views/ViewManager.tsx +10 -10
  38. package/client/features/views/api.ts +63 -130
  39. package/client/features/views/useViewActions.ts +151 -0
  40. package/client/features/views/useViewDrafts.ts +79 -0
  41. package/client/features/views/view-presentation.ts +4 -5
  42. package/client/features/views/view-submission.ts +88 -0
  43. package/client/features/workspace/WorkspaceMenu.tsx +63 -0
  44. package/client/features/workspace/WorkspaceScreen.tsx +180 -375
  45. package/client/features/workspace/browser-tab-state.ts +16 -9
  46. package/client/features/workspace/moi-context.ts +13 -15
  47. package/client/features/workspace/tab-resolution.ts +16 -29
  48. package/client/features/workspace/useWorkspaceNavigation.ts +146 -104
  49. package/client/index.tsx +5 -1
  50. package/client/runtime/useWorkspaceEvents.ts +7 -6
  51. package/client/store/ui.ts +25 -29
  52. package/dist/chunk-1zhnhy00.js +1 -0
  53. package/dist/chunk-27501vke.js +1 -0
  54. package/dist/{chunk-jf6czgrz.js → chunk-9xtv6djt.js} +2 -2
  55. package/dist/chunk-am1x230f.js +2 -0
  56. package/dist/{chunk-nez8sdta.js → chunk-darpsw65.js} +1 -1
  57. package/dist/{chunk-97eg9mjn.js → chunk-gps4qc38.js} +1 -1
  58. package/dist/{chunk-3a48fyf7.js → chunk-hzwr8dp8.js} +4 -4
  59. package/dist/{chunk-efdyz6xp.js → chunk-j905va8r.js} +1 -1
  60. package/dist/chunk-n33w9y38.js +10 -0
  61. package/dist/chunk-r63ks44z.js +68 -0
  62. package/dist/{chunk-vfpsc75k.js → chunk-vqpkqtdr.js} +1 -1
  63. package/dist/chunk-wd46nk26.css +1 -0
  64. package/dist/chunk-xgt7vxt9.js +1 -0
  65. package/dist/{chunk-z3byfve5.js → chunk-yvzhwtfa.js} +2 -2
  66. package/dist/index.html +1 -1
  67. package/lib/ids.ts +2 -5
  68. package/lib/moi-context.ts +100 -73
  69. package/lib/navigation.ts +48 -87
  70. package/lib/session-drafts.ts +10 -0
  71. package/lib/types.ts +64 -31
  72. package/lib/view-build-directives.ts +12 -0
  73. package/lib/workspace-layout.ts +1 -1
  74. package/lib/workspace-tabs.ts +12 -7
  75. package/package.json +3 -1
  76. package/server/agent-launcher.ts +27 -0
  77. package/server/api.ts +119 -209
  78. package/server/app-config.ts +21 -2
  79. package/server/applets/build-worker.ts +2 -1
  80. package/server/applets/view-source.ts +7 -1
  81. package/server/cli-env.ts +72 -50
  82. package/server/cli.ts +127 -70
  83. package/server/control.ts +82 -63
  84. package/server/data-dir.ts +13 -0
  85. package/server/functions.ts +2 -1
  86. package/server/harness/README.md +8 -0
  87. package/server/harness/acp/adapter.ts +2 -2
  88. package/server/harness/acp/client.ts +2 -1
  89. package/server/harness/acp/discovery.ts +3 -3
  90. package/server/harness/acp/session.ts +6 -9
  91. package/server/harness/claude-code/adapter.ts +13 -8
  92. package/server/harness/claude-code/auth.ts +3 -2
  93. package/server/harness/claude-code/cli.ts +3 -1
  94. package/server/harness/claude-code/git-worktree.ts +5 -2
  95. package/server/harness/claude-code/index.ts +5 -0
  96. package/server/harness/claude-code/mcp.ts +2 -0
  97. package/server/harness/claude-code/models.ts +2 -0
  98. package/server/harness/claude-code/session.ts +5 -34
  99. package/server/harness/claude-code/sessions.ts +8 -12
  100. package/server/harness/codex/NOTES.md +23 -4
  101. package/server/harness/codex/adapter.ts +5 -3
  102. package/server/harness/codex/client.ts +13 -21
  103. package/server/harness/codex/index.ts +18 -0
  104. package/server/harness/codex/session.ts +6 -14
  105. package/server/harness/codex/thread-list.ts +74 -0
  106. package/server/harness/fork.ts +12 -0
  107. package/server/harness/openclaw/adapter.ts +3 -3
  108. package/server/harness/openclaw/session.ts +2 -30
  109. package/server/harness/session-title.ts +12 -3
  110. package/server/harness/types.ts +8 -3
  111. package/server/moi-scaffold.ts +53 -20
  112. package/server/pending-views.ts +164 -0
  113. package/server/registry.ts +14 -4
  114. package/server/selected-session.ts +91 -44
  115. package/server/service.ts +16 -2
  116. package/server/session-archive.ts +32 -0
  117. package/server/session-config.ts +16 -111
  118. package/server/session-lifecycle.ts +17 -0
  119. package/server/session-store.ts +127 -0
  120. package/server/status.ts +3 -1
  121. package/server/tabs.ts +7 -10
  122. package/server/view-sessions.ts +267 -0
  123. package/server/views.ts +30 -41
  124. package/server/web.ts +47 -45
  125. package/server/workspace-env.ts +27 -0
  126. package/server/workspace-init.ts +12 -5
  127. package/workspace/.claude/skills/moi-workspace/SKILL.md +49 -20
  128. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +2 -5
  129. package/client/features/views/ViewBuilder.tsx +0 -239
  130. package/client/features/views/useViewBuilderActions.ts +0 -103
  131. package/client/features/views/useViewBuilderDrafts.ts +0 -68
  132. package/dist/chunk-2jncyq65.js +0 -1
  133. package/dist/chunk-9zpvdws4.js +0 -68
  134. package/dist/chunk-h2kj1ysj.js +0 -1
  135. package/dist/chunk-hvj7tp3y.js +0 -1
  136. package/dist/chunk-nzwgm8vc.css +0 -1
  137. package/dist/chunk-ryg9z3kn.js +0 -10
  138. package/dist/chunk-tpn177bt.js +0 -2
  139. package/lib/view-builder-directives.ts +0 -16
  140. package/server/chat-selection.ts +0 -22
  141. package/server/view-builders.ts +0 -453
@@ -4,6 +4,11 @@ import {
4
4
  writeSelectedSession
5
5
  } from '@/client/features/chat/sessions/browser-tab-state'
6
6
  import { useCallback, useMemo } from 'react'
7
+ import { useParams } from 'wouter'
8
+ import { isWorkspaceTabId } from '@/lib/workspace-tabs'
9
+ import type { WorkspaceSessionSelection, WorkspaceTabId } from '@/lib/types'
10
+ import { composerDraftKey } from '@/lib/session-drafts'
11
+ import { useUiStore } from '@/client/store/ui'
7
12
 
8
13
  import { useIsMutating, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
9
14
  import type { QueryClient } from '@tanstack/react-query'
@@ -18,22 +23,42 @@ import type { SelectedSessionScope, SelectedSessionState } from '@/lib/types'
18
23
  type SaveSelectedSessionInput = {
19
24
  sessionId: string | null
20
25
  previousSessionId: string | null
26
+ tabId: WorkspaceTabId
27
+ scope: SelectedSessionScope
21
28
  }
22
29
 
23
30
  type SetSelectedSession = (sessionId: string | null) => void
24
31
 
25
32
  type SelectedSessionResult = readonly [
26
33
  sessionId: string | null | undefined,
27
- setSessionId: SetSelectedSession
34
+ setSessionId: SetSelectedSession,
35
+ selectSessionForTab: (sessionId: string, tabId: WorkspaceTabId) => Promise<void>
28
36
  ]
29
37
 
30
38
  export type SelectedSessionSaveResult = 'applied' | 'conflict' | 'ignored'
31
39
 
32
40
  export function selectedSessionKey(workspaceId: string, scope: SelectedSessionScope = 'shared') {
33
- const key = appUiKeys.selectedSession(workspaceId)
41
+ const key = appUiKeys.sessionSelection(workspaceId)
34
42
  return scope === 'browser-tab' ? ([...key, 'browser-tab'] as const) : key
35
43
  }
36
44
 
45
+ export function selectedSessionOptions(
46
+ workspaceId: string,
47
+ scope: SelectedSessionScope = 'shared'
48
+ ) {
49
+ return {
50
+ queryKey: selectedSessionKey(workspaceId, scope),
51
+ queryFn: () =>
52
+ scope === 'browser-tab'
53
+ ? Promise.resolve(readSelectedSession(workspaceId))
54
+ : requestJson<WorkspaceSessionSelection>(`/api/workspaces/${workspaceId}/selected-session`),
55
+ staleTime: Infinity,
56
+ gcTime: 0,
57
+ refetchOnMount: false,
58
+ refetchOnWindowFocus: false
59
+ }
60
+ }
61
+
37
62
  function selectedSessionMutationKey(workspaceId: string, scope: SelectedSessionScope) {
38
63
  return [...selectedSessionKey(workspaceId, scope), 'save'] as const
39
64
  }
@@ -42,47 +67,66 @@ export function optimisticallySetSelectedSession(
42
67
  queryClient: QueryClient,
43
68
  workspaceId: string,
44
69
  sessionId: string | null,
70
+ tabId: WorkspaceTabId,
45
71
  scope: SelectedSessionScope = 'shared'
46
72
  ): SaveSelectedSessionInput | null {
47
73
  const queryKey = selectedSessionKey(workspaceId, scope)
48
- const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
49
- const previousSessionId = current?.sessionId ?? null
50
- if (current && previousSessionId === sessionId) return null
74
+ const current = queryClient.getQueryData<WorkspaceSessionSelection>(queryKey)
75
+ const previousSessionId = current?.selected[tabId] ?? null
76
+ if (
77
+ current &&
78
+ previousSessionId === sessionId &&
79
+ (scope === 'shared' || tabId in current.selected)
80
+ )
81
+ return null
51
82
 
52
- queryClient.setQueryData<SelectedSessionState>(queryKey, { sessionId })
53
- return { sessionId, previousSessionId }
83
+ const selected = { ...current?.selected }
84
+ if (sessionId === null && scope === 'shared') delete selected[tabId]
85
+ else selected[tabId] = sessionId
86
+ queryClient.setQueryData<WorkspaceSessionSelection>(queryKey, {
87
+ selected,
88
+ pinned: current?.pinned ?? null
89
+ })
90
+ if (scope === 'browser-tab') writeSelectedSession(workspaceId, { selected, pinned: null })
91
+ return { sessionId, previousSessionId, tabId, scope }
54
92
  }
55
93
 
56
94
  export function settleSelectedSessionSave(
57
95
  queryClient: QueryClient,
58
96
  workspaceId: string,
59
97
  saved: SelectedSessionState,
60
- input: SaveSelectedSessionInput,
61
- scope: SelectedSessionScope = 'shared'
98
+ input: SaveSelectedSessionInput
62
99
  ): SelectedSessionSaveResult {
63
- const queryKey = selectedSessionKey(workspaceId, scope)
64
- const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
100
+ const queryKey = selectedSessionKey(workspaceId, input.scope)
101
+ const current = queryClient.getQueryData<WorkspaceSessionSelection>(queryKey)
65
102
 
66
- if (saved.sessionId !== input.sessionId && current?.sessionId !== saved.sessionId) {
103
+ const currentSessionId = current?.selected[input.tabId] ?? null
104
+ if (saved.sessionId !== input.sessionId && currentSessionId !== saved.sessionId) {
67
105
  return 'conflict'
68
106
  }
69
- if (current?.sessionId !== input.sessionId && current?.sessionId !== input.previousSessionId) {
107
+ if (currentSessionId !== input.sessionId && currentSessionId !== input.previousSessionId) {
70
108
  return 'ignored'
71
109
  }
72
110
 
73
- queryClient.setQueryData<SelectedSessionState>(queryKey, saved)
111
+ const selected = { ...current?.selected }
112
+ if (saved.sessionId === null && input.scope === 'shared') delete selected[input.tabId]
113
+ else selected[input.tabId] = saved.sessionId
114
+ queryClient.setQueryData<WorkspaceSessionSelection>(queryKey, {
115
+ selected,
116
+ pinned: current?.pinned ?? null
117
+ })
74
118
  return 'applied'
75
119
  }
76
120
 
77
121
  export function applySelectedSessionEvent(
78
122
  queryClient: QueryClient,
79
123
  workspaceId: string,
80
- sessionId: string | null,
81
124
  hasPendingSave: boolean
82
125
  ): void {
83
126
  if (hasPendingSave) return
84
- queryClient.setQueryData<SelectedSessionState>(appUiKeys.selectedSession(workspaceId), {
85
- sessionId
127
+ void queryClient.invalidateQueries({
128
+ queryKey: appUiKeys.sessionSelection(workspaceId),
129
+ exact: true
86
130
  })
87
131
  }
88
132
 
@@ -92,16 +136,54 @@ export function renameSelectedSessionInCache(
92
136
  from: string,
93
137
  to: string
94
138
  ): void {
139
+ useUiStore
140
+ .getState()
141
+ .moveComposerDraft(composerDraftKey(workspaceId, from), composerDraftKey(workspaceId, to))
95
142
  for (const scope of ['shared', 'browser-tab'] as const) {
96
- queryClient.setQueryData<SelectedSessionState>(
143
+ queryClient.setQueryData<WorkspaceSessionSelection>(
97
144
  selectedSessionKey(workspaceId, scope),
98
- current => (current?.sessionId === from ? { sessionId: to } : current)
145
+ current =>
146
+ current
147
+ ? {
148
+ selected: Object.fromEntries(
149
+ Object.entries(current.selected).map(([tabId, id]) => [
150
+ tabId,
151
+ id === from ? to : id
152
+ ])
153
+ ),
154
+ pinned: current.pinned === from ? to : current.pinned
155
+ }
156
+ : current
99
157
  )
100
158
  }
101
- if (readSelectedSession(workspaceId) === from) writeSelectedSession(workspaceId, to)
159
+ const local = readSelectedSession(workspaceId)
160
+ writeSelectedSession(workspaceId, {
161
+ selected: Object.fromEntries(
162
+ Object.entries(local.selected).map(([tabId, id]) => [tabId, id === from ? to : id])
163
+ ),
164
+ pinned: null
165
+ })
166
+ }
167
+
168
+ export function useCurrentTabId(): WorkspaceTabId {
169
+ const tab = useParams()['*']
170
+ return isWorkspaceTabId(tab) ? tab : 'overview'
102
171
  }
103
172
 
104
- export function useSelectedSession(): SelectedSessionResult {
173
+ export function selectedSessionForTab(
174
+ shared: WorkspaceSessionSelection | undefined,
175
+ tabId: WorkspaceTabId,
176
+ local?: WorkspaceSessionSelection
177
+ ): string | null | undefined {
178
+ if (!shared) return undefined
179
+ if (shared.pinned) return shared.pinned
180
+ if (local && tabId in local.selected) return local.selected[tabId] ?? null
181
+ return shared.selected[tabId] ?? null
182
+ }
183
+
184
+ export function useSelectedSession(explicitTabId?: WorkspaceTabId): SelectedSessionResult {
185
+ const routeTabId = useCurrentTabId()
186
+ const tabId = explicitTabId ?? routeTabId
105
187
  const workspaceId = useWorkspaceId()
106
188
  const collabEnabled = useCollabEnabled()
107
189
  const scope: SelectedSessionScope = collabEnabled ? 'browser-tab' : 'shared'
@@ -116,19 +198,11 @@ export function useSelectedSession(): SelectedSessionResult {
116
198
  // WorkspaceContent remains an observer for the active workspace. Nested hook
117
199
  // users reuse its result without refetching; once the route unmounts, dropping
118
200
  // the cache makes the next visit load the server-owned selection again.
119
- const query = useQuery<SelectedSessionState>({
120
- queryKey,
121
- queryFn: () =>
122
- scope === 'browser-tab'
123
- ? Promise.resolve({ sessionId: readSelectedSession(workspaceId) })
124
- : requestJson(`/api/workspaces/${workspaceId}/selected-session`),
125
- staleTime: Infinity,
126
- gcTime: 0,
127
- refetchOnMount: false,
128
- refetchOnWindowFocus: false
129
- })
201
+ const query = useQuery(selectedSessionOptions(workspaceId, scope))
202
+ // A pin is shared with CLI creation and applies to every workspace tab.
203
+ const sharedSelection = useWorkspaceSessionSelection().data
130
204
 
131
- const { mutate: saveSelectedSession } = useMutation<
205
+ const { mutate: saveSelectedSession, mutateAsync: saveSelectedSessionAsync } = useMutation<
132
206
  SelectedSessionState,
133
207
  Error,
134
208
  SaveSelectedSessionInput
@@ -136,8 +210,12 @@ export function useSelectedSession(): SelectedSessionResult {
136
210
  mutationKey,
137
211
  scope: { id: `selected-session:${workspaceId}` },
138
212
  mutationFn: input => {
139
- if (scope === 'browser-tab') {
140
- writeSelectedSession(workspaceId, input.sessionId)
213
+ if (input.scope === 'browser-tab') {
214
+ writeSelectedSession(
215
+ workspaceId,
216
+ queryClient.getQueryData<WorkspaceSessionSelection>(queryKey) ??
217
+ readSelectedSession(workspaceId)
218
+ )
141
219
  return Promise.resolve({ sessionId: input.sessionId })
142
220
  }
143
221
  return requestJson<SelectedSessionState>(
@@ -147,39 +225,127 @@ export function useSelectedSession(): SelectedSessionResult {
147
225
  )
148
226
  },
149
227
  onSuccess: (saved, input) => {
150
- const result = settleSelectedSessionSave(queryClient, workspaceId, saved, input, scope)
228
+ const result = settleSelectedSessionSave(queryClient, workspaceId, saved, input)
151
229
  if (result !== 'conflict') return
152
230
 
153
231
  toast.add({ title: 'Couldn’t save selected chat', type: 'error' })
154
- queryClient.invalidateQueries({ queryKey })
232
+ void queryClient.invalidateQueries({ queryKey, exact: true })
155
233
  },
156
234
  onError: (_error, input) => {
157
- const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
158
- if (current?.sessionId !== input.sessionId) return
235
+ const current = queryClient.getQueryData<WorkspaceSessionSelection>(queryKey)
236
+ if ((current?.selected[input.tabId] ?? null) !== input.sessionId) return
159
237
 
160
238
  toast.add({ title: 'Couldn’t save selected chat', type: 'error' })
161
- queryClient.invalidateQueries({ queryKey })
239
+ void queryClient.invalidateQueries({ queryKey, exact: true })
240
+ },
241
+ onSettled: () => {
242
+ if (scope === 'shared' && queryClient.isMutating({ mutationKey, exact: true }) === 1)
243
+ void queryClient.invalidateQueries({ queryKey, exact: true })
162
244
  }
163
245
  })
164
246
 
165
247
  const setSelectedSessionId = useCallback<SetSelectedSession>(
166
248
  sessionId => {
167
- const input = optimisticallySetSelectedSession(queryClient, workspaceId, sessionId, scope)
249
+ if (
250
+ queryClient.getQueryData<WorkspaceSessionSelection>(selectedSessionKey(workspaceId))?.pinned
251
+ )
252
+ return
253
+ const input = optimisticallySetSelectedSession(
254
+ queryClient,
255
+ workspaceId,
256
+ sessionId,
257
+ tabId,
258
+ scope
259
+ )
168
260
  if (input) saveSelectedSession(input)
169
261
  },
170
- [queryClient, saveSelectedSession, workspaceId, scope]
262
+ [queryClient, saveSelectedSession, workspaceId, tabId, scope]
263
+ )
264
+
265
+ const selectSessionForTab = useCallback(
266
+ async (sessionId: string, destination: WorkspaceTabId) => {
267
+ const input = optimisticallySetSelectedSession(
268
+ queryClient,
269
+ workspaceId,
270
+ sessionId,
271
+ destination,
272
+ scope
273
+ )
274
+ if (!input) return
275
+ const saved = await saveSelectedSessionAsync(input)
276
+ if (
277
+ saved.sessionId !== sessionId ||
278
+ queryClient.getQueryData<WorkspaceSessionSelection>(queryKey)?.selected[destination] !==
279
+ sessionId
280
+ )
281
+ throw new Error('Couldn’t save selected chat')
282
+ },
283
+ [queryClient, queryKey, saveSelectedSessionAsync, scope, workspaceId]
171
284
  )
172
285
 
173
286
  useWorkspaceEvent(event => {
174
- if (
175
- scope === 'browser-tab' ||
176
- event.type !== 'selected-session:updated' ||
177
- event.workspaceId !== workspaceId
178
- )
179
- return
180
- applySelectedSessionEvent(queryClient, workspaceId, event.sessionId, pendingSaves > 0)
287
+ if (event.type !== 'selected-session:updated' || event.workspaceId !== workspaceId) return
288
+ applySelectedSessionEvent(queryClient, workspaceId, scope === 'shared' && pendingSaves > 0)
181
289
  })
182
290
 
183
- const selectedSessionId = query.isLoading ? undefined : (query.data?.sessionId ?? null)
184
- return [selectedSessionId, setSelectedSessionId]
291
+ const selectedSessionId =
292
+ query.data === undefined || sharedSelection === undefined
293
+ ? undefined
294
+ : selectedSessionForTab(
295
+ sharedSelection,
296
+ tabId,
297
+ scope === 'browser-tab' ? query.data : undefined
298
+ )
299
+ return [selectedSessionId, setSelectedSessionId, selectSessionForTab]
300
+ }
301
+
302
+ function useWorkspaceSessionSelection() {
303
+ const workspaceId = useWorkspaceId()
304
+ return useQuery(selectedSessionOptions(workspaceId))
305
+ }
306
+
307
+ export function usePinnedSession() {
308
+ const workspaceId = useWorkspaceId()
309
+ const queryClient = useQueryClient()
310
+ const { data } = useWorkspaceSessionSelection()
311
+ const mutation = useMutation({
312
+ scope: { id: `pinned-session:${workspaceId}` },
313
+ mutationFn: (sessionId: string | null) =>
314
+ requestJson<{ pinnedSessionId: string | null }>(
315
+ `/api/workspaces/${workspaceId}/pinned-session`,
316
+ jsonRequest('PUT', { sessionId })
317
+ ),
318
+ onMutate: sessionId => {
319
+ const queryKey = appUiKeys.sessionSelection(workspaceId)
320
+ const previousPinnedSessionId =
321
+ queryClient.getQueryData<WorkspaceSessionSelection>(queryKey)?.pinned ?? null
322
+ queryClient.setQueryData<WorkspaceSessionSelection>(queryKey, current => ({
323
+ selected: current?.selected ?? {},
324
+ pinned: sessionId
325
+ }))
326
+ return previousPinnedSessionId
327
+ },
328
+ onError: (_error, sessionId, previousPinnedSessionId) => {
329
+ queryClient.setQueryData<WorkspaceSessionSelection>(
330
+ appUiKeys.sessionSelection(workspaceId),
331
+ current =>
332
+ current?.pinned === sessionId
333
+ ? { ...current, pinned: previousPinnedSessionId ?? null }
334
+ : current
335
+ )
336
+ toast.add({ title: 'Couldn’t pin chat', type: 'error' })
337
+ },
338
+ onSettled: () => {
339
+ void queryClient.invalidateQueries({
340
+ queryKey: appUiKeys.sessionSelection(workspaceId),
341
+ exact: true
342
+ })
343
+ }
344
+ })
345
+ return {
346
+ pinnedSessionId: data?.pinned ?? null,
347
+ loaded: data !== undefined,
348
+ pin: mutation.mutate,
349
+ pinAsync: mutation.mutateAsync
350
+ }
185
351
  }
@@ -1,10 +1,10 @@
1
- import { useCallback, useEffect, useMemo } from 'react'
1
+ import { useCallback, useMemo } from 'react'
2
2
 
3
3
  import { useQueryClient } from '@tanstack/react-query'
4
4
 
5
5
  import { workspaceKeys } from '@/client/api/workspace-keys'
6
6
  import {
7
- useSessionConfig,
7
+ useSession,
8
8
  useSessionView,
9
9
  useWorkspaceSessions
10
10
  } from '@/client/features/chat/sessions/api'
@@ -20,13 +20,16 @@ import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayo
20
20
  import { sendMessage } from '@/client/features/chat/connection/chat-connection'
21
21
  import {
22
22
  type ChatSendOptions,
23
+ finishComposerSend,
24
+ moveChatDraft,
23
25
  prepareDraftAttachments,
26
+ prepareOptimisticSend,
24
27
  attachmentsForSend,
25
28
  ownsComposerAttachments,
26
29
  resolveChatRunOptions,
27
- startOptimisticSession,
28
- startOptimisticTurn
30
+ startOptimisticSession
29
31
  } from '@/client/features/chat/chat-send'
32
+ import { visibleForkHistory } from '@/client/features/chat/messages/fork-history'
30
33
  import { buildPreviewTurn } from '@/client/features/chat/messages/preview-turn'
31
34
  import {
32
35
  isRunningActivity,
@@ -34,11 +37,11 @@ import {
34
37
  selectPreviews,
35
38
  useLive
36
39
  } from '@/client/features/chat/chat-store'
37
- import { useUiStore } from '@/client/store/ui'
38
40
  import { toast } from '@/client/components/ui/toast'
39
41
  import { emptyViewState } from '@/lib/format'
40
42
  import { messageAttachmentLimitError } from '@/lib/message-attachments'
41
- import type { Part, ViewState } from '@/lib/types'
43
+ import { draftSessionId } from '@/lib/session-drafts'
44
+ import type { ViewState } from '@/lib/types'
42
45
 
43
46
  const EMPTY: ViewState = emptyViewState()
44
47
 
@@ -53,19 +56,14 @@ export function useChat(address: WorkspaceTabAddress) {
53
56
  const workspaceId = useWorkspaceId()
54
57
  const qc = useQueryClient()
55
58
  const { layout } = useWorkspaceLayoutCtx()
56
- const [selectedSession, selectSession] = useSelectedSession()
59
+ const [selectedSession, selectSession] = useSelectedSession(address.activeTab)
57
60
  const collabEnabled = useCollabEnabled()
58
61
  const modelsData = useWorkspaceAgent(workspaceId).data
59
62
  const sessions = useWorkspaceSessions(workspaceId).data
60
- const selectedSessionMissing =
61
- Boolean(selectedSession) &&
62
- sessions !== undefined &&
63
- !sessions.some(session => session.sessionId === selectedSession)
64
- const selectedSessionId = selectedSessionMissing ? null : (selectedSession ?? null)
65
-
66
- useEffect(() => {
67
- if (selectedSessionMissing) selectSession(null)
68
- }, [selectSession, selectedSessionMissing])
63
+ // A newly forked/native session can precede the provider's session listing.
64
+ // Archive explicitly clears selection; a stale catalog must not do so.
65
+ const selectedSessionId = selectedSession ?? null
66
+ const composerSessionId = selectedSessionId ?? draftSessionId(address.activeTab)
69
67
  // Snapshot of the workspace's ambient UI state + queued one-shot
70
68
  // directives, taken when the message actually goes out.
71
69
  const buildMoiContext = useMoiUserMessageContext(address)
@@ -81,10 +79,21 @@ export function useChat(address: WorkspaceTabAddress) {
81
79
 
82
80
  const viewQuery = useSessionView(workspaceId, selectedSessionId)
83
81
  const { refetch } = viewQuery
84
- const retryLoad = useCallback(() => void refetch(), [refetch])
85
- const view = viewQuery.data ?? EMPTY
82
+ const session = useSession(workspaceId, selectedSessionId)
83
+ const { refetch: refetchSession } = session
84
+ const retryLoad = useCallback(async () => {
85
+ await refetch()
86
+ await refetchSession()
87
+ }, [refetch, refetchSession])
88
+ const forkedFromSessionId = session.data?.forkedFromSessionId
89
+ const sessionReady = !selectedSessionId || session.data !== undefined
90
+ let view = sessionReady ? (viewQuery.data ?? EMPTY) : EMPTY
91
+ if (viewQuery.data && forkedFromSessionId) view = visibleForkHistory(viewQuery.data, session.data)
86
92
  const chatLoaded =
87
- sessions !== undefined && (selectedSessionId === null || viewQuery.data !== undefined)
93
+ selectedSession !== undefined &&
94
+ sessionReady &&
95
+ sessions !== undefined &&
96
+ (selectedSessionId === null || viewQuery.data !== undefined)
88
97
 
89
98
  // The live streaming preview as a synthetic assistant turn, so the ChatPanel
90
99
  // can merge it into the trailing assistant run — a
@@ -99,7 +108,7 @@ export function useChat(address: WorkspaceTabAddress) {
99
108
 
100
109
  // The selected session's persisted model/effort. For a brand-new chat (no
101
110
  // session yet) this is empty and `send` falls back to workspace defaults.
102
- const sessionConfig = useSessionConfig(workspaceId, selectedSessionId).data
111
+ const sessionConfig = session.data?.config
103
112
 
104
113
  // The composer owns the workspace draft in the persisted UI store and hands
105
114
  // the text in, so a keystroke re-renders only the composer.
@@ -110,7 +119,7 @@ export function useChat(address: WorkspaceTabAddress) {
110
119
  // sent; the composer disables send while any are still uploading, so in
111
120
  // practice they're all ready here. Applet sends supply their own prepared
112
121
  // attachments and leave the user's staged files alone.
113
- const ready = attachmentsForSend(workspaceId, selectedSessionId, options)
122
+ const ready = attachmentsForSend(workspaceId, composerSessionId, options)
114
123
  // No `processing` guard: sending while a turn is in flight QUEUES the
115
124
  // message into the same live server session (streaming-input mode).
116
125
  if (!text && ready.length === 0 && !options?.preparedAttachments?.attachments.length) return
@@ -129,10 +138,11 @@ export function useChat(address: WorkspaceTabAddress) {
129
138
  isNew = true
130
139
  // An immediate applet send leaves the user's attachments staged in this chat.
131
140
  if (!ownsComposerAttachments(options)) {
132
- liveStore.getState().renameSession(workspaceId, selectedSessionId, sid)
141
+ moveChatDraft(workspaceId, composerSessionId, sid)
133
142
  }
134
143
  selectSession(sid)
135
144
  startOptimisticSession({
145
+ tabId: address.activeTab,
136
146
  queryClient: qc,
137
147
  workspaceId,
138
148
  sessionId: sid,
@@ -141,19 +151,11 @@ export function useChat(address: WorkspaceTabAddress) {
141
151
  })
142
152
  }
143
153
 
144
- // Optimistic user turn — primed into the RQ transcript cache so it renders
145
- // immediately. The server re-ids the SDK's user echo to optimisticId so it
146
- // upserts in place rather than duplicating. Image attachments render from
147
- // their local object URL until the server's broadcast (with a data URL)
148
- // upserts in place.
149
- const parts: Part[] = [...prepared.parts]
150
- if (text) parts.push({ type: 'text', text })
151
- const optimisticId = startOptimisticTurn({
152
- queryClient: qc,
153
- workspaceId,
154
- sessionId: sid,
155
- parts
156
- })
154
+ const { attachments, optimisticId } = prepareOptimisticSend(
155
+ { queryClient: qc, workspaceId, sessionId: sid, text },
156
+ ready,
157
+ prepared
158
+ )
157
159
 
158
160
  // Resolve the session/workspace choice against the catalog. Codex sends
159
161
  // the picker's concrete model even for an implicit or stale selection;
@@ -168,7 +170,6 @@ export function useChat(address: WorkspaceTabAddress) {
168
170
  pickedEffort,
169
171
  pickedFastMode
170
172
  )
171
- const { attachments } = prepared
172
173
  sendMessage({
173
174
  type: 'chat',
174
175
  workspaceId,
@@ -184,19 +185,14 @@ export function useChat(address: WorkspaceTabAddress) {
184
185
  context: buildMoiContext(options),
185
186
  ...(attachments.length > 0 ? { attachments } : {})
186
187
  })
187
- useUiStore.getState().markMessageSentFromMoi(workspaceId)
188
+ finishComposerSend(workspaceId, ready)
188
189
  if (isNew) {
189
190
  qc.invalidateQueries({ queryKey: workspaceKeys.preview(workspaceId) })
190
191
  }
191
- // Drop the session's attachments now that they've been sent (revokes the
192
- // preview object URLs). Keyed by the pre-mint id, matching where they were
193
- // stored by the composer. Skipped for an applet send:
194
- // clearing here would discard the user's staged (and in-flight) files.
195
- if (ownsComposerAttachments(options)) {
196
- liveStore.getState().clearAttachments(workspaceId, selectedSessionId)
197
- }
198
192
  },
199
193
  [
194
+ address.activeTab,
195
+ composerSessionId,
200
196
  selectedSessionId,
201
197
  workspaceId,
202
198
  qc,
@@ -225,12 +221,14 @@ export function useChat(address: WorkspaceTabAddress) {
225
221
 
226
222
  return {
227
223
  view,
224
+ forkedFromSessionId,
228
225
  chatLoaded,
229
226
  previewTurn,
230
227
  sessionId: selectedSessionId,
228
+ composerSessionId,
231
229
  processing,
232
230
  error,
233
- loadError: viewQuery.error?.message ?? null,
231
+ loadError: session.error?.message ?? viewQuery.error?.message ?? null,
234
232
  retryLoad,
235
233
  send,
236
234
  stop,
@@ -10,11 +10,10 @@ import type {
10
10
 
11
11
  import {
12
12
  getCurrentUser,
13
- getWorkspaceDirectory,
13
+ getDirectory,
14
14
  subscribeCurrentUserStore,
15
- subscribeWorkspaceUsersStore
15
+ subscribeDirectoryStore
16
16
  } from './host-state'
17
- import type { WorkspaceDirectory } from './host-state'
18
17
  import { CollabStore, DISCONNECTED_STATE } from './store'
19
18
  import type { ClientState, PresenceEntry } from './store'
20
19
 
@@ -32,8 +31,10 @@ export type CollabEngineApi = {
32
31
  subscribe: (listener: () => void) => Unsubscribe
33
32
  getCurrentUser: () => UserProfile | undefined
34
33
  subscribeCurrentUser: (listener: () => void) => Unsubscribe
35
- getWorkspaceDirectory: () => WorkspaceDirectory | undefined
36
- subscribeWorkspaceUsers: (listener: () => void) => Unsubscribe
34
+ // Everyone an outer host published. Undefined without a host, in which
35
+ // case live users stand in.
36
+ getDirectory: () => readonly UserProfile[] | undefined
37
+ subscribeDirectory: (listener: () => void) => Unsubscribe
37
38
  getLocation: () => ConnectionLocation | null
38
39
  setLocation: (location: ConnectionLocation | null) => void
39
40
  setPresence: (registration: PresenceRegistration) => void
@@ -53,8 +54,8 @@ export const NO_ENGINE: CollabEngineApi = {
53
54
  subscribe: () => noop,
54
55
  getCurrentUser,
55
56
  subscribeCurrentUser: subscribeCurrentUserStore,
56
- getWorkspaceDirectory: () => undefined,
57
- subscribeWorkspaceUsers: () => noop,
57
+ getDirectory,
58
+ subscribeDirectory: subscribeDirectoryStore,
58
59
  getLocation: () => null,
59
60
  setLocation: noop,
60
61
  setPresence: noop,
@@ -91,10 +92,8 @@ export class CollabClient implements CollabEngineApi {
91
92
  this.enabled ? this.store.subscribe(listener) : noop
92
93
  getCurrentUser = getCurrentUser
93
94
  subscribeCurrentUser = subscribeCurrentUserStore
94
- getWorkspaceDirectory = (): WorkspaceDirectory | undefined =>
95
- getWorkspaceDirectory(this.workspaceId)
96
- subscribeWorkspaceUsers = (listener: () => void): Unsubscribe =>
97
- subscribeWorkspaceUsersStore(this.workspaceId, listener)
95
+ getDirectory = getDirectory
96
+ subscribeDirectory = subscribeDirectoryStore
98
97
  getLocation = (): ConnectionLocation | null => (this.enabled ? this.store.getLocation() : null)
99
98
  setLocation = (location: ConnectionLocation | null): void => {
100
99
  this.store.setLocation(location)
@@ -20,14 +20,6 @@ export function useConnectionState() {
20
20
  const engine = useCollabEngine()
21
21
  return useSyncExternalStore(engine.subscribe, engine.getUsersSnapshot, engine.getUsersSnapshot)
22
22
  }
23
- export function useWorkspaceDirectory() {
24
- const engine = useCollabEngine()
25
- return useSyncExternalStore(
26
- engine.subscribeWorkspaceUsers,
27
- engine.getWorkspaceDirectory,
28
- engine.getWorkspaceDirectory
29
- )
30
- }
31
23
  function useUsersSource() {
32
24
  const engine = useCollabEngine()
33
25
  const state = useConnectionState()
@@ -36,10 +28,13 @@ function useUsersSource() {
36
28
  engine.getCurrentUser,
37
29
  engine.getCurrentUser
38
30
  )
39
- const directory = useWorkspaceDirectory()
31
+ const directory = useSyncExternalStore(
32
+ engine.subscribeDirectory,
33
+ engine.getDirectory,
34
+ engine.getDirectory
35
+ )
40
36
  const users = useMemo(
41
- () =>
42
- workspaceProfiles(state.users, self, directory?.status === 'loading' ? [] : directory?.users),
37
+ () => workspaceProfiles(state.users, self, directory),
43
38
  [state.users, self, directory]
44
39
  )
45
40
  return { state, self, users, engine }