moi-computer 0.5.2-next.0 → 0.6.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 (89) hide show
  1. package/client/AGENTS.md +9 -0
  2. package/client/api/app-ui-keys.ts +4 -0
  3. package/client/api/workspace-keys.ts +2 -2
  4. package/client/app/routes/WorkspaceRoute.tsx +8 -28
  5. package/client/app/shell/SidebarLayout.tsx +1 -1
  6. package/client/components/shared/Composer.tsx +15 -9
  7. package/client/components/shared/IconGhost.tsx +130 -0
  8. package/client/components/ui/dropdown-menu.tsx +2 -5
  9. package/client/components/ui/popover.tsx +11 -4
  10. package/client/components/ui/slider.tsx +70 -0
  11. package/client/components/ui/spinner.tsx +18 -0
  12. package/client/components/ui/toast.tsx +220 -0
  13. package/client/components/ui/tooltip.tsx +1 -1
  14. package/client/features/chat/ChatComposer.tsx +11 -14
  15. package/client/features/chat/ChatPanel.tsx +15 -14
  16. package/client/features/chat/ChatPopup.tsx +10 -4
  17. package/client/features/chat/ChatSelector.tsx +263 -48
  18. package/client/features/chat/ModelPicker.tsx +295 -121
  19. package/client/features/chat/TurnView.tsx +1 -1
  20. package/client/features/chat/api.ts +36 -9
  21. package/client/features/chat/chat-frames.ts +35 -6
  22. package/client/features/chat/chat-send.ts +40 -6
  23. package/client/features/chat/chat-store.ts +52 -40
  24. package/client/features/chat/model-order.ts +50 -28
  25. package/client/features/chat/useChat.ts +71 -60
  26. package/client/features/chat/useSelectedSession.ts +151 -0
  27. package/client/features/chat/useStickToBottom.ts +3 -3
  28. package/client/features/home/api.ts +0 -2
  29. package/client/features/scratchpad/ScratchpadControls.tsx +2 -2
  30. package/client/features/settings/IconPicker.tsx +2 -2
  31. package/client/features/settings/WorkspaceSettings.tsx +6 -6
  32. package/client/features/views/ViewBuilderTab.tsx +3 -4
  33. package/client/features/views/api.ts +1 -0
  34. package/client/features/views/useViewBuilderActions.ts +7 -3
  35. package/client/features/workspace/WorkspaceScreen.tsx +40 -19
  36. package/client/features/workspace/WorkspaceSkillUpdateBanner.tsx +2 -2
  37. package/client/features/workspace/WorkspaceTabs.tsx +10 -1
  38. package/client/index.css +5 -3
  39. package/client/main.tsx +2 -0
  40. package/client/runtime/useWorkspaceEvents.ts +1 -0
  41. package/client/store/ui.ts +13 -3
  42. package/dist/{chunk-m9qja0nx.js → chunk-0pcdwjkp.js} +1 -1
  43. package/dist/chunk-55sh4dty.js +2 -0
  44. package/dist/{chunk-h3evrtyp.js → chunk-9y2zbzqz.js} +1 -1
  45. package/dist/{chunk-7bzpmtxp.js → chunk-afgbg75t.js} +1 -1
  46. package/dist/chunk-agtetn7n.css +1 -0
  47. package/dist/chunk-bv6vrvqf.js +27 -0
  48. package/dist/chunk-dfs36zgc.js +1 -0
  49. package/dist/chunk-exj6hr30.js +9 -0
  50. package/dist/{chunk-v797g6ap.js → chunk-m11ckkxd.js} +1 -1
  51. package/dist/chunk-n6t40enm.js +1 -0
  52. package/dist/{chunk-jg6ezptn.js → chunk-rxvx4ta9.js} +3 -3
  53. package/dist/index.html +1 -1
  54. package/lib/attachment-note.ts +18 -0
  55. package/lib/chat-title.ts +6 -0
  56. package/lib/types.ts +33 -10
  57. package/package.json +1 -1
  58. package/server/api.ts +100 -10
  59. package/server/app-settings.ts +1 -1
  60. package/server/data-dir.ts +1 -1
  61. package/server/harness/README.md +6 -0
  62. package/server/harness/claude-code/adapter.ts +2 -2
  63. package/server/harness/claude-code/index.ts +7 -1
  64. package/server/harness/claude-code/models.ts +25 -2
  65. package/server/harness/claude-code/session-title.ts +106 -0
  66. package/server/harness/claude-code/session.ts +114 -17
  67. package/server/harness/claude-code/sessions.ts +35 -4
  68. package/server/harness/codex/adapter.ts +27 -2
  69. package/server/harness/codex/client.ts +56 -9
  70. package/server/harness/codex/index.ts +2 -0
  71. package/server/harness/codex/session-title.ts +149 -0
  72. package/server/harness/codex/session.ts +96 -14
  73. package/server/harness/openclaw/adapter.ts +4 -2
  74. package/server/harness/openclaw/discovery.ts +2 -0
  75. package/server/harness/openclaw/session.ts +15 -7
  76. package/server/harness/session-title.ts +96 -0
  77. package/server/harness/types.ts +5 -2
  78. package/server/selected-session.ts +132 -0
  79. package/server/session-config.ts +146 -0
  80. package/server/web.ts +15 -1
  81. package/workspace/.claude/skills/moi-workspace/DESIGN.md +54 -68
  82. package/workspace/.claude/skills/moi-workspace/SKILL.md +8 -2
  83. package/dist/chunk-5vaevt8z.js +0 -2
  84. package/dist/chunk-fhhv99bd.js +0 -1
  85. package/dist/chunk-h0hk61pm.js +0 -9
  86. package/dist/chunk-k5sjx9s5.js +0 -1
  87. package/dist/chunk-rs9nb0fr.js +0 -27
  88. package/dist/chunk-s7za1qsv.css +0 -1
  89. package/server/thread-config.ts +0 -124
@@ -1,11 +1,12 @@
1
1
  import type { QueryClient } from '@tanstack/react-query'
2
2
 
3
3
  import { workspaceKeys } from '@/client/api/workspace-keys'
4
- import { type ChatAttachment, draftKey, liveStore } from '@/client/features/chat/chat-store'
4
+ import { attachmentKey, type ChatAttachment, liveStore } from '@/client/features/chat/chat-store'
5
5
  import type { MoiUserMessageOptions } from '@/client/features/workspace/moi-context'
6
6
  import { STREAM_RESPONSES } from '@/client/lib/flags'
7
+ import { formatChatTitle } from '@/lib/chat-title'
7
8
  import { applyEvent, emptyViewState } from '@/lib/format'
8
- import type { Part, ViewState, WorkspaceModels } from '@/lib/types'
9
+ import type { Part, SessionInfo, ViewState, WorkspaceModels } from '@/lib/types'
9
10
 
10
11
  // What a caller may attach to one message beyond its text. All of it is
11
12
  // envelope material — the agent sees it, the chat bubble does not.
@@ -27,7 +28,7 @@ export function attachmentsForSend(
27
28
  options?: ChatSendOptions
28
29
  ): ChatAttachment[] {
29
30
  if (!ownsComposerAttachments(options)) return []
30
- const pending = liveStore.getState().attachments[draftKey(workspaceId, sessionId)] ?? []
31
+ const pending = liveStore.getState().attachments[attachmentKey(workspaceId, sessionId)] ?? []
31
32
  return pending.filter(a => a.status === 'ready' && a.upload)
32
33
  }
33
34
 
@@ -62,11 +63,35 @@ export function startOptimisticTurn({
62
63
  return optimisticId
63
64
  }
64
65
 
66
+ type StartOptimisticSessionInput = {
67
+ queryClient: QueryClient
68
+ workspaceId: string
69
+ sessionId: string
70
+ text: string
71
+ filenames?: readonly string[]
72
+ }
73
+
74
+ export function startOptimisticSession({
75
+ queryClient,
76
+ workspaceId,
77
+ sessionId,
78
+ text,
79
+ filenames = []
80
+ }: StartOptimisticSessionInput): void {
81
+ const summary = formatChatTitle(text, filenames)
82
+ if (!summary) return
83
+ queryClient.setQueryData<SessionInfo[]>(workspaceKeys.sessions(workspaceId), current => [
84
+ { sessionId, summary, lastModified: Date.now() },
85
+ ...(current ?? []).filter(session => session.sessionId !== sessionId)
86
+ ])
87
+ }
88
+
65
89
  export function resolveChatRunOptions(
66
90
  modelsData: WorkspaceModels | undefined,
67
91
  pickedModel: string | undefined,
68
- pickedEffort: string | undefined
69
- ): { model?: string; effort?: string; stream?: true } {
92
+ pickedEffort: string | undefined,
93
+ pickedFastMode?: boolean
94
+ ): { model?: string; effort?: string; fastMode?: boolean; stream?: true } {
70
95
  const models = modelsData?.models
71
96
  const model =
72
97
  !pickedModel || !models || models.some(candidate => candidate.value === pickedModel)
@@ -77,6 +102,15 @@ export function resolveChatRunOptions(
77
102
  pickedEffort && (!modelInfo || (modelInfo.supportedEffortLevels ?? []).includes(pickedEffort))
78
103
  ? pickedEffort
79
104
  : undefined
105
+ const fastMode =
106
+ pickedFastMode === undefined || !modelInfo || modelInfo.supportsFastMode
107
+ ? pickedFastMode
108
+ : false
80
109
  const stream = STREAM_RESPONSES && modelsData?.supportsStreaming ? true : undefined
81
- return { model, effort, stream }
110
+ return {
111
+ model,
112
+ effort,
113
+ ...(fastMode !== undefined ? { fastMode } : {}),
114
+ stream
115
+ }
82
116
  }
@@ -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,11 +33,46 @@ function key(workspaceId: string, sessionId: string): string {
35
33
  return `${workspaceId}:${sessionId}`
36
34
  }
37
35
 
38
- // Draft text is keyed per thread. A brand-new chat has no session id yet, so it
39
- // gets a stable `'new'` sentinel; once `send` mints the real id the input reads
40
- // the (empty) draft under the new key. Exported so `ChatInput` builds the same
41
- // key it reads as the store writes.
42
- export function draftKey(workspaceId: string, sessionId: string | null): string {
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
+
73
+ // Attachments stay with the chat they were added to. A brand-new chat has no
74
+ // session id yet, so it gets a stable `'new'` sentinel until send mints one.
75
+ export function attachmentKey(workspaceId: string, sessionId: string | null): string {
43
76
  return key(workspaceId, sessionId ?? 'new')
44
77
  }
45
78
 
@@ -55,7 +88,6 @@ export type LivePreview = {
55
88
  }
56
89
 
57
90
  export type LiveStore = {
58
- activeByWorkspace: Record<string, string | null>
59
91
  // Per-session activity mirrored from server `status` frames. Only `running`
60
92
  // shows the loader/Stop; `requires-action` is tracked but not rendered yet.
61
93
  // Missing key = idle.
@@ -65,17 +97,10 @@ export type LiveStore = {
65
97
  // so concurrent streams never collide. Reconciled against the durable
66
98
  // transcript: a preview is dropped the instant its finalized turn arrives.
67
99
  previews: Record<string, LivePreview>
68
- // Unsent composer text, keyed per thread (`${workspaceId}:${sessionId}`, with
69
- // a `'new'` sentinel for a not-yet-created thread). Lives here — not in the
70
- // chat component — so a keystroke re-renders only the composer (which alone
71
- // subscribes), not the whole workspace, and the draft survives the chat
72
- // panel's remounts on mode switch.
73
- drafts: Record<string, string>
74
- // Composer attachments, keyed per thread exactly like `drafts` (so they follow
75
- // the active thread and survive composer remounts). Cleared on send.
100
+ // Composer attachments are per chat, survive composer remounts, and clear on
101
+ // send. Draft text is workspace-local persisted UI state (client/store/ui).
76
102
  attachments: Record<string, ChatAttachment[]>
77
103
 
78
- setActive: (workspaceId: string, sessionId: string | null) => void
79
104
  setActivity: (workspaceId: string, sessionId: string, value: SessionActivity) => void
80
105
  // Authoritative reconcile from a server `status_snapshot`: exactly the listed
81
106
  // sessions are active; everything else is cleared to idle (fixes a spinner
@@ -84,7 +109,6 @@ export type LiveStore = {
84
109
  sessions: { workspaceId: string; sessionId: string; activity: SessionActivity }[]
85
110
  ) => void
86
111
  setError: (workspaceId: string, sessionId: string, message: string | null) => void
87
- setDraft: (workspaceId: string, sessionId: string | null, value: string) => void
88
112
  addAttachments: (workspaceId: string, sessionId: string | null, items: ChatAttachment[]) => void
89
113
  updateAttachment: (
90
114
  workspaceId: string,
@@ -111,16 +135,11 @@ export type LiveStore = {
111
135
  }
112
136
 
113
137
  export const liveStore = createStore<LiveStore>()(set => ({
114
- activeByWorkspace: {},
115
138
  activity: {},
116
139
  errors: {},
117
- drafts: {},
118
140
  previews: {},
119
141
  attachments: {},
120
142
 
121
- setActive: (workspaceId, sessionId) =>
122
- set(s => ({ activeByWorkspace: { ...s.activeByWorkspace, [workspaceId]: sessionId } })),
123
-
124
143
  setActivity: (workspaceId, sessionId, value) =>
125
144
  set(s => ({ activity: { ...s.activity, [key(workspaceId, sessionId)]: value } })),
126
145
 
@@ -132,9 +151,6 @@ export const liveStore = createStore<LiveStore>()(set => ({
132
151
  setError: (workspaceId, sessionId, message) =>
133
152
  set(s => ({ errors: { ...s.errors, [key(workspaceId, sessionId)]: message } })),
134
153
 
135
- setDraft: (workspaceId, sessionId, value) =>
136
- set(s => ({ drafts: { ...s.drafts, [draftKey(workspaceId, sessionId)]: value } })),
137
-
138
154
  setPreview: frame =>
139
155
  set(s => ({
140
156
  previews: {
@@ -182,13 +198,13 @@ export const liveStore = createStore<LiveStore>()(set => ({
182
198
 
183
199
  addAttachments: (workspaceId, sessionId, items) =>
184
200
  set(s => {
185
- const k = draftKey(workspaceId, sessionId)
201
+ const k = attachmentKey(workspaceId, sessionId)
186
202
  return { attachments: { ...s.attachments, [k]: [...(s.attachments[k] ?? []), ...items] } }
187
203
  }),
188
204
 
189
205
  updateAttachment: (workspaceId, sessionId, localId, patch) =>
190
206
  set(s => {
191
- const k = draftKey(workspaceId, sessionId)
207
+ const k = attachmentKey(workspaceId, sessionId)
192
208
  const list = s.attachments[k]
193
209
  if (!list) return {}
194
210
  return {
@@ -201,7 +217,7 @@ export const liveStore = createStore<LiveStore>()(set => ({
201
217
 
202
218
  removeAttachment: (workspaceId, sessionId, localId) =>
203
219
  set(s => {
204
- const k = draftKey(workspaceId, sessionId)
220
+ const k = attachmentKey(workspaceId, sessionId)
205
221
  const list = s.attachments[k]
206
222
  if (!list) return {}
207
223
  const target = list.find(a => a.localId === localId)
@@ -211,7 +227,7 @@ export const liveStore = createStore<LiveStore>()(set => ({
211
227
 
212
228
  clearAttachments: (workspaceId, sessionId) =>
213
229
  set(s => {
214
- const k = draftKey(workspaceId, sessionId)
230
+ const k = attachmentKey(workspaceId, sessionId)
215
231
  for (const a of s.attachments[k] ?? []) {
216
232
  if (a.previewUrl) URL.revokeObjectURL(a.previewUrl)
217
233
  }
@@ -234,12 +250,8 @@ export const liveStore = createStore<LiveStore>()(set => ({
234
250
  errors[toKey] = errors[fromKey]
235
251
  delete errors[fromKey]
236
252
  }
237
- const activeByWorkspace =
238
- s.activeByWorkspace[workspaceId] === from
239
- ? { ...s.activeByWorkspace, [workspaceId]: to }
240
- : s.activeByWorkspace
241
253
  // Retarget any in-flight previews from the temp id to the real one so a
242
- // preview that arrived before the rename keeps routing to the thread.
254
+ // preview that arrived before the rename keeps routing to the session.
243
255
  let previews = s.previews
244
256
  let previewsChanged = false
245
257
  for (const [id, p] of Object.entries(s.previews)) {
@@ -251,11 +263,11 @@ export const liveStore = createStore<LiveStore>()(set => ({
251
263
  previews[id] = { ...p, sessionId: to }
252
264
  }
253
265
  }
254
- return { activity, errors, activeByWorkspace, previews }
266
+ return { activity, errors, previews }
255
267
  })
256
268
  }))
257
269
 
258
- // 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
259
271
  // assistant) stream and per-subagent streams. Takes the raw `previews` record
260
272
  // (a stable store slice) so callers select that slice and run this inside a
261
273
  // `useMemo` — never return a fresh object straight from a zustand selector.
@@ -2,24 +2,39 @@ import type { Model, WorkspaceType } from '@/lib/types'
2
2
 
3
3
  export const DEFAULT_EFFORT = 'high'
4
4
 
5
- export const MODEL_ORDER = {
6
- 'claude-code': [
7
- 'claude-fable-5',
8
- 'claude-opus-4-8',
9
- 'claude-opus-4-8[1m]',
10
- 'claude-sonnet-5',
11
- 'claude-haiku-4-5-20251001'
12
- ],
13
- codex: [],
14
- openclaw: []
15
- } as const satisfies Record<WorkspaceType, readonly string[]>
5
+ const ANTHROPIC_MODEL_FAMILY_ORDER = ['fable', 'opus', 'sonnet', 'haiku'] as const
16
6
 
17
- function modelOrderKey(model: Model): string {
18
- return model.resolvedModel ?? model.value
7
+ type ModelComparator = (a: Model, b: Model) => number
8
+
9
+ function anthropicModelFamilyRank(model: Model): number | undefined {
10
+ const key = model.resolvedModel ?? model.value
11
+ const rank = ANTHROPIC_MODEL_FAMILY_ORDER.findIndex(
12
+ family => key === family || key.startsWith(`${family}[`) || key.includes(`-${family}-`)
13
+ )
14
+
15
+ return rank === -1 ? undefined : rank
16
+ }
17
+
18
+ function compareOptionalRanks(a: number | undefined, b: number | undefined): number {
19
+ if (a === undefined && b === undefined) return 0
20
+ if (a === undefined) return -1
21
+ if (b === undefined) return 1
22
+ return a - b
23
+ }
24
+
25
+ function compareAnthropicModels(a: Model, b: Model): number {
26
+ return compareOptionalRanks(anthropicModelFamilyRank(a), anthropicModelFamilyRank(b))
19
27
  }
20
28
 
21
- export function reverseEffortLevels(levels: readonly string[]): string[] {
22
- return [...levels].reverse()
29
+ const PROVIDER_MODEL_COMPARATORS: Partial<Record<WorkspaceType, ModelComparator>> = {
30
+ 'claude-code': compareAnthropicModels
31
+ }
32
+
33
+ function stableSortModels(models: Model[], compare: ModelComparator): Model[] {
34
+ return models
35
+ .map((model, index) => ({ model, index }))
36
+ .sort((a, b) => compare(a.model, b.model) || a.index - b.index)
37
+ .map(({ model }) => model)
23
38
  }
24
39
 
25
40
  export function resolveDisplayedEffort(
@@ -28,20 +43,27 @@ export function resolveDisplayedEffort(
28
43
  ): string | undefined {
29
44
  if (selectedEffort && levels.includes(selectedEffort)) return selectedEffort
30
45
  if (levels.includes(DEFAULT_EFFORT)) return DEFAULT_EFFORT
31
- return levels[0]
46
+ return levels[levels.length - 1]
32
47
  }
33
48
 
34
- export function sortModelsByProviderOrder(models: Model[], provider: WorkspaceType): Model[] {
35
- const configuredOrder: readonly string[] = MODEL_ORDER[provider]
36
- const rank = new Map<string, number>(configuredOrder.map((model, index) => [model, index]))
49
+ export function resolveEffortIndex(
50
+ levels: readonly string[],
51
+ selectedEffort: string | undefined
52
+ ): number {
53
+ const displayedEffort = resolveDisplayedEffort(levels, selectedEffort)
54
+ return displayedEffort ? levels.indexOf(displayedEffort) : -1
55
+ }
37
56
 
38
- return models
39
- .map((model, index) => ({ model, index, rank: rank.get(modelOrderKey(model)) }))
40
- .sort((a, b) => {
41
- if (a.rank === undefined && b.rank === undefined) return a.index - b.index
42
- if (a.rank === undefined) return -1
43
- if (b.rank === undefined) return 1
44
- return a.rank - b.rank || a.index - b.index
45
- })
46
- .map(({ model }) => model)
57
+ export function hasEffortChoice(levels: readonly string[]): boolean {
58
+ return levels.length > 1
59
+ }
60
+
61
+ export function resolveFastMode(model: Model, selectedFastMode: boolean | undefined): boolean {
62
+ if (model.supportsFastMode !== true) return false
63
+ return selectedFastMode ?? model.defaultFastMode ?? false
64
+ }
65
+
66
+ export function sortModelsByProviderOrder(models: Model[], provider: WorkspaceType): Model[] {
67
+ const compare = PROVIDER_MODEL_COMPARATORS[provider]
68
+ return compare ? stableSortModels(models, compare) : models
47
69
  }
@@ -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,35 +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
- // The composer owns the draft (in the live store) and hands the text in, so a
90
- // keystroke re-renders only the composer — not this hook's host (WorkspaceView)
91
- // and its whole subtree. See `ChatInput`.
90
+ // The composer owns the workspace draft in the persisted UI store and hands
91
+ // the text in, so a keystroke re-renders only the composer.
92
92
  const send = useCallback(
93
93
  (draft: string, options?: ChatSendOptions) => {
94
94
  const text = draft.trim()
95
- // Attachments for the active thread, keyed exactly like the draft. Only
96
- // fully-uploaded ones are sent; the composer disables send while any are
97
- // still uploading, so in practice they're all ready here. An applet send
98
- // gets none — the staged files are the user's, not the widget's.
99
- const ready = attachmentsForSend(workspaceId, activeSessionId, options)
95
+ // Attachments stay with the selected session. Only fully-uploaded ones are
96
+ // sent; the composer disables send while any are still uploading, so in
97
+ // practice they're all ready here. An applet send gets none — the staged
98
+ // files are the user's, not the widget's.
99
+ const ready = attachmentsForSend(workspaceId, selectedSessionId, options)
100
100
  // No `processing` guard: sending while a turn is in flight QUEUES the
101
101
  // message into the same live server session (streaming-input mode).
102
102
  if (!text && ready.length === 0) return
103
103
 
104
- let sid = activeSessionId
104
+ let sid = selectedSessionId
105
105
  let isNew = false
106
106
  if (!sid) {
107
107
  sid = crypto.randomUUID()
108
108
  isNew = true
109
- 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
+ })
110
117
  }
111
118
 
112
119
  // Optimistic user turn — primed into the RQ transcript cache so it renders
@@ -130,14 +137,21 @@ export function useChat(address: WorkspaceTabAddress) {
130
137
  parts
131
138
  })
132
139
 
133
- // 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
134
141
  // model the loaded list no longer offers (stale alias) so the SDK doesn't
135
- // reject model_not_found. Drop an effort the resolved model doesn't support
136
- // (e.g. model changed under it); when the model is unknown/default we can't
137
- // check, so pass it through — the SDK silently downgrades unsupported effort.
138
- const pickedModel = threadCfg?.model ?? layout.selectedModel
139
- const pickedEffort = threadCfg?.effort ?? layout.selectedEffort
140
- const { model, effort, stream } = resolveChatRunOptions(modelsData, pickedModel, pickedEffort)
142
+ // reject model_not_found. Drop an effort the resolved model doesn't
143
+ // support and explicitly disable Fast mode on a known unsupported model.
144
+ // When the model is unknown/default we can't validate either capability,
145
+ // so pass the stored choices through.
146
+ const pickedModel = sessionConfig?.model ?? layout.selectedModel
147
+ const pickedEffort = sessionConfig?.effort ?? layout.selectedEffort
148
+ const pickedFastMode = sessionConfig?.fastMode ?? layout.selectedFastMode
149
+ const { model, effort, fastMode, stream } = resolveChatRunOptions(
150
+ modelsData,
151
+ pickedModel,
152
+ pickedEffort,
153
+ pickedFastMode
154
+ )
141
155
  sendMessage({
142
156
  type: 'chat',
143
157
  workspaceId,
@@ -147,6 +161,7 @@ export function useChat(address: WorkspaceTabAddress) {
147
161
  optimisticId,
148
162
  model,
149
163
  effort,
164
+ fastMode,
150
165
  stream,
151
166
  context: buildMoiContext(options),
152
167
  ...(ready.length > 0 ? { attachments: ready.map(a => a.upload!.id) } : {})
@@ -155,54 +170,50 @@ export function useChat(address: WorkspaceTabAddress) {
155
170
  if (isNew) {
156
171
  qc.invalidateQueries({ queryKey: workspaceKeys.preview(workspaceId) })
157
172
  }
158
- // 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
159
174
  // preview object URLs). Keyed by the pre-mint id, matching where they were
160
175
  // stored by the composer. Skipped for an applet send, which carried none:
161
176
  // clearing here would discard the user's staged (and in-flight) files.
162
177
  if (ownsComposerAttachments(options)) {
163
- liveStore.getState().clearAttachments(workspaceId, activeSessionId)
178
+ liveStore.getState().clearAttachments(workspaceId, selectedSessionId)
164
179
  }
165
180
  },
166
181
  [
167
- activeSessionId,
182
+ selectedSessionId,
168
183
  workspaceId,
169
184
  qc,
170
185
  layout.selectedModel,
171
186
  layout.selectedEffort,
187
+ layout.selectedFastMode,
172
188
  buildMoiContext,
173
- threadCfg?.model,
174
- threadCfg?.effort,
189
+ sessionConfig?.model,
190
+ sessionConfig?.effort,
191
+ sessionConfig?.fastMode,
192
+ selectSession,
175
193
  modelsData
176
194
  ]
177
195
  )
178
196
 
179
197
  const dismissError = useCallback(() => {
180
- if (!activeSessionId) return
181
- liveStore.getState().setError(workspaceId, activeSessionId, null)
182
- }, [activeSessionId, workspaceId])
198
+ if (!selectedSessionId) return
199
+ liveStore.getState().setError(workspaceId, selectedSessionId, null)
200
+ }, [selectedSessionId, workspaceId])
183
201
 
184
202
  const stop = useCallback(() => {
185
- if (!processing || !activeSessionId) return
186
- sendMessage({ type: 'stop', workspaceId, sessionId: activeSessionId })
187
- }, [processing, activeSessionId, workspaceId])
188
-
189
- const switchThread = useCallback(
190
- (sessionId: string | null) => {
191
- liveStore.getState().setActive(workspaceId, sessionId)
192
- },
193
- [workspaceId]
194
- )
203
+ if (!processing || !selectedSessionId) return
204
+ sendMessage({ type: 'stop', workspaceId, sessionId: selectedSessionId })
205
+ }, [processing, selectedSessionId, workspaceId])
195
206
 
196
207
  return {
197
208
  view,
198
209
  chatLoaded,
199
210
  previewTurn,
200
- sessionId: activeSessionId,
211
+ sessionId: selectedSessionId,
201
212
  processing,
202
213
  error,
203
214
  send,
204
215
  stop,
205
- switchThread,
216
+ selectSession,
206
217
  dismissError
207
218
  }
208
219
  }