moi-computer 0.5.2-next.1 → 0.6.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 (83) hide show
  1. package/README.md +39 -0
  2. package/client/AGENTS.md +9 -0
  3. package/client/api/app-ui-keys.ts +4 -0
  4. package/client/api/workspace-keys.ts +2 -2
  5. package/client/app/routes/WorkspaceRoute.tsx +8 -28
  6. package/client/components/shared/Composer.tsx +3 -6
  7. package/client/components/shared/IconGhost.tsx +130 -0
  8. package/client/components/ui/dropdown-menu.tsx +1 -1
  9. package/client/components/ui/spinner.tsx +18 -0
  10. package/client/components/ui/toast.tsx +220 -0
  11. package/client/features/chat/ChatComposer.tsx +3 -2
  12. package/client/features/chat/ChatPanel.tsx +7 -6
  13. package/client/features/chat/ChatPopup.tsx +10 -4
  14. package/client/features/chat/ChatSelector.tsx +263 -48
  15. package/client/features/chat/ModelPicker.tsx +13 -18
  16. package/client/features/chat/api.ts +36 -9
  17. package/client/features/chat/chat-frames.ts +35 -6
  18. package/client/features/chat/chat-send.ts +25 -1
  19. package/client/features/chat/chat-store.ts +43 -18
  20. package/client/features/chat/useChat.ts +54 -52
  21. package/client/features/chat/useSelectedSession.ts +151 -0
  22. package/client/features/chat/useStickToBottom.ts +3 -3
  23. package/client/features/home/api.ts +0 -2
  24. package/client/features/scratchpad/ScratchpadControls.tsx +2 -2
  25. package/client/features/settings/WorkspaceSettings.tsx +6 -6
  26. package/client/features/views/ViewBuilderTab.tsx +3 -4
  27. package/client/features/views/useViewBuilderActions.ts +3 -1
  28. package/client/features/workspace/WorkspaceScreen.tsx +38 -17
  29. package/client/features/workspace/WorkspaceTabs.tsx +10 -1
  30. package/client/main.tsx +2 -0
  31. package/client/runtime/useWorkspaceEvents.ts +1 -0
  32. package/client/store/ui.ts +2 -2
  33. package/dist/{chunk-zs4mte79.js → chunk-0pcdwjkp.js} +1 -1
  34. package/dist/chunk-175bm057.js +27 -0
  35. package/dist/chunk-55sh4dty.js +2 -0
  36. package/dist/{chunk-tzz101ea.js → chunk-9y2zbzqz.js} +1 -1
  37. package/dist/{chunk-jvhvme3z.js → chunk-afgbg75t.js} +1 -1
  38. package/dist/chunk-agtetn7n.css +1 -0
  39. package/dist/chunk-dfs36zgc.js +1 -0
  40. package/dist/chunk-exj6hr30.js +9 -0
  41. package/dist/{chunk-bcrkdhwe.js → chunk-m11ckkxd.js} +1 -1
  42. package/dist/{chunk-kfw1qwqe.js → chunk-rxvx4ta9.js} +3 -3
  43. package/dist/{chunk-xwhya7kb.js → chunk-w3tnv51j.js} +1 -1
  44. package/dist/index.html +1 -1
  45. package/lib/attachment-note.ts +18 -0
  46. package/lib/chat-title.ts +6 -0
  47. package/lib/types.ts +24 -10
  48. package/package.json +1 -1
  49. package/server/agent-caller.ts +16 -0
  50. package/server/api.ts +90 -9
  51. package/server/app-settings.ts +1 -1
  52. package/server/cli.ts +628 -45
  53. package/server/control.ts +18 -1
  54. package/server/data-dir.ts +1 -1
  55. package/server/harness/README.md +6 -0
  56. package/server/harness/claude-code/adapter.ts +2 -2
  57. package/server/harness/claude-code/index.ts +7 -1
  58. package/server/harness/claude-code/session-title.ts +106 -0
  59. package/server/harness/claude-code/session.ts +107 -17
  60. package/server/harness/claude-code/sessions.ts +63 -4
  61. package/server/harness/codex/client.ts +33 -13
  62. package/server/harness/codex/index.ts +2 -0
  63. package/server/harness/codex/session-title.ts +149 -0
  64. package/server/harness/codex/session.ts +84 -11
  65. package/server/harness/openclaw/adapter.ts +4 -2
  66. package/server/harness/openclaw/discovery.ts +2 -0
  67. package/server/harness/openclaw/session.ts +15 -7
  68. package/server/harness/session-title.ts +96 -0
  69. package/server/harness/types.ts +2 -0
  70. package/server/selected-session.ts +132 -0
  71. package/server/service.ts +786 -0
  72. package/server/{thread-config.ts → session-config.ts} +57 -39
  73. package/server/status.ts +2 -0
  74. package/server/update.ts +141 -0
  75. package/server/version.ts +41 -0
  76. package/server/web.ts +17 -1
  77. package/workspace/.claude/skills/moi-workspace/DESIGN.md +16 -26
  78. package/workspace/.claude/skills/moi-workspace/SKILL.md +8 -2
  79. package/dist/chunk-94m3q9ce.js +0 -1
  80. package/dist/chunk-k9dcnd73.js +0 -27
  81. package/dist/chunk-pk11vfzs.js +0 -9
  82. package/dist/chunk-r2bqaege.js +0 -2
  83. package/dist/chunk-y4g8j7mv.css +0 -1
@@ -3,7 +3,7 @@ import { createStore } from 'zustand/vanilla'
3
3
 
4
4
  import type { PreviewBlock, PreviewFrame, SessionActivity, UploadInfo } from '@/lib/types'
5
5
 
6
- // One composer attachment, tracked per thread until the message is sent. It is
6
+ // One composer attachment, tracked per session until the message is sent. It is
7
7
  // uploaded as soon as it's added (drop/paste/pick); `status` reflects that
8
8
  // in-flight upload, and `upload` holds the server handle once ready. `previewUrl`
9
9
  // is a local object URL for image thumbnails (revoked on remove/clear).
@@ -19,15 +19,13 @@ export type ChatAttachment = {
19
19
 
20
20
  // App-level ephemeral chat state — the bits that are *pushed* from the server
21
21
  // over the WebSocket and can't be re-fetched as request/response data:
22
- // - which thread is active per workspace (a UI selection),
23
22
  // - per-session `activity` (spinner) state,
24
23
  // - per-session error banners.
25
24
  //
26
25
  // The durable message transcripts live in the React Query cache (see
27
26
  // useSessionView), which is also app-level — so nothing here needs to mirror
28
- // them. This is a single module-singleton store (not React-context scoped), so
29
- // it survives route navigation: leaving and re-entering a workspace keeps the
30
- // active thread and any in-flight spinner intact.
27
+ // them. The selected session has its own persisted React Query context; this
28
+ // store only owns disposable live state.
31
29
  //
32
30
  // Per-session entries are keyed `${workspaceId}:${sessionId}`.
33
31
 
@@ -35,6 +33,43 @@ function key(workspaceId: string, sessionId: string): string {
35
33
  return `${workspaceId}:${sessionId}`
36
34
  }
37
35
 
36
+ export function isRunningActivity(activity: SessionActivity | undefined): boolean {
37
+ return activity === 'running'
38
+ }
39
+
40
+ export function isSessionRunning(
41
+ activity: Record<string, SessionActivity>,
42
+ workspaceId: string,
43
+ sessionId: string
44
+ ): boolean {
45
+ return isRunningActivity(activity[key(workspaceId, sessionId)])
46
+ }
47
+
48
+ export function hasRunningWorkspaceActivity(
49
+ activity: Record<string, SessionActivity>,
50
+ workspaceId: string
51
+ ): boolean {
52
+ const prefix = `${workspaceId}:`
53
+ return Object.entries(activity).some(
54
+ ([activityKey, value]) => activityKey.startsWith(prefix) && isRunningActivity(value)
55
+ )
56
+ }
57
+
58
+ export function hasRunningBackgroundSession(
59
+ activity: Record<string, SessionActivity>,
60
+ workspaceId: string,
61
+ selectedSessionId: string | null
62
+ ): boolean {
63
+ if (!selectedSessionId) return false
64
+
65
+ const prefix = `${workspaceId}:`
66
+ const selectedKey = key(workspaceId, selectedSessionId)
67
+ return Object.entries(activity).some(
68
+ ([activityKey, value]) =>
69
+ activityKey.startsWith(prefix) && activityKey !== selectedKey && isRunningActivity(value)
70
+ )
71
+ }
72
+
38
73
  // Attachments stay with the chat they were added to. A brand-new chat has no
39
74
  // session id yet, so it gets a stable `'new'` sentinel until send mints one.
40
75
  export function attachmentKey(workspaceId: string, sessionId: string | null): string {
@@ -53,7 +88,6 @@ export type LivePreview = {
53
88
  }
54
89
 
55
90
  export type LiveStore = {
56
- activeByWorkspace: Record<string, string | null>
57
91
  // Per-session activity mirrored from server `status` frames. Only `running`
58
92
  // shows the loader/Stop; `requires-action` is tracked but not rendered yet.
59
93
  // Missing key = idle.
@@ -67,7 +101,6 @@ export type LiveStore = {
67
101
  // send. Draft text is workspace-local persisted UI state (client/store/ui).
68
102
  attachments: Record<string, ChatAttachment[]>
69
103
 
70
- setActive: (workspaceId: string, sessionId: string | null) => void
71
104
  setActivity: (workspaceId: string, sessionId: string, value: SessionActivity) => void
72
105
  // Authoritative reconcile from a server `status_snapshot`: exactly the listed
73
106
  // sessions are active; everything else is cleared to idle (fixes a spinner
@@ -102,15 +135,11 @@ export type LiveStore = {
102
135
  }
103
136
 
104
137
  export const liveStore = createStore<LiveStore>()(set => ({
105
- activeByWorkspace: {},
106
138
  activity: {},
107
139
  errors: {},
108
140
  previews: {},
109
141
  attachments: {},
110
142
 
111
- setActive: (workspaceId, sessionId) =>
112
- set(s => ({ activeByWorkspace: { ...s.activeByWorkspace, [workspaceId]: sessionId } })),
113
-
114
143
  setActivity: (workspaceId, sessionId, value) =>
115
144
  set(s => ({ activity: { ...s.activity, [key(workspaceId, sessionId)]: value } })),
116
145
 
@@ -221,12 +250,8 @@ export const liveStore = createStore<LiveStore>()(set => ({
221
250
  errors[toKey] = errors[fromKey]
222
251
  delete errors[fromKey]
223
252
  }
224
- const activeByWorkspace =
225
- s.activeByWorkspace[workspaceId] === from
226
- ? { ...s.activeByWorkspace, [workspaceId]: to }
227
- : s.activeByWorkspace
228
253
  // Retarget any in-flight previews from the temp id to the real one so a
229
- // preview that arrived before the rename keeps routing to the thread.
254
+ // preview that arrived before the rename keeps routing to the session.
230
255
  let previews = s.previews
231
256
  let previewsChanged = false
232
257
  for (const [id, p] of Object.entries(s.previews)) {
@@ -238,11 +263,11 @@ export const liveStore = createStore<LiveStore>()(set => ({
238
263
  previews[id] = { ...p, sessionId: to }
239
264
  }
240
265
  }
241
- return { activity, errors, activeByWorkspace, previews }
266
+ return { activity, errors, previews }
242
267
  })
243
268
  }))
244
269
 
245
- // Select the live previews for a thread, split into the root (top-level
270
+ // Select the live previews for a session, split into the root (top-level
246
271
  // assistant) stream and per-subagent streams. Takes the raw `previews` record
247
272
  // (a stable store slice) so callers select that slice and run this inside a
248
273
  // `useMemo` — never return a fresh object straight from a zustand selector.
@@ -4,11 +4,12 @@ import { useQueryClient } from '@tanstack/react-query'
4
4
 
5
5
  import { workspaceKeys } from '@/client/api/workspace-keys'
6
6
  import {
7
+ useSessionConfig,
7
8
  useSessionView,
8
- useThreadConfig,
9
9
  useWorkspaceModels,
10
10
  useWorkspaceSessions
11
11
  } from '@/client/features/chat/api'
12
+ import { useSelectedSession } from '@/client/features/chat/useSelectedSession'
12
13
  import {
13
14
  type WorkspaceTabAddress,
14
15
  useMoiUserMessageContext
@@ -21,19 +22,25 @@ import {
21
22
  attachmentsForSend,
22
23
  ownsComposerAttachments,
23
24
  resolveChatRunOptions,
25
+ startOptimisticSession,
24
26
  startOptimisticTurn
25
27
  } from '@/client/features/chat/chat-send'
26
28
  import { buildPreviewTurn } from '@/client/features/chat/preview-turn'
27
- import { liveStore, selectPreviews, useLive } from '@/client/features/chat/chat-store'
29
+ import {
30
+ isRunningActivity,
31
+ liveStore,
32
+ selectPreviews,
33
+ useLive
34
+ } from '@/client/features/chat/chat-store'
28
35
  import { useUiStore } from '@/client/store/ui'
29
36
  import { emptyViewState } from '@/lib/format'
30
37
  import type { Part, ViewState } from '@/lib/types'
31
38
 
32
39
  const EMPTY: ViewState = emptyViewState()
33
40
 
34
- // Thin projection over app-level state: the active thread + spinner/error come
35
- // from the live store; the transcript comes from the React Query cache (kept
36
- // current by the connection manager's WS deltas). No socket lifecycle here.
41
+ // Thin projection over app-level state: the selected session comes from
42
+ // useSelectedSession, spinner/error come from the live store, and the
43
+ // transcript comes from the React Query cache. No socket lifecycle here.
37
44
  //
38
45
  // Takes the workspace's tab address because every message carries it: the
39
46
  // envelope tells the agent which tab the user is on and what the active view
@@ -42,34 +49,28 @@ export function useChat(address: WorkspaceTabAddress) {
42
49
  const workspaceId = useWorkspaceId()
43
50
  const qc = useQueryClient()
44
51
  const { layout } = useWorkspaceLayoutCtx()
52
+ const [selectedSession, selectSession] = useSelectedSession()
53
+ const selectedSessionId = selectedSession ?? null
45
54
  const modelsData = useWorkspaceModels(workspaceId).data
46
55
  const sessions = useWorkspaceSessions(workspaceId).data
47
56
  // Snapshot of the workspace's ambient UI state + queued one-shot
48
57
  // directives, taken when the message actually goes out.
49
58
  const buildMoiContext = useMoiUserMessageContext(address)
50
59
 
51
- const activeSessionId = useLive(s => s.activeByWorkspace[workspaceId] ?? null)
52
- const sessionSelectionInitialized = useLive(s =>
53
- Object.prototype.hasOwnProperty.call(s.activeByWorkspace, workspaceId)
54
- )
55
60
  const activity = useLive(s =>
56
- activeSessionId ? (s.activity[`${workspaceId}:${activeSessionId}`] ?? 'idle') : 'idle'
61
+ selectedSessionId ? (s.activity[`${workspaceId}:${selectedSessionId}`] ?? 'idle') : 'idle'
57
62
  )
58
63
  // Only `running` shows the loader/Stop. `requires-action` (agent blocked on
59
64
  // user input) deliberately renders like idle until it gets its own UI.
60
- const processing = activity === 'running'
65
+ const processing = isRunningActivity(activity)
61
66
  const error = useLive(s =>
62
- activeSessionId ? (s.errors[`${workspaceId}:${activeSessionId}`] ?? null) : null
67
+ selectedSessionId ? (s.errors[`${workspaceId}:${selectedSessionId}`] ?? null) : null
63
68
  )
64
69
 
65
- const viewQuery = useSessionView(workspaceId, activeSessionId)
70
+ const viewQuery = useSessionView(workspaceId, selectedSessionId)
66
71
  const view = viewQuery.data ?? EMPTY
67
72
  const chatLoaded =
68
- sessionSelectionInitialized &&
69
- sessions !== undefined &&
70
- (activeSessionId === null ||
71
- (sessions.some(session => session.sessionId === activeSessionId) &&
72
- viewQuery.data !== undefined))
73
+ sessions !== undefined && (selectedSessionId === null || viewQuery.data !== undefined)
73
74
 
74
75
  // The live streaming preview as a synthetic assistant turn, so the ChatPanel
75
76
  // can run it through the SAME groupTurns pipeline as finalized turns — a
@@ -78,34 +79,41 @@ export function useChat(address: WorkspaceTabAddress) {
78
79
  // stable across other updates); null when there's nothing visible yet.
79
80
  const previews = useLive(s => s.previews)
80
81
  const previewTurn = useMemo(
81
- () => buildPreviewTurn(selectPreviews(previews, workspaceId, activeSessionId).root),
82
- [previews, workspaceId, activeSessionId]
82
+ () => buildPreviewTurn(selectPreviews(previews, workspaceId, selectedSessionId).root),
83
+ [previews, workspaceId, selectedSessionId]
83
84
  )
84
85
 
85
- // The active thread's persisted model/effort. For a brand-new chat (no thread
86
- // yet) this is empty and `send` falls back to the workspace defaults below.
87
- const threadCfg = useThreadConfig(workspaceId, activeSessionId).data
86
+ // The selected session's persisted model/effort. For a brand-new chat (no
87
+ // session yet) this is empty and `send` falls back to workspace defaults.
88
+ const sessionConfig = useSessionConfig(workspaceId, selectedSessionId).data
88
89
 
89
90
  // The composer owns the workspace draft in the persisted UI store and hands
90
91
  // the text in, so a keystroke re-renders only the composer.
91
92
  const send = useCallback(
92
93
  (draft: string, options?: ChatSendOptions) => {
93
94
  const text = draft.trim()
94
- // Attachments stay with the active thread. Only fully-uploaded ones are
95
+ // Attachments stay with the selected session. Only fully-uploaded ones are
95
96
  // sent; the composer disables send while any are still uploading, so in
96
97
  // practice they're all ready here. An applet send gets none — the staged
97
98
  // files are the user's, not the widget's.
98
- const ready = attachmentsForSend(workspaceId, activeSessionId, options)
99
+ const ready = attachmentsForSend(workspaceId, selectedSessionId, options)
99
100
  // No `processing` guard: sending while a turn is in flight QUEUES the
100
101
  // message into the same live server session (streaming-input mode).
101
102
  if (!text && ready.length === 0) return
102
103
 
103
- let sid = activeSessionId
104
+ let sid = selectedSessionId
104
105
  let isNew = false
105
106
  if (!sid) {
106
107
  sid = crypto.randomUUID()
107
108
  isNew = true
108
- liveStore.getState().setActive(workspaceId, sid)
109
+ selectSession(sid)
110
+ startOptimisticSession({
111
+ queryClient: qc,
112
+ workspaceId,
113
+ sessionId: sid,
114
+ text,
115
+ filenames: ready.map(attachment => attachment.name)
116
+ })
109
117
  }
110
118
 
111
119
  // Optimistic user turn — primed into the RQ transcript cache so it renders
@@ -129,15 +137,15 @@ export function useChat(address: WorkspaceTabAddress) {
129
137
  parts
130
138
  })
131
139
 
132
- // The thread's persisted choice (workspace defaults for a new chat). Drop a
140
+ // The session's persisted choice (workspace defaults for a new chat). Drop a
133
141
  // model the loaded list no longer offers (stale alias) so the SDK doesn't
134
142
  // reject model_not_found. Drop an effort the resolved model doesn't
135
143
  // support and explicitly disable Fast mode on a known unsupported model.
136
144
  // When the model is unknown/default we can't validate either capability,
137
145
  // so pass the stored choices through.
138
- const pickedModel = threadCfg?.model ?? layout.selectedModel
139
- const pickedEffort = threadCfg?.effort ?? layout.selectedEffort
140
- const pickedFastMode = threadCfg?.fastMode ?? layout.selectedFastMode
146
+ const pickedModel = sessionConfig?.model ?? layout.selectedModel
147
+ const pickedEffort = sessionConfig?.effort ?? layout.selectedEffort
148
+ const pickedFastMode = sessionConfig?.fastMode ?? layout.selectedFastMode
141
149
  const { model, effort, fastMode, stream } = resolveChatRunOptions(
142
150
  modelsData,
143
151
  pickedModel,
@@ -162,56 +170,50 @@ export function useChat(address: WorkspaceTabAddress) {
162
170
  if (isNew) {
163
171
  qc.invalidateQueries({ queryKey: workspaceKeys.preview(workspaceId) })
164
172
  }
165
- // Drop the thread's attachments now that they've been sent (revokes the
173
+ // Drop the session's attachments now that they've been sent (revokes the
166
174
  // preview object URLs). Keyed by the pre-mint id, matching where they were
167
175
  // stored by the composer. Skipped for an applet send, which carried none:
168
176
  // clearing here would discard the user's staged (and in-flight) files.
169
177
  if (ownsComposerAttachments(options)) {
170
- liveStore.getState().clearAttachments(workspaceId, activeSessionId)
178
+ liveStore.getState().clearAttachments(workspaceId, selectedSessionId)
171
179
  }
172
180
  },
173
181
  [
174
- activeSessionId,
182
+ selectedSessionId,
175
183
  workspaceId,
176
184
  qc,
177
185
  layout.selectedModel,
178
186
  layout.selectedEffort,
179
187
  layout.selectedFastMode,
180
188
  buildMoiContext,
181
- threadCfg?.model,
182
- threadCfg?.effort,
183
- threadCfg?.fastMode,
189
+ sessionConfig?.model,
190
+ sessionConfig?.effort,
191
+ sessionConfig?.fastMode,
192
+ selectSession,
184
193
  modelsData
185
194
  ]
186
195
  )
187
196
 
188
197
  const dismissError = useCallback(() => {
189
- if (!activeSessionId) return
190
- liveStore.getState().setError(workspaceId, activeSessionId, null)
191
- }, [activeSessionId, workspaceId])
198
+ if (!selectedSessionId) return
199
+ liveStore.getState().setError(workspaceId, selectedSessionId, null)
200
+ }, [selectedSessionId, workspaceId])
192
201
 
193
202
  const stop = useCallback(() => {
194
- if (!processing || !activeSessionId) return
195
- sendMessage({ type: 'stop', workspaceId, sessionId: activeSessionId })
196
- }, [processing, activeSessionId, workspaceId])
197
-
198
- const switchThread = useCallback(
199
- (sessionId: string | null) => {
200
- liveStore.getState().setActive(workspaceId, sessionId)
201
- },
202
- [workspaceId]
203
- )
203
+ if (!processing || !selectedSessionId) return
204
+ sendMessage({ type: 'stop', workspaceId, sessionId: selectedSessionId })
205
+ }, [processing, selectedSessionId, workspaceId])
204
206
 
205
207
  return {
206
208
  view,
207
209
  chatLoaded,
208
210
  previewTurn,
209
- sessionId: activeSessionId,
211
+ sessionId: selectedSessionId,
210
212
  processing,
211
213
  error,
212
214
  send,
213
215
  stop,
214
- switchThread,
216
+ selectSession,
215
217
  dismissError
216
218
  }
217
219
  }
@@ -0,0 +1,151 @@
1
+ import { useCallback, useMemo } from 'react'
2
+
3
+ import { useIsMutating, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
4
+ import type { QueryClient } from '@tanstack/react-query'
5
+
6
+ import { appUiKeys } from '@/client/api/app-ui-keys'
7
+ import { jsonRequest, requestJson } from '@/client/api/http'
8
+ import { toast } from '@/client/components/ui/toast'
9
+ import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
10
+ import { useWorkspaceEvent } from '@/client/runtime/useWorkspaceEvents'
11
+ import type { SelectedSessionState } from '@/lib/types'
12
+
13
+ type SaveSelectedSessionInput = {
14
+ sessionId: string | null
15
+ previousSessionId: string | null
16
+ }
17
+
18
+ type SetSelectedSession = (sessionId: string | null) => void
19
+
20
+ type SelectedSessionResult = readonly [
21
+ sessionId: string | null | undefined,
22
+ setSessionId: SetSelectedSession
23
+ ]
24
+
25
+ export type SelectedSessionSaveResult = 'applied' | 'conflict' | 'ignored'
26
+
27
+ function selectedSessionMutationKey(workspaceId: string) {
28
+ return [...appUiKeys.selectedSession(workspaceId), 'save'] as const
29
+ }
30
+
31
+ export function optimisticallySetSelectedSession(
32
+ queryClient: QueryClient,
33
+ workspaceId: string,
34
+ sessionId: string | null
35
+ ): SaveSelectedSessionInput | null {
36
+ const queryKey = appUiKeys.selectedSession(workspaceId)
37
+ const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
38
+ const previousSessionId = current?.sessionId ?? null
39
+ if (current && previousSessionId === sessionId) return null
40
+
41
+ queryClient.setQueryData<SelectedSessionState>(queryKey, { sessionId })
42
+ return { sessionId, previousSessionId }
43
+ }
44
+
45
+ export function settleSelectedSessionSave(
46
+ queryClient: QueryClient,
47
+ workspaceId: string,
48
+ saved: SelectedSessionState,
49
+ input: SaveSelectedSessionInput
50
+ ): SelectedSessionSaveResult {
51
+ const queryKey = appUiKeys.selectedSession(workspaceId)
52
+ const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
53
+
54
+ if (saved.sessionId !== input.sessionId && current?.sessionId !== saved.sessionId) {
55
+ return 'conflict'
56
+ }
57
+ if (current?.sessionId !== input.sessionId && current?.sessionId !== input.previousSessionId) {
58
+ return 'ignored'
59
+ }
60
+
61
+ queryClient.setQueryData<SelectedSessionState>(queryKey, saved)
62
+ return 'applied'
63
+ }
64
+
65
+ export function applySelectedSessionEvent(
66
+ queryClient: QueryClient,
67
+ workspaceId: string,
68
+ sessionId: string | null,
69
+ hasPendingSave: boolean
70
+ ): void {
71
+ if (hasPendingSave) return
72
+ queryClient.setQueryData<SelectedSessionState>(appUiKeys.selectedSession(workspaceId), {
73
+ sessionId
74
+ })
75
+ }
76
+
77
+ export function renameSelectedSessionInCache(
78
+ queryClient: QueryClient,
79
+ workspaceId: string,
80
+ from: string,
81
+ to: string
82
+ ): void {
83
+ queryClient.setQueryData<SelectedSessionState>(appUiKeys.selectedSession(workspaceId), current =>
84
+ current?.sessionId === from ? { sessionId: to } : current
85
+ )
86
+ }
87
+
88
+ export function useSelectedSession(): SelectedSessionResult {
89
+ const workspaceId = useWorkspaceId()
90
+ const queryClient = useQueryClient()
91
+ const queryKey = useMemo(() => appUiKeys.selectedSession(workspaceId), [workspaceId])
92
+ const mutationKey = useMemo(() => selectedSessionMutationKey(workspaceId), [workspaceId])
93
+ const pendingSaves = useIsMutating({ mutationKey, exact: true })
94
+
95
+ // WorkspaceLoader remains an observer for the active workspace. Nested hook
96
+ // users reuse its result without refetching; once the route unmounts, dropping
97
+ // the cache makes the next visit load the server-owned selection again.
98
+ const query = useQuery<SelectedSessionState>({
99
+ queryKey,
100
+ queryFn: () => requestJson(`/api/workspaces/${workspaceId}/selected-session`),
101
+ staleTime: Infinity,
102
+ gcTime: 0,
103
+ refetchOnMount: false,
104
+ refetchOnWindowFocus: false
105
+ })
106
+
107
+ const { mutate: saveSelectedSession } = useMutation<
108
+ SelectedSessionState,
109
+ Error,
110
+ SaveSelectedSessionInput
111
+ >({
112
+ mutationKey,
113
+ scope: { id: `selected-session:${workspaceId}` },
114
+ mutationFn: input =>
115
+ requestJson(
116
+ `/api/workspaces/${workspaceId}/selected-session`,
117
+ jsonRequest('PUT', input),
118
+ 'Couldn’t save selected chat'
119
+ ),
120
+ onSuccess: (saved, input) => {
121
+ const result = settleSelectedSessionSave(queryClient, workspaceId, saved, input)
122
+ if (result !== 'conflict') return
123
+
124
+ toast.add({ title: 'Couldn’t save selected chat', type: 'error' })
125
+ queryClient.invalidateQueries({ queryKey })
126
+ },
127
+ onError: (_error, input) => {
128
+ const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
129
+ if (current?.sessionId !== input.sessionId) return
130
+
131
+ toast.add({ title: 'Couldn’t save selected chat', type: 'error' })
132
+ queryClient.invalidateQueries({ queryKey })
133
+ }
134
+ })
135
+
136
+ const setSelectedSessionId = useCallback<SetSelectedSession>(
137
+ sessionId => {
138
+ const input = optimisticallySetSelectedSession(queryClient, workspaceId, sessionId)
139
+ if (input) saveSelectedSession(input)
140
+ },
141
+ [queryClient, saveSelectedSession, workspaceId]
142
+ )
143
+
144
+ useWorkspaceEvent(event => {
145
+ if (event.type !== 'selected-session:updated' || event.workspaceId !== workspaceId) return
146
+ applySelectedSessionEvent(queryClient, workspaceId, event.sessionId, pendingSaves > 0)
147
+ })
148
+
149
+ const selectedSessionId = query.isLoading ? undefined : (query.data?.sessionId ?? null)
150
+ return [selectedSessionId, setSelectedSessionId]
151
+ }
@@ -7,7 +7,7 @@ import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useSta
7
7
  // they read history.
8
8
  // • Re-pin automatically when they scroll back to (near) the bottom.
9
9
  // • `scrollToBottom()` for the "jump to latest" button and for send.
10
- // • On mount and whenever `resetKey` changes (thread switch), jump to bottom.
10
+ // • On mount and whenever `resetKey` changes (session switch), jump to bottom.
11
11
  //
12
12
  // Content growth is followed via a ResizeObserver on the scroll content, so we
13
13
  // don't depend on React deps to know when to scroll — it just works for any
@@ -85,8 +85,8 @@ export function useStickToBottom(
85
85
  return () => ro.disconnect()
86
86
  }, [scrollRef])
87
87
 
88
- // Jump to bottom on mount and on thread switch (before paint, so no flash).
89
- // If the new thread's content is still loading, the ResizeObserver above lands
88
+ // Jump to bottom on mount and on session switch (before paint, so no flash).
89
+ // If the new session's content is still loading, the ResizeObserver above lands
90
90
  // us at the bottom once it arrives (pin is set here).
91
91
  useLayoutEffect(() => {
92
92
  scrollToBottom('auto')
@@ -2,7 +2,6 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
2
2
 
3
3
  import { jsonRequest, requestJson, requestVoid } from '@/client/api/http'
4
4
  import { workspaceKeys } from '@/client/api/workspace-keys'
5
- import { liveStore } from '@/client/features/chat/chat-store'
6
5
  import { useUiStore } from '@/client/store/ui'
7
6
  import type {
8
7
  DiscoveredWorkspace,
@@ -52,7 +51,6 @@ export function useImportWorkspace() {
52
51
  mutationFn: input =>
53
52
  requestJson('/api/workspaces', jsonRequest('POST', input), 'Failed to add workspace'),
54
53
  onSuccess: (entry, input) => {
55
- liveStore.getState().setActive(entry.id, null)
56
54
  useUiStore.getState().markWorkspacePendingAnalysis(entry.id)
57
55
  queryClient.setQueryData<WorkspaceEntry[]>(workspaceKeys.all, previous =>
58
56
  upsertWorkspaceEntry(previous, entry)
@@ -148,7 +148,7 @@ export function ScratchToolbar({ editor }: ScratchToolbarProps) {
148
148
  }
149
149
 
150
150
  return (
151
- <div className="absolute top-1/2 left-2 z-10 -translate-y-1/2">
151
+ <div className="absolute top-1/2 left-2 -translate-y-1/2">
152
152
  <motion.div
153
153
  initial={{ x: -72, opacity: 0 }}
154
154
  animate={{ x: 0, opacity: 1 }}
@@ -491,7 +491,7 @@ export function ScratchStyleBar({ editor }: ScratchStyleBarProps) {
491
491
  }
492
492
 
493
493
  return (
494
- <div className="absolute top-1/2 left-14 z-10 flex -translate-y-1/2 flex-col items-center gap-1.5 rounded-full bg-background/95 px-1 py-1 shadow-[0_2px_8px_rgba(0,0,0,0.08),0_4px_16px_rgba(0,0,0,0.06),0_0_0_1px_rgba(0,0,0,0.04)] backdrop-blur">
494
+ <div className="absolute top-1/2 left-14 flex -translate-y-1/2 flex-col items-center gap-1.5 rounded-full bg-background/95 px-1 py-1 shadow-[0_2px_8px_rgba(0,0,0,0.08),0_4px_16px_rgba(0,0,0,0.06),0_0_0_1px_rgba(0,0,0,0.04)] backdrop-blur">
495
495
  {state.controls.map((control, i) => (
496
496
  <Fragment key={control}>
497
497
  {i > 0 && <div className="h-px w-5 bg-border" />}
@@ -67,23 +67,23 @@ export function WorkspaceSettings() {
67
67
 
68
68
  {/* Page */}
69
69
  <div className="relative scrollbar-thin min-w-0 flex-1 overflow-y-auto">
70
+ <div className="px-8 py-7">
71
+ {page === 'general' && <GeneralSettings />}
72
+ {page === 'connectors' && <ConnectorsSettings />}
73
+ {page === 'environment' && <EnvironmentSettings />}
74
+ </div>
70
75
  <DialogClose
71
76
  render={
72
77
  <Button
73
78
  variant="ghost"
74
79
  size="icon"
75
80
  aria-label="Close"
76
- className="absolute top-3 right-3 z-10"
81
+ className="absolute top-3 right-3"
77
82
  >
78
83
  <IconX stroke={1.5} />
79
84
  </Button>
80
85
  }
81
86
  />
82
- <div className="px-8 py-7">
83
- {page === 'general' && <GeneralSettings />}
84
- {page === 'connectors' && <ConnectorsSettings />}
85
- {page === 'environment' && <EnvironmentSettings />}
86
- </div>
87
87
  </div>
88
88
  </DialogContent>
89
89
  </Dialog>
@@ -1,7 +1,5 @@
1
1
  import { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from 'react'
2
2
 
3
- import { IconLoader2 } from '@tabler/icons-react'
4
-
5
3
  import { Button } from '@/client/components/ui/button'
6
4
  import {
7
5
  canSubmitComposerAction,
@@ -12,6 +10,7 @@ import {
12
10
  } from '@/client/components/shared/Composer'
13
11
  import { ModelPicker } from '@/client/features/chat/ModelPicker'
14
12
  import type { ViewBuilder } from '@/lib/types'
13
+ import { Spinner } from '@/client/components/ui/spinner'
15
14
 
16
15
  type ViewBuilderTabProps = {
17
16
  builder: ViewBuilder
@@ -144,8 +143,8 @@ export function ViewBuilderTab({
144
143
  return (
145
144
  <div className="flex min-h-0 flex-1 items-center justify-center p-6">
146
145
  <div className="flex items-center gap-2 text-sm text-muted-foreground">
147
- <IconLoader2 stroke={1.75} className="animate-spin" />
148
- {builder.status === 'ready' ? 'Opening view…' : 'Building your view…'}
146
+ <Spinner />
147
+ {builder.status === 'ready' ? 'Opening view…' : 'Building view…'}
149
148
  </div>
150
149
  </div>
151
150
  )
@@ -3,6 +3,7 @@ import { useQueryClient } from '@tanstack/react-query'
3
3
  import { useWorkspaceModels } from '@/client/features/chat/api'
4
4
  import { resolveChatRunOptions, startOptimisticTurn } from '@/client/features/chat/chat-send'
5
5
  import { liveStore } from '@/client/features/chat/chat-store'
6
+ import { useSelectedSession } from '@/client/features/chat/useSelectedSession'
6
7
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
7
8
  import {
8
9
  useCreateViewBuilder,
@@ -15,6 +16,7 @@ import type { ViewBuilder } from '@/lib/types'
15
16
  export function useViewBuilderActions() {
16
17
  const queryClient = useQueryClient()
17
18
  const { workspaceId, layout } = useWorkspaceLayoutCtx()
19
+ const [, selectSession] = useSelectedSession()
18
20
  const modelData = useWorkspaceModels(workspaceId).data
19
21
  const createMutation = useCreateViewBuilder(workspaceId)
20
22
  const saveMutation = useSaveViewBuilder(workspaceId)
@@ -36,7 +38,7 @@ export function useViewBuilderActions() {
36
38
  sessionId: builder.sessionId,
37
39
  parts: [{ type: 'text', text }]
38
40
  })
39
- liveStore.getState().setActive(workspaceId, builder.sessionId)
41
+ selectSession(builder.sessionId)
40
42
 
41
43
  const { model, effort, fastMode, stream } = resolveChatRunOptions(
42
44
  modelData,