The best way to control Claude Code, Codex and more from any computer or phone

main
ts 4,888 lines 191 KB
Raw
1 import {
2 composerFileAttachmentMimeType,
3 composerImageDedupKey,
4 rememberComposerImageBytes,
5 } from "./components/chat/composerAttachmentFiles";
6 import { elementContextToPreviewAnnotation } from "./lib/elementContext";
7 import {
8 ResponseContextRecord,
9 ElementContextDetails,
10 DEFAULT_MODEL,
11 DEFAULT_MODEL_BY_PROVIDER,
12 defaultInstanceIdForDriver,
13 EnvironmentId,
14 ModelSelection,
15 ProjectId,
16 ProviderInstanceId,
17 ProviderInteractionMode,
18 ProviderDriverKind,
19 ProviderOptionSelection,
20 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
21 ProviderOptionSelections,
22 PreviewAnnotationPayloadSchema,
23 PastedTextAttachmentSource,
24 type PreviewAnnotationPayload,
25 RuntimeMode,
26 ThreadContextRecord,
27 EnvironmentContextRecord,
28 type ServerProvider,
29 type ScopedProjectRef,
30 type ScopedThreadRef,
31 ThreadId,
32 SnapShotSource,
33 } from "@t3tools/contracts";
34 import {
35 parseScopedProjectKey,
36 parseScopedThreadKey,
37 scopedProjectKey,
38 scopeProjectRef,
39 scopedThreadKey,
40 scopeThreadRef,
41 } from "@t3tools/client-runtime/environment";
42 import * as Schema from "effect/Schema";
43 import * as Equal from "effect/Equal";
44 import * as Effect from "effect/Effect";
45 import { DeepMutable } from "effect/Types";
46 import {
47 createModelSelection,
48 draftModelPickMatchesThread,
49 normalizeCustomModelSlug,
50 normalizeModelSlug,
51 } from "@t3tools/shared/model";
52 import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
53 import * as Option from "effect/Option";
54 import type {
55 EnvironmentShellState,
56 EnvironmentThreadShell,
57 } from "@t3tools/client-runtime/state/shell";
58 import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition";
59 import { getLocalStorageItem } from "./hooks/useLocalStorage";
60 import { readThreadPreviewState } from "./previewStateStore";
61 import {
62 readInstanceCustomModels,
63 resolveAppModelSelection,
64 resolveAppModelSelectionForInstance,
65 } from "./modelSelection";
66 import {
67 DEFAULT_INTERACTION_MODE,
68 DEFAULT_RUNTIME_MODE,
69 type ChatFileAttachment,
70 type ChatImageAttachment,
71 videoMimeType,
72 } from "./types";
73 import {
74 type TerminalContextDraft,
75 migrateLegacyTerminalContextPlaceholders,
76 normalizeTerminalContextText,
77 } from "./lib/terminalContext";
78 import {
79 appendInlineContextReference,
80 type ComposerContextReference,
81 ensureInlineContextReferences,
82 formatInlineContextReference,
83 removeInlineContextReference,
84 } from "./lib/composerContextReferences";
85 import {
86 fileContextReference,
87 previewAnnotationContextId,
88 previewAnnotationContextReference,
89 reviewCommentContextId,
90 reviewCommentContextReference,
91 terminalContextReference,
92 threadContextReference,
93 environmentContextReference,
94 } from "./lib/composerContextRecords";
95 import { create } from "zustand";
96 import { persist, type PersistStorage, type StorageValue } from "zustand/middleware";
97 import { useShallow } from "zustand/react/shallow";
98 import { draftModelSelectionApplies } from "./lib/chatThreadActions";
99 import { createDeferredStorage, createMemoryStorage } from "./lib/storage";
100 import { getDefaultServerModel } from "./providerModels";
101 import {
102 replaceComposerContextReferences,
103 toComposerContextId,
104 toKindScopedComposerContextId,
105 } from "@t3tools/shared/composerContextReferences";
106 import { UnifiedSettings } from "@t3tools/contracts/settings";
107
108 const isElementContextDetails = Schema.is(ElementContextDetails);
109 import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
110 const isRuntimeMode = Schema.is(RuntimeMode);
111 const isProviderDriverKind = Schema.is(ProviderDriverKind);
112 const isReviewCommentContext = Schema.is(ReviewCommentContextSchema);
113 const isThreadContextRecord = Schema.is(ThreadContextRecord);
114 const isEnvironmentContextRecord = Schema.is(EnvironmentContextRecord);
115 const isSnapShotSource = Schema.is(SnapShotSource);
116 const isPreviewAnnotationPayload = Schema.is(PreviewAnnotationPayloadSchema);
117 const isResponseContextRecord = Schema.is(ResponseContextRecord);
118
119 export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
120 const COMPOSER_DRAFT_STORAGE_VERSION = 9;
121 const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
122 export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
123
124 export const DraftId = Schema.String.pipe(Schema.brand("DraftId"));
125 export type DraftId = typeof DraftId.Type;
126
127 const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
128
129 type ComposerPersistState =
130 | { capturedState: ComposerDraftStoreState }
131 | PersistedComposerDraftStoreState;
132
133 const composerDraftBaseStorage =
134 typeof localStorage !== "undefined" ? localStorage : createMemoryStorage();
135
136 interface ComposerDraftWrite {
137 readonly text: string;
138 /** This tab's own state as of the write; entries it still matches were not edited here. */
139 readonly local: PersistedComposerDraftStoreState;
140 readonly merged: PersistedComposerDraftStoreState;
141 }
142 let composerDraftLoadedState: PersistedComposerDraftStoreState | null = null;
143 let composerDraftLastWrite: ComposerDraftWrite | null = null;
144 let composerDraftPendingWrite: ComposerDraftWrite | null = null;
145
146 function readStoredComposerDraftState(): PersistedComposerDraftStoreState | null {
147 const text = composerDraftBaseStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY);
148 if (typeof text !== "string") return null;
149 if (text === composerDraftLastWrite?.text) return composerDraftLastWrite.merged;
150 try {
151 const parsed = JSON.parse(text) as StorageValue<PersistedComposerDraftStoreState>;
152 return parsed.version === COMPOSER_DRAFT_STORAGE_VERSION ? parsed.state : null;
153 } catch {
154 return null;
155 }
156 }
157
158 function mergeDraftRecord<V>(
159 stored: Readonly<Record<string, V>> | undefined,
160 local: Readonly<Record<string, V>>,
161 baseline: Readonly<Record<string, V>>,
162 ): Record<string, V> {
163 const merged = { ...stored };
164 for (const key of new Set([...Object.keys(local), ...Object.keys(baseline)])) {
165 if (Equal.equals(local[key], baseline[key])) continue;
166 const value = local[key];
167 if (value === undefined) delete merged[key];
168 else merged[key] = value;
169 }
170 return merged;
171 }
172
173 /** Writes only what this tab changed since its last write over what other tabs saved since. */
174 function mergeComposerDraftStates(
175 stored: PersistedComposerDraftStoreState,
176 local: PersistedComposerDraftStoreState,
177 baseline: PersistedComposerDraftStoreState,
178 ): PersistedComposerDraftStoreState {
179 const pick = <K extends keyof PersistedComposerDraftStoreState>(key: K) => {
180 const value = Equal.equals(local[key], baseline[key]) ? stored[key] : local[key];
181 return value === undefined ? {} : { [key]: value };
182 };
183 return {
184 draftsByThreadKey: mergeDraftRecord(
185 stored.draftsByThreadKey,
186 local.draftsByThreadKey,
187 baseline.draftsByThreadKey,
188 ),
189 draftThreadsByThreadKey: mergeDraftRecord(
190 stored.draftThreadsByThreadKey,
191 local.draftThreadsByThreadKey,
192 baseline.draftThreadsByThreadKey,
193 ),
194 logicalProjectDraftThreadKeyByLogicalProjectKey: mergeDraftRecord(
195 stored.logicalProjectDraftThreadKeyByLogicalProjectKey,
196 local.logicalProjectDraftThreadKeyByLogicalProjectKey,
197 baseline.logicalProjectDraftThreadKeyByLogicalProjectKey,
198 ),
199 ...pick("stickyModelSelectionByProvider"),
200 ...pick("stickyOptionsByModelByProvider"),
201 ...pick("stickyActiveProvider"),
202 };
203 }
204
205 function serializeComposerDraftState(value: StorageValue<ComposerPersistState>): string {
206 if (!("capturedState" in value.state)) {
207 return JSON.stringify({ state: value.state, version: value.version });
208 }
209 const local = partializeComposerDraftStoreState(value.state.capturedState);
210 const baseline = composerDraftLastWrite?.local ?? composerDraftLoadedState;
211 const stored = baseline ? readStoredComposerDraftState() : null;
212 const merged = stored && baseline ? mergeComposerDraftStates(stored, local, baseline) : local;
213 const text = JSON.stringify({ state: merged, version: value.version });
214 composerDraftPendingWrite = { text, local, merged };
215 return text;
216 }
217
218 const composerDebouncedStorage = createDeferredStorage<StorageValue<ComposerPersistState>>(
219 {
220 getItem: (name) => composerDraftBaseStorage.getItem(name),
221 setItem: (name, text) => {
222 composerDraftBaseStorage.setItem(name, text);
223 if (composerDraftPendingWrite?.text === text)
224 composerDraftLastWrite = composerDraftPendingWrite;
225 },
226 removeItem: (name) => {
227 composerDraftBaseStorage.removeItem(name);
228 composerDraftLoadedState = null;
229 composerDraftLastWrite = null;
230 },
231 },
232 serializeComposerDraftState,
233 COMPOSER_PERSIST_DEBOUNCE_MS,
234 );
235
236 const composerPersistStorage: PersistStorage<ComposerPersistState> = {
237 getItem: (name) => {
238 const raw = composerDebouncedStorage.getItem(name);
239 if (typeof raw !== "string") {
240 return null;
241 }
242 return JSON.parse(raw) as StorageValue<ComposerPersistState>;
243 },
244 setItem: (name, value) => composerDebouncedStorage.setItem(name, value),
245 removeItem: (name) => composerDebouncedStorage.removeItem(name),
246 };
247
248 if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
249 window.addEventListener("beforeunload", () => {
250 composerDebouncedStorage.flush();
251 });
252 }
253
254 export const PersistedComposerImageAttachment = Schema.Struct({
255 id: Schema.String,
256 name: Schema.String,
257 mimeType: Schema.String,
258 sizeBytes: Schema.Number,
259 source: Schema.optional(SnapShotSource),
260 dataUrl: Schema.String,
261 });
262 export type PersistedComposerImageAttachment = typeof PersistedComposerImageAttachment.Type;
263
264 export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
265 previewUrl: string;
266 file: File;
267 }
268
269 export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
270 file: File | null;
271 uploadedAttachmentId?: string;
272 uploadEnvironmentId?: EnvironmentId;
273 }
274
275 export function composerFileNeedsReattach(file: ComposerFileAttachment): boolean {
276 return file.file === null && file.uploadedAttachmentId === undefined;
277 }
278
279 /** Strips upload ids another environment owns; local bytes re-upload, byte-less files need reattaching. */
280 function clearStaleFileUploadMetadata(
281 draft: ComposerThreadDraftState,
282 environmentId: EnvironmentId | null,
283 ): ComposerThreadDraftState {
284 let changed = false;
285 const files = draft.files.map((file) => {
286 if (
287 (file.uploadedAttachmentId === undefined && file.uploadEnvironmentId === undefined) ||
288 file.uploadEnvironmentId === environmentId
289 ) {
290 return file;
291 }
292
293 changed = true;
294 const nextFile = { ...file };
295 delete nextFile.uploadedAttachmentId;
296 delete nextFile.uploadEnvironmentId;
297 return nextFile;
298 });
299
300 return changed ? { ...draft, files } : draft;
301 }
302
303 export const PersistedComposerFileAttachment = Schema.Struct({
304 id: Schema.String,
305 name: Schema.String,
306 mimeType: Schema.String,
307 sizeBytes: Schema.Number,
308 attachmentId: Schema.String,
309 environmentId: EnvironmentId,
310 source: Schema.optional(PastedTextAttachmentSource),
311 });
312 export type PersistedComposerFileAttachment = typeof PersistedComposerFileAttachment.Type;
313
314 /** File handles cannot serialize; metadata-only markers hydrate as needs-reattach rows. */
315 export const PersistedComposerDraftFileAttachment = Schema.Struct({
316 id: Schema.String,
317 name: Schema.String,
318 mimeType: Schema.String,
319 sizeBytes: Schema.Number,
320 attachmentId: Schema.optionalKey(Schema.String),
321 environmentId: Schema.optionalKey(EnvironmentId),
322 source: Schema.optional(PastedTextAttachmentSource),
323 });
324 export type PersistedComposerDraftFileAttachment = typeof PersistedComposerDraftFileAttachment.Type;
325 const isPersistedComposerDraftFileAttachment = Schema.is(PersistedComposerDraftFileAttachment);
326
327 const PersistedTerminalContextDraft = Schema.Struct({
328 id: Schema.String,
329 threadId: ThreadId,
330 createdAt: Schema.String,
331 terminalId: Schema.String,
332 terminalLabel: Schema.String,
333 lineStart: Schema.Number,
334 lineEnd: Schema.Number,
335 text: Schema.optionalKey(Schema.String),
336 });
337 type PersistedTerminalContextDraft = typeof PersistedTerminalContextDraft.Type;
338
339 const PersistedComposerThreadDraftState = Schema.Struct({
340 prompt: Schema.String,
341 attachments: Schema.Array(PersistedComposerImageAttachment),
342 files: Schema.optionalKey(Schema.Array(PersistedComposerDraftFileAttachment)),
343 terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
344 previewAnnotations: Schema.optionalKey(Schema.Array(PreviewAnnotationPayloadSchema)),
345 reviewComments: Schema.optionalKey(Schema.Array(ReviewCommentContextSchema)),
346 threadContexts: Schema.optionalKey(Schema.Array(ThreadContextRecord)),
347 environmentContexts: Schema.optionalKey(Schema.Array(EnvironmentContextRecord)),
348 replyTo: Schema.optionalKey(ResponseContextRecord),
349 modelSelectionByProvider: Schema.optionalKey(Schema.Record(ProviderInstanceId, ModelSelection)),
350 activeProvider: Schema.optionalKey(Schema.NullOr(ProviderInstanceId)),
351 modelSelectionExplicit: Schema.optionalKey(Schema.Boolean),
352 runtimeMode: Schema.optionalKey(RuntimeMode),
353 interactionMode: Schema.optionalKey(ProviderInteractionMode),
354 });
355 type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type;
356
357 type ProviderOptionSelectionsByProvider = Partial<
358 Record<string, ReadonlyArray<ProviderOptionSelection>>
359 >;
360
361 type LegacyCodexFields = {
362 effort?: unknown;
363 codexFastMode?: unknown;
364 serviceTier?: unknown;
365 };
366
367 type LegacyThreadModelFields = {
368 provider?: unknown;
369 model?: unknown;
370 modelOptions?: unknown;
371 };
372
373 type LegacyV2ThreadDraftFields = {
374 modelSelection?: ModelSelection | null;
375 modelOptions?: unknown;
376 };
377
378 type LegacyPersistedComposerThreadDraftState = PersistedComposerThreadDraftState &
379 LegacyCodexFields &
380 LegacyThreadModelFields &
381 LegacyV2ThreadDraftFields;
382
383 type LegacyStickyModelFields = {
384 stickyProvider?: unknown;
385 stickyModel?: unknown;
386 stickyModelOptions?: unknown;
387 };
388
389 type LegacyV2StoreFields = {
390 stickyModelSelection?: ModelSelection | null;
391 stickyModelOptions?: unknown;
392 projectDraftThreadIdByProjectId?: Record<string, string> | null;
393 draftsByThreadId?: Record<string, PersistedComposerThreadDraftState> | null;
394 draftThreadsByThreadId?: Record<string, PersistedDraftThreadState> | null;
395 projectDraftThreadIdByProjectKey?: Record<string, string> | null;
396 draftsByThreadKey?: Record<string, PersistedComposerThreadDraftState> | null;
397 draftThreadsByThreadKey?: Record<string, PersistedDraftThreadState> | null;
398 projectDraftThreadKeyByProjectKey?: Record<string, string> | null;
399 logicalProjectDraftThreadKeyByLogicalProjectKey?: Record<string, string> | null;
400 };
401
402 type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
403 LegacyStickyModelFields &
404 LegacyV2StoreFields;
405
406 const PersistedDraftThreadState = Schema.Struct({
407 threadId: ThreadId,
408 environmentId: Schema.String,
409 projectId: ProjectId,
410 logicalProjectKey: Schema.optionalKey(Schema.String),
411 environmentSelection: Schema.optionalKey(Schema.Literals(["auto", "manual"])),
412 loadBalancedEnvironmentId: Schema.optionalKey(Schema.NullOr(Schema.String)),
413 createdAt: Schema.String,
414 runtimeMode: RuntimeMode,
415 interactionMode: ProviderInteractionMode,
416 branch: Schema.NullOr(Schema.String),
417 worktreePath: Schema.NullOr(Schema.String),
418 envMode: DraftThreadEnvModeSchema,
419 startFromOrigin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
420 checkoutPullRequest: Schema.optionalKey(
421 Schema.Struct({ url: Schema.String, branch: Schema.String }),
422 ),
423 promotedTo: Schema.optionalKey(
424 Schema.NullOr(
425 Schema.Struct({
426 environmentId: Schema.String,
427 threadId: Schema.String,
428 }),
429 ),
430 ),
431 });
432 type PersistedDraftThreadState = typeof PersistedDraftThreadState.Type;
433
434 const PersistedComposerDraftStoreState = Schema.Struct({
435 draftsByThreadKey: Schema.Record(Schema.String, PersistedComposerThreadDraftState),
436 draftThreadsByThreadKey: Schema.Record(Schema.String, PersistedDraftThreadState),
437 logicalProjectDraftThreadKeyByLogicalProjectKey: Schema.Record(Schema.String, Schema.String),
438 stickyModelSelectionByProvider: Schema.optionalKey(
439 Schema.Record(ProviderInstanceId, ModelSelection),
440 ),
441 stickyOptionsByModelByProvider: Schema.optionalKey(
442 Schema.Record(ProviderInstanceId, Schema.Record(Schema.String, ProviderOptionSelections)),
443 ),
444 stickyActiveProvider: Schema.optionalKey(Schema.NullOr(ProviderInstanceId)),
445 });
446 type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
447
448 const PersistedComposerDraftStoreStorage = Schema.Struct({
449 version: Schema.Number,
450 state: PersistedComposerDraftStoreState,
451 });
452
453 export interface ComposerContextAddOptions {
454 appendReference?: boolean;
455 allowDuplicateReference?: boolean;
456 /** `false` to append synchronously instead of asking a mounted editor for its current caret. */
457 insertAtCaret?: boolean;
458 }
459
460 export type ComposerContextInsertionHandler = (
461 references: ReadonlyArray<ComposerContextReference>,
462 ) => boolean;
463 const contextInsertionHandlers = new Map<string, ComposerContextInsertionHandler>();
464
465 export interface ComposerThreadDraftState {
466 prompt: string;
467 images: ComposerImageAttachment[];
468 files: ComposerFileAttachment[];
469 nonPersistedImageIds: string[];
470 persistedAttachments: PersistedComposerImageAttachment[];
471 terminalContexts: TerminalContextDraft[];
472 previewAnnotations: PreviewAnnotationPayload[];
473 reviewComments: ReviewCommentContext[];
474 threadContexts: ThreadContextRecord[];
475 environmentContexts: EnvironmentContextRecord[];
476 /** The response this message replies to. It becomes a context record when the message is sent. */
477 replyTo: ResponseContextRecord | null;
478 modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
479 activeProvider: ProviderInstanceId | null;
480 modelSelectionExplicit?: boolean;
481 runtimeMode: RuntimeMode | null;
482 interactionMode: ProviderInteractionMode | null;
483 }
484
485 export function composerDraftHasUserContent(
486 draft: ComposerThreadDraftState | null | undefined,
487 ): boolean {
488 if (!draft) {
489 return false;
490 }
491 return (
492 draft.prompt.trim().length > 0 ||
493 draft.images.length > 0 ||
494 draft.files.length > 0 ||
495 draft.persistedAttachments.length > 0 ||
496 draft.terminalContexts.length > 0 ||
497 draft.previewAnnotations.length > 0 ||
498 draft.reviewComments.length > 0 ||
499 draft.threadContexts.length > 0 ||
500 draft.environmentContexts.length > 0 ||
501 draft.replyTo !== null
502 );
503 }
504
505 export interface DraftSessionState {
506 threadId: ThreadId;
507 environmentId: EnvironmentId;
508 projectId: ProjectId;
509 logicalProjectKey: string;
510 environmentSelection?: "auto" | "manual";
511 loadBalancedEnvironmentId?: EnvironmentId | null;
512 createdAt: string;
513 runtimeMode: RuntimeMode;
514 interactionMode: ProviderInteractionMode;
515 branch: string | null;
516 worktreePath: string | null;
517 envMode: DraftThreadEnvMode;
518 startFromOrigin: boolean;
519 /** Linked to the thread when the draft is sent on this branch. */
520 checkoutPullRequest?: DraftCheckoutPullRequest;
521 promotedTo?: ScopedThreadRef | null;
522 }
523
524 export type DraftThreadState = DraftSessionState;
525
526 export interface DraftCheckoutPullRequest {
527 readonly url: string;
528 readonly branch: string;
529 }
530
531 /**
532 * The pull request to link when this draft becomes a thread. Matching the branch at send time,
533 * rather than clearing on every branch write, matters: right after a local checkout the live
534 * branch sync briefly writes the stale pre-checkout branch back onto the draft before the fresh
535 * git status lands.
536 */
537 export function checkoutPullRequestUrlToLink(
538 draft: Pick<DraftSessionState, "branch" | "checkoutPullRequest"> | null | undefined,
539 ): string | null {
540 const checkout = draft?.checkoutPullRequest;
541 return checkout && draft.branch === checkout.branch ? checkout.url : null;
542 }
543
544 interface ProjectDraftSession extends DraftSessionState {
545 draftId: DraftId;
546 }
547
548 export type ComposerThreadTarget = ScopedThreadRef | DraftId;
549
550 interface ComposerDraftStoreState {
551 draftsByThreadKey: Record<string, ComposerThreadDraftState>;
552 draftThreadsByThreadKey: Record<string, DraftThreadState>;
553 logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string>;
554 backgroundSubmissionThreadKeys: Record<string, true>;
555 /**
556 * Where each finalized draft went, so `/draft/<id>` keeps leading to its thread (Back, an
557 * "Open draft" toast) after the draft is gone. In memory only, one small entry per sent draft.
558 */
559 promotedDraftRedirects: Record<string, ScopedThreadRef>;
560 rewindingThreadKeys: ReadonlySet<string>;
561 stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
562 stickyOptionsByModelByProvider: Partial<
563 Record<ProviderInstanceId, Partial<Record<string, ReadonlyArray<ProviderOptionSelection>>>>
564 >;
565 stickyActiveProvider: ProviderInstanceId | null;
566 getComposerDraft: (target: ComposerThreadTarget) => ComposerThreadDraftState | null;
567 getDraftSessionByLogicalProjectKey: (logicalProjectKey: string) => ProjectDraftSession | null;
568 getDraftThreadByProjectRef: (projectRef: ScopedProjectRef) => ProjectDraftSession | null;
569 getDraftSessionByProjectRef: (projectRef: ScopedProjectRef) => ProjectDraftSession | null;
570 getDraftSession: (draftId: DraftId) => DraftSessionState | null;
571 getDraftSessionByRef: (threadRef: ScopedThreadRef) => DraftSessionState | null;
572 getDraftIdByRef: (threadRef: ScopedThreadRef) => DraftId | null;
573 getPromotedDraftRedirect: (draftId: DraftId) => ScopedThreadRef | null;
574 getDraftThreadByRef: (threadRef: ScopedThreadRef) => DraftThreadState | null;
575 getDraftThread: (threadRef: ComposerThreadTarget) => DraftThreadState | null;
576 listDraftThreadKeys: () => string[];
577 hasDraftThreadsInEnvironment: (environmentId: EnvironmentId) => boolean;
578 setLogicalProjectDraftThreadId: (
579 logicalProjectKey: string,
580 projectRef: ScopedProjectRef,
581 draftId: DraftId,
582 options?: {
583 threadId?: ThreadId;
584 branch?: string | null;
585 worktreePath?: string | null;
586 createdAt?: string;
587 envMode?: DraftThreadEnvMode;
588 startFromOrigin?: boolean;
589 runtimeMode?: RuntimeMode;
590 interactionMode?: ProviderInteractionMode;
591 environmentSelection?: "auto" | "manual";
592 loadBalancedEnvironmentId?: EnvironmentId | null;
593 checkoutPullRequest?: DraftCheckoutPullRequest | null;
594 },
595 ) => void;
596 setProjectDraftThreadId: (
597 projectRef: ScopedProjectRef,
598 draftId: DraftId,
599 options?: {
600 threadId?: ThreadId;
601 branch?: string | null;
602 worktreePath?: string | null;
603 createdAt?: string;
604 envMode?: DraftThreadEnvMode;
605 startFromOrigin?: boolean;
606 runtimeMode?: RuntimeMode;
607 interactionMode?: ProviderInteractionMode;
608 environmentSelection?: "auto" | "manual";
609 loadBalancedEnvironmentId?: EnvironmentId | null;
610 checkoutPullRequest?: DraftCheckoutPullRequest | null;
611 },
612 ) => void;
613 setDraftThreadContext: (
614 threadRef: ComposerThreadTarget,
615 options: {
616 branch?: string | null;
617 worktreePath?: string | null;
618 projectRef?: ScopedProjectRef;
619 createdAt?: string;
620 envMode?: DraftThreadEnvMode;
621 startFromOrigin?: boolean;
622 runtimeMode?: RuntimeMode;
623 interactionMode?: ProviderInteractionMode;
624 environmentSelection?: "auto" | "manual";
625 loadBalancedEnvironmentId?: EnvironmentId | null;
626 checkoutPullRequest?: DraftCheckoutPullRequest | null;
627 },
628 ) => void;
629 clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void;
630 clearProjectDraftThreadById: (
631 projectRef: ScopedProjectRef,
632 threadRef: ComposerThreadTarget,
633 ) => void;
634 markDraftThreadPromoting: (threadRef: ComposerThreadTarget, promotedTo?: ScopedThreadRef) => void;
635 finalizePromotedDraftThread: (threadRef: ComposerThreadTarget) => void;
636 clearDraftThread: (threadRef: ComposerThreadTarget) => void;
637 setStickyModelSelection: (modelSelection: ModelSelection | null | undefined) => void;
638 setPrompt: (threadRef: ComposerThreadTarget, prompt: string) => void;
639 setTerminalContexts: (threadRef: ComposerThreadTarget, contexts: TerminalContextDraft[]) => void;
640 setModelSelection: (
641 threadRef: ComposerThreadTarget,
642 modelSelection: ModelSelection | null | undefined,
643 opts?: {
644 explicit?: boolean;
645 /** Replace existing options even when the incoming selection has none. */
646 replaceOptions?: boolean;
647 },
648 ) => void;
649 /** Lets the thread's model show again once the server accepted this exact pick. */
650 releaseModelSelection: (threadRef: ScopedThreadRef, modelSelection: ModelSelection) => void;
651 applyStickyState: (threadRef: ComposerThreadTarget) => void;
652 setProviderModelOptions: (
653 threadRef: ComposerThreadTarget,
654 provider: ProviderDriverKind,
655 nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
656 options?: {
657 instanceId?: ProviderInstanceId | null | undefined;
658 model?: string | null | undefined;
659 persistSticky?: boolean;
660 },
661 ) => void;
662 setRuntimeMode: (
663 threadRef: ComposerThreadTarget,
664 runtimeMode: RuntimeMode | null | undefined,
665 ) => void;
666 setInteractionMode: (
667 threadRef: ComposerThreadTarget,
668 interactionMode: ProviderInteractionMode | null | undefined,
669 ) => void;
670 addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => boolean;
671 addImages: (
672 threadRef: ComposerThreadTarget,
673 images: ComposerImageAttachment[],
674 options?: {
675 allowDuplicates?: boolean;
676 onCapacityExceeded?: (image: ComposerImageAttachment) => void;
677 },
678 ) => string[];
679 removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
680 /** Returns the ids of files appended; a re-pick that replaces a marker is not listed. */
681 addFiles: (
682 threadRef: ComposerThreadTarget,
683 files: ComposerFileAttachment[],
684 options?: { allowDuplicates?: boolean; appendReference?: boolean },
685 ) => string[];
686 removeFile: (threadRef: ComposerThreadTarget, fileId: string) => void;
687 setFileUpload: (
688 threadRef: ComposerThreadTarget,
689 fileId: string,
690 environmentId: EnvironmentId,
691 attachmentId: string,
692 ) => void;
693 markFileUploadMissing: (
694 threadRef: ComposerThreadTarget,
695 fileId: string,
696 environmentId: EnvironmentId,
697 attachmentId: string,
698 ) => boolean;
699 insertTerminalContext: (
700 threadRef: ComposerThreadTarget,
701 prompt: string,
702 context: TerminalContextDraft,
703 index: number,
704 ) => boolean;
705 addTerminalContexts: (
706 threadRef: ComposerThreadTarget,
707 contexts: TerminalContextDraft[],
708 options?: ComposerContextAddOptions,
709 ) => void;
710 removeTerminalContext: (threadRef: ComposerThreadTarget, contextId: string) => void;
711 clearTerminalContexts: (threadRef: ComposerThreadTarget) => void;
712 addPreviewAnnotation: (
713 threadRef: ComposerThreadTarget,
714 annotation: PreviewAnnotationPayload,
715 options?: ComposerContextAddOptions,
716 ) => void;
717 setPreviewAnnotations: (
718 threadRef: ComposerThreadTarget,
719 annotations: ReadonlyArray<PreviewAnnotationPayload>,
720 ) => void;
721 removePreviewAnnotation: (threadRef: ComposerThreadTarget, annotationId: string) => void;
722 setReplyTo: (threadRef: ComposerThreadTarget, response: ResponseContextRecord | null) => void;
723 addReviewComment: (
724 threadRef: ComposerThreadTarget,
725 comment: ReviewCommentContext,
726 options?: ComposerContextAddOptions,
727 ) => void;
728 setContextInsertionHandler: (
729 threadRef: ComposerThreadTarget,
730 handler: ComposerContextInsertionHandler | null,
731 ) => (() => void) | undefined;
732 setReviewComments: (
733 threadRef: ComposerThreadTarget,
734 comments: ReadonlyArray<ReviewCommentContext>,
735 ) => void;
736 removeReviewComment: (threadRef: ComposerThreadTarget, commentId: string) => void;
737 addThreadContexts: (
738 threadRef: ComposerThreadTarget,
739 records: ReadonlyArray<ThreadContextRecord>,
740 options?: ComposerContextAddOptions,
741 ) => void;
742 setThreadContexts: (
743 threadRef: ComposerThreadTarget,
744 records: ReadonlyArray<ThreadContextRecord>,
745 ) => void;
746 /** Mentions machines as context; already-mentioned machines are skipped. */
747 addEnvironmentContexts: (
748 threadRef: ComposerThreadTarget,
749 records: ReadonlyArray<EnvironmentContextRecord>,
750 options?: ComposerContextAddOptions,
751 ) => void;
752 setEnvironmentContexts: (
753 threadRef: ComposerThreadTarget,
754 records: ReadonlyArray<EnvironmentContextRecord>,
755 ) => void;
756 clearPersistedAttachments: (threadRef: ComposerThreadTarget) => void;
757 syncPersistedAttachments: (
758 threadRef: ComposerThreadTarget,
759 attachments: PersistedComposerImageAttachment[],
760 ) => Promise<void>;
761 /** Saves records for the supplied images that the draft still owns after serialization. */
762 appendPersistedAttachments: (
763 threadRef: ComposerThreadTarget,
764 images: ReadonlyArray<ComposerImageAttachment>,
765 attachments: ReadonlyArray<PersistedComposerImageAttachment>,
766 ) => Promise<void>;
767 clearComposerContent: (threadRef: ComposerThreadTarget) => void;
768 /** Clears text and attachments, preserving terminal/element contexts, preview annotations, and review comments. */
769 clearComposerPromptAndImages: (threadRef: ComposerThreadTarget) => void;
770 /** Moves all user content into a destination that has none; otherwise leaves both drafts alone. */
771 moveComposerContent: (from: ComposerThreadTarget, to: ComposerThreadTarget) => void;
772 }
773
774 export interface EffectiveComposerModelState {
775 selectedModel: string;
776 modelOptions: ProviderOptionSelectionsByProvider | null;
777 }
778
779 interface ComposerDraftModelState {
780 activeProvider: ProviderInstanceId | null;
781 modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
782 modelSelectionExplicit: boolean;
783 }
784
785 function selectionsByInstance(
786 modelSelection: ModelSelection | null | undefined,
787 ): Partial<Record<string, ModelSelection>> | null {
788 return modelSelection ? { [modelSelection.instanceId]: modelSelection } : null;
789 }
790
791 function modelSelectionByProviderToOptions(
792 map: Partial<Record<string, ModelSelection>> | null | undefined,
793 ): ProviderOptionSelectionsByProvider | null {
794 if (!map) return null;
795 const result: ProviderOptionSelectionsByProvider = {};
796 for (const [provider, selection] of Object.entries(map)) {
797 if (selection?.options && selection.options.length > 0) {
798 result[provider] = selection.options;
799 }
800 }
801 return Object.keys(result).length > 0 ? result : null;
802 }
803
804 function cloneModelSelection(selection: ModelSelection): DeepMutable<ModelSelection> {
805 return {
806 ...selection,
807 ...(selection.options ? { options: selection.options.map((option) => ({ ...option })) } : {}),
808 } as DeepMutable<ModelSelection>;
809 }
810
811 function compactModelSelectionByProvider(
812 selections: Partial<Record<ProviderInstanceId, ModelSelection>>,
813 ): DeepMutable<Record<ProviderInstanceId, ModelSelection>> {
814 const entries: Array<[string, DeepMutable<ModelSelection>]> = [];
815 for (const [provider, selection] of Object.entries(selections)) {
816 if (selection !== undefined) {
817 entries.push([provider, cloneModelSelection(selection)]);
818 }
819 }
820 return Object.fromEntries(entries) as DeepMutable<Record<ProviderInstanceId, ModelSelection>>;
821 }
822
823 function compactStickyOptionsByModel(
824 optionsByModelByProvider: ComposerDraftStoreState["stickyOptionsByModelByProvider"],
825 ): NonNullable<PersistedComposerDraftStoreState["stickyOptionsByModelByProvider"]> {
826 const result: Record<string, Record<string, ReadonlyArray<ProviderOptionSelection>>> = {};
827 for (const [instanceId, optionsByModel] of Object.entries(optionsByModelByProvider)) {
828 for (const [modelSlug, options] of Object.entries(optionsByModel ?? {})) {
829 if (options === undefined || options.length === 0) continue;
830 result[instanceId] ??= {};
831 result[instanceId][modelSlug] = options;
832 }
833 }
834 return result as NonNullable<PersistedComposerDraftStoreState["stickyOptionsByModelByProvider"]>;
835 }
836
837 function seedStickyOptionsByModel(
838 stickySelections: Partial<Record<ProviderInstanceId, ModelSelection>>,
839 ): NonNullable<PersistedComposerDraftStoreState["stickyOptionsByModelByProvider"]> {
840 const result: Record<string, Record<string, ReadonlyArray<ProviderOptionSelection>>> = {};
841 for (const [instanceId, selection] of Object.entries(stickySelections)) {
842 if (
843 selection === undefined ||
844 selection.options === undefined ||
845 selection.options.length === 0
846 ) {
847 continue;
848 }
849 result[instanceId] = { [selection.model]: selection.options };
850 }
851 return result as NonNullable<PersistedComposerDraftStoreState["stickyOptionsByModelByProvider"]>;
852 }
853
854 const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
855 draftsByThreadKey: {},
856 draftThreadsByThreadKey: {},
857 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
858 stickyModelSelectionByProvider: {},
859 stickyOptionsByModelByProvider: {},
860 stickyActiveProvider: null,
861 });
862
863 const EMPTY_IMAGES: ComposerImageAttachment[] = [];
864 const EMPTY_FILES: ComposerFileAttachment[] = [];
865 const EMPTY_IDS: string[] = [];
866 const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
867 const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
868 const EMPTY_PREVIEW_ANNOTATIONS: PreviewAnnotationPayload[] = [];
869 const EMPTY_REVIEW_COMMENTS: ReviewCommentContext[] = [];
870 const EMPTY_THREAD_CONTEXTS: ThreadContextRecord[] = [];
871 const EMPTY_ENVIRONMENT_CONTEXTS: EnvironmentContextRecord[] = [];
872 Object.freeze(EMPTY_IMAGES);
873 Object.freeze(EMPTY_FILES);
874 Object.freeze(EMPTY_IDS);
875 Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
876 Object.freeze(EMPTY_PREVIEW_ANNOTATIONS);
877 Object.freeze(EMPTY_REVIEW_COMMENTS);
878 Object.freeze(EMPTY_THREAD_CONTEXTS);
879 Object.freeze(EMPTY_ENVIRONMENT_CONTEXTS);
880 const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderDriverKind, ModelSelection>> =
881 Object.freeze({});
882 const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>({
883 activeProvider: null,
884 modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
885 modelSelectionExplicit: false,
886 });
887
888 const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
889 prompt: "",
890 images: EMPTY_IMAGES,
891 files: EMPTY_FILES,
892 nonPersistedImageIds: EMPTY_IDS,
893 persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
894 terminalContexts: EMPTY_TERMINAL_CONTEXTS,
895 previewAnnotations: EMPTY_PREVIEW_ANNOTATIONS,
896 reviewComments: EMPTY_REVIEW_COMMENTS,
897 threadContexts: EMPTY_THREAD_CONTEXTS,
898 environmentContexts: EMPTY_ENVIRONMENT_CONTEXTS,
899 replyTo: null,
900 modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
901 activeProvider: null,
902 runtimeMode: null,
903 interactionMode: null,
904 });
905
906 function createEmptyThreadDraft(): ComposerThreadDraftState {
907 return {
908 prompt: "",
909 images: [],
910 files: [],
911 nonPersistedImageIds: [],
912 persistedAttachments: [],
913 terminalContexts: [],
914 previewAnnotations: [],
915 reviewComments: [],
916 threadContexts: [],
917 environmentContexts: [],
918 replyTo: null,
919 modelSelectionByProvider: {},
920 activeProvider: null,
921 runtimeMode: null,
922 interactionMode: null,
923 };
924 }
925
926 /** Keep these content fields aligned with composerDraftHasUserContent. */
927 function composerDraftContent({
928 modelSelectionByProvider: _modelSelectionByProvider,
929 activeProvider: _activeProvider,
930 modelSelectionExplicit: _modelSelectionExplicit,
931 runtimeMode: _runtimeMode,
932 interactionMode: _interactionMode,
933 ...content
934 }: ComposerThreadDraftState) {
935 return content;
936 }
937
938 export function composerFileDedupKey(
939 file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
940 ): string {
941 return `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
942 }
943
944 export function composerFileMatchesReattachMarker(
945 marker: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
946 file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
947 ): boolean {
948 if (marker.name !== file.name || marker.sizeBytes !== file.sizeBytes) return false;
949 if (marker.mimeType === file.mimeType) return true;
950 const normalizedMarkerMimeType = composerFileAttachmentMimeType({
951 name: marker.name,
952 type: marker.mimeType,
953 });
954 if (
955 normalizedMarkerMimeType === "image/x-adobe-dng" &&
956 normalizedMarkerMimeType ===
957 composerFileAttachmentMimeType({ name: file.name, type: file.mimeType })
958 ) {
959 return true;
960 }
961 const markerMimeType = marker.mimeType.toLowerCase();
962 return (
963 (markerMimeType === "" || markerMimeType === "application/octet-stream") &&
964 videoMimeType(marker) !== null &&
965 videoMimeType(file) !== null
966 );
967 }
968
969 function terminalContextDedupKey(context: TerminalContextDraft): string {
970 return `${context.terminalId}\u0000${context.lineStart}\u0000${context.lineEnd}`;
971 }
972
973 function normalizeTerminalContextForThread(
974 threadId: ThreadId,
975 context: TerminalContextDraft,
976 ): TerminalContextDraft | null {
977 const terminalId = context.terminalId.trim();
978 const terminalLabel = context.terminalLabel.trim();
979 if (terminalId.length === 0 || terminalLabel.length === 0) {
980 return null;
981 }
982 const lineStart = Math.max(1, Math.floor(context.lineStart));
983 const lineEnd = Math.max(lineStart, Math.floor(context.lineEnd));
984 return {
985 ...context,
986 id: toComposerContextId(context.id),
987 threadId,
988 terminalId,
989 terminalLabel,
990 lineStart,
991 lineEnd,
992 text: normalizeTerminalContextText(context.text),
993 };
994 }
995
996 function normalizeTerminalContextsForThread(
997 threadId: ThreadId,
998 contexts: ReadonlyArray<TerminalContextDraft>,
999 ): TerminalContextDraft[] {
1000 const existingIds = new Set<string>();
1001 const existingDedupKeys = new Set<string>();
1002 const normalizedContexts: TerminalContextDraft[] = [];
1003
1004 for (const context of contexts) {
1005 const normalizedContext = normalizeTerminalContextForThread(threadId, context);
1006 if (!normalizedContext) {
1007 continue;
1008 }
1009 const dedupKey = terminalContextDedupKey(normalizedContext);
1010 if (existingIds.has(normalizedContext.id) || existingDedupKeys.has(dedupKey)) {
1011 continue;
1012 }
1013 normalizedContexts.push(normalizedContext);
1014 existingIds.add(normalizedContext.id);
1015 existingDedupKeys.add(dedupKey);
1016 }
1017
1018 return normalizedContexts;
1019 }
1020
1021 function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
1022 return (
1023 draft.prompt.length === 0 &&
1024 draft.images.length === 0 &&
1025 draft.files.length === 0 &&
1026 draft.persistedAttachments.length === 0 &&
1027 draft.terminalContexts.length === 0 &&
1028 draft.previewAnnotations.length === 0 &&
1029 draft.reviewComments.length === 0 &&
1030 draft.threadContexts.length === 0 &&
1031 draft.environmentContexts.length === 0 &&
1032 draft.replyTo === null &&
1033 Object.keys(draft.modelSelectionByProvider).length === 0 &&
1034 draft.activeProvider === null &&
1035 draft.runtimeMode === null &&
1036 draft.interactionMode === null
1037 );
1038 }
1039
1040 function normalizeProviderDriverKind(value: unknown): ProviderDriverKind | null {
1041 return isProviderDriverKind(value) ? value : null;
1042 }
1043
1044 /** The schema owns validation; this permissive pattern keeps Effect Schema off the hot path. */
1045 const PROVIDER_INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
1046
1047 function normalizeProviderInstanceId(value: unknown): ProviderInstanceId | null {
1048 if (typeof value !== "string") return null;
1049 if (!PROVIDER_INSTANCE_ID_PATTERN.test(value)) return null;
1050 return value as ProviderInstanceId;
1051 }
1052
1053 function coerceProviderOptionSelections(
1054 value: unknown,
1055 ): ReadonlyArray<ProviderOptionSelection> | undefined {
1056 if (Array.isArray(value)) {
1057 const out: ProviderOptionSelection[] = [];
1058 for (const entry of value) {
1059 if (!entry || typeof entry !== "object") continue;
1060 const record = entry as Record<string, unknown>;
1061 const id = record.id;
1062 const optionValue = record.value;
1063 if (typeof id !== "string" || id.length === 0) continue;
1064 if (typeof optionValue === "string" || typeof optionValue === "boolean") {
1065 out.push({ id, value: optionValue });
1066 }
1067 }
1068 return out.length > 0 ? out : undefined;
1069 }
1070 if (value && typeof value === "object") {
1071 const record = value as Record<string, unknown>;
1072 const out: ProviderOptionSelection[] = [];
1073 for (const [id, raw] of Object.entries(record)) {
1074 if (typeof raw === "string" || typeof raw === "boolean") {
1075 out.push({ id, value: raw });
1076 }
1077 }
1078 return out.length > 0 ? out : undefined;
1079 }
1080 return undefined;
1081 }
1082
1083 function normalizeProviderModelOptions(
1084 value: unknown,
1085 provider?: ProviderDriverKind | null,
1086 legacy?: LegacyCodexFields,
1087 ): ProviderOptionSelectionsByProvider | null {
1088 const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;
1089 const result: ProviderOptionSelectionsByProvider = {};
1090 for (const providerKey of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
1091 const selections = coerceProviderOptionSelections(candidate?.[providerKey]);
1092 if (selections) {
1093 result[providerKey] = selections;
1094 }
1095 }
1096
1097 if (provider === "codex" && legacy) {
1098 const codexExtras: ProviderOptionSelection[] = [];
1099 if (typeof legacy.effort === "string" && legacy.effort.length > 0) {
1100 codexExtras.push({ id: "reasoningEffort", value: legacy.effort });
1101 }
1102 const fastMode =
1103 legacy.codexFastMode === true ||
1104 (typeof legacy.serviceTier === "string" && legacy.serviceTier === "fast");
1105 if (fastMode) {
1106 codexExtras.push({ id: "fastMode", value: true });
1107 }
1108 if (codexExtras.length > 0) {
1109 const existing = result.codex ?? [];
1110 const existingIds = new Set(existing.map((entry) => entry.id));
1111 const merged = [...existing];
1112 for (const extra of codexExtras) {
1113 if (!existingIds.has(extra.id)) merged.push(extra);
1114 }
1115 result.codex = merged;
1116 }
1117 }
1118
1119 return Object.keys(result).length > 0 ? result : null;
1120 }
1121
1122 function normalizeModelSelection(
1123 value: unknown,
1124 legacy?: {
1125 provider?: unknown;
1126 model?: unknown;
1127 modelOptions?: unknown;
1128 legacyCodex?: LegacyCodexFields;
1129 },
1130 ): NormalizedModelSelection | null {
1131 const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;
1132 const instanceId = normalizeProviderInstanceId(
1133 candidate?.instanceId ?? candidate?.provider ?? legacy?.provider,
1134 );
1135 if (instanceId === null) {
1136 return null;
1137 }
1138 const rawModel = candidate?.model ?? legacy?.model;
1139 if (typeof rawModel !== "string") {
1140 return null;
1141 }
1142 const driverKindHint =
1143 normalizeProviderDriverKind(candidate?.provider ?? legacy?.provider) ??
1144 ProviderDriverKind.make("codex");
1145 // Instance-scoped picks are already resolved slugs; a custom slug can match a static alias.
1146 const model =
1147 candidate?.instanceId === undefined
1148 ? normalizeModelSlug(rawModel, driverKindHint)
1149 : normalizeCustomModelSlug(rawModel);
1150 if (!model) {
1151 return null;
1152 }
1153 if (Array.isArray(candidate?.options)) {
1154 const selections = coerceProviderOptionSelections(candidate.options);
1155 return createModelSelection(instanceId, model, selections) as NormalizedModelSelection;
1156 }
1157 const kindForLegacyOptions = normalizeProviderDriverKind(instanceId);
1158 const modelOptions = kindForLegacyOptions
1159 ? normalizeProviderModelOptions(
1160 candidate?.options ? { [kindForLegacyOptions]: candidate.options } : legacy?.modelOptions,
1161 kindForLegacyOptions,
1162 kindForLegacyOptions === "codex" ? legacy?.legacyCodex : undefined,
1163 )
1164 : null;
1165 const options = kindForLegacyOptions ? modelOptions?.[kindForLegacyOptions] : undefined;
1166 return createModelSelection(instanceId, model, options) as NormalizedModelSelection;
1167 }
1168
1169 type NormalizedModelSelection = Omit<ModelSelection, "instanceId"> & {
1170 readonly instanceId: ProviderInstanceId;
1171 };
1172
1173 function legacySyncModelSelectionOptions(
1174 modelSelection: NormalizedModelSelection | null,
1175 modelOptions: ProviderOptionSelectionsByProvider | null | undefined,
1176 ): NormalizedModelSelection | null {
1177 if (modelSelection === null) {
1178 return null;
1179 }
1180 const kind = normalizeProviderDriverKind(modelSelection.instanceId);
1181 const options = kind ? modelOptions?.[kind] : undefined;
1182 return createModelSelection(
1183 modelSelection.instanceId,
1184 modelSelection.model,
1185 options,
1186 ) as NormalizedModelSelection;
1187 }
1188
1189 function legacyMergeModelSelectionIntoProviderModelOptions(
1190 modelSelection: NormalizedModelSelection | null,
1191 currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined,
1192 ): ProviderOptionSelectionsByProvider | null {
1193 if (!modelSelection?.options || modelSelection.options.length === 0) {
1194 return normalizeProviderModelOptions(currentModelOptions);
1195 }
1196 const kind = normalizeProviderDriverKind(modelSelection.instanceId);
1197 if (!kind) {
1198 return normalizeProviderModelOptions(currentModelOptions);
1199 }
1200 return legacyReplaceProviderModelOptions(
1201 normalizeProviderModelOptions(currentModelOptions),
1202 kind,
1203 modelSelection.options,
1204 );
1205 }
1206
1207 function legacyReplaceProviderModelOptions(
1208 currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined,
1209 provider: ProviderDriverKind,
1210 nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
1211 ): ProviderOptionSelectionsByProvider | null {
1212 const { [provider]: _discardedProviderModelOptions, ...otherProviderModelOptions } =
1213 currentModelOptions ?? {};
1214 const merged: ProviderOptionSelectionsByProvider = { ...otherProviderModelOptions };
1215 if (nextProviderOptions && nextProviderOptions.length > 0) {
1216 merged[provider] = nextProviderOptions;
1217 }
1218 return Object.keys(merged).length > 0 ? merged : null;
1219 }
1220
1221 function legacyToModelSelectionByProvider(
1222 modelSelection: NormalizedModelSelection | null,
1223 modelOptions: ProviderOptionSelectionsByProvider | null | undefined,
1224 ): Partial<Record<ProviderInstanceId, ModelSelection>> {
1225 const result: Partial<Record<ProviderInstanceId, ModelSelection>> = {};
1226 if (modelOptions) {
1227 for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
1228 const options = modelOptions[provider];
1229 if (options && options.length > 0) {
1230 const driverKind = ProviderDriverKind.make(provider);
1231 const instanceKey = defaultInstanceIdForDriver(driverKind);
1232 result[instanceKey] = createModelSelection(
1233 instanceKey,
1234 modelSelection?.instanceId === instanceKey
1235 ? modelSelection.model
1236 : (DEFAULT_MODEL_BY_PROVIDER[driverKind] ?? DEFAULT_MODEL),
1237 options,
1238 );
1239 }
1240 }
1241 }
1242 if (modelSelection) {
1243 result[modelSelection.instanceId] = modelSelection as ModelSelection;
1244 }
1245 return result;
1246 }
1247
1248 // Static aliases are shared across instances; exact custom slugs and catalog aliases are not.
1249 function composerModelIdentity(
1250 input: {
1251 providers: ReadonlyArray<ServerProvider>;
1252 settings: UnifiedSettings;
1253 selectedProvider: ProviderDriverKind;
1254 },
1255 instanceId: ProviderInstanceId,
1256 model: string | undefined,
1257 ) {
1258 const isCustom =
1259 input.providers
1260 .find((provider) => provider.instanceId === instanceId)
1261 ?.models.some((entry) => entry.slug === model && entry.isCustom) ||
1262 readInstanceCustomModels(input.settings, instanceId, input.selectedProvider).some(
1263 (entry) => entry.slug === model,
1264 );
1265 return isCustom ? model : normalizeModelSlug(model, input.selectedProvider);
1266 }
1267
1268 export function deriveEffectiveComposerModelState(input: {
1269 draft:
1270 | Pick<
1271 ComposerThreadDraftState,
1272 "modelSelectionByProvider" | "activeProvider" | "modelSelectionExplicit"
1273 >
1274 | null
1275 | undefined;
1276 threadStarted: boolean;
1277 providers: ReadonlyArray<ServerProvider>;
1278 selectedProvider: ProviderDriverKind;
1279 selectedInstanceId?: ProviderInstanceId | null | undefined;
1280 /** The instance the draft, thread or project asked for; differs from the selection on fallback. */
1281 requestedInstanceId?: ProviderInstanceId | null | undefined;
1282 threadModelSelection: ModelSelection | null | undefined;
1283 projectModelSelection: ModelSelection | null | undefined;
1284 settings: UnifiedSettings;
1285 }): EffectiveComposerModelState {
1286 const draft = draftModelSelectionApplies(input.draft, input.threadStarted) ? input.draft : null;
1287 const baseSelection = input.threadModelSelection ?? input.projectModelSelection;
1288 const baseModelCandidate = baseSelection?.model ?? null;
1289 const preserveThreadModel =
1290 input.selectedInstanceId !== null &&
1291 input.selectedInstanceId !== undefined &&
1292 input.threadModelSelection?.instanceId === input.selectedInstanceId;
1293 const baseModel =
1294 (input.selectedInstanceId
1295 ? resolveAppModelSelectionForInstance(
1296 input.selectedInstanceId,
1297 input.settings,
1298 input.providers,
1299 baseModelCandidate,
1300 { preserveUnavailableSelection: preserveThreadModel },
1301 )
1302 : null) ??
1303 // Antigravity has no static model or cross-account catalog fallback.
1304 (input.selectedProvider === "antigravity" && input.selectedInstanceId ? "" : null) ??
1305 resolveAppModelSelection(
1306 input.selectedProvider,
1307 input.settings,
1308 input.providers,
1309 baseModelCandidate,
1310 ) ??
1311 normalizeModelSlug(baseModelCandidate, input.selectedProvider) ??
1312 getDefaultServerModel(input.providers, input.selectedProvider);
1313 const instanceSelection = input.selectedInstanceId
1314 ? draft?.modelSelectionByProvider?.[input.selectedInstanceId]
1315 : undefined;
1316 // Legacy driver-keyed drafts belong to the default instance.
1317 const legacySelection =
1318 input.selectedInstanceId &&
1319 input.selectedInstanceId !== defaultInstanceIdForDriver(input.selectedProvider)
1320 ? undefined
1321 : draft?.modelSelectionByProvider?.[ProviderInstanceId.make(input.selectedProvider)];
1322 const activeSelection = instanceSelection ?? legacySelection;
1323 const activeSelectionInstanceId = instanceSelection
1324 ? (input.selectedInstanceId ?? ProviderInstanceId.make(input.selectedProvider))
1325 : ProviderInstanceId.make(input.selectedProvider);
1326 const selectedModel = activeSelection?.model
1327 ? (resolveAppModelSelectionForInstance(
1328 activeSelectionInstanceId,
1329 input.settings,
1330 input.providers,
1331 activeSelection.model,
1332 { preserveUnavailableSelection: true },
1333 ) ??
1334 (input.selectedProvider === "antigravity" ? "" : null) ??
1335 resolveAppModelSelection(
1336 input.selectedProvider,
1337 input.settings,
1338 input.providers,
1339 activeSelection.model,
1340 ))
1341 : baseModel;
1342 // Base options belong to the base model, so a draft pick of another model gets none of them.
1343 const draftPicksOtherModel =
1344 !!activeSelection?.model &&
1345 composerModelIdentity(input, activeSelectionInstanceId, activeSelection.model) !==
1346 composerModelIdentity(
1347 input,
1348 baseSelection?.instanceId ?? activeSelectionInstanceId,
1349 baseSelection?.model,
1350 );
1351 // An existing thread's options, even none, outrank the project's. Next to draft options, they
1352 // fill in only for the model they were stored with. Each source keeps its selections so a
1353 // fallback instance can check which model its options belong to.
1354 const optionsFrom = (optionSelections: Partial<Record<string, ModelSelection>> | null) =>
1355 withFallbackInstanceOptions({
1356 ...input,
1357 modelOptions: modelSelectionByProviderToOptions(optionSelections),
1358 optionSelections,
1359 selectedModel,
1360 });
1361 const draftOptions = optionsFrom(draft?.modelSelectionByProvider ?? null);
1362 const storedIsShownModel =
1363 baseSelection != null &&
1364 isSameModel(input, baseSelection, {
1365 instanceId: input.selectedInstanceId ?? baseSelection.instanceId,
1366 model: selectedModel,
1367 });
1368 const storedOptions = optionsFrom(
1369 !draftPicksOtherModel && (draftOptions === null || storedIsShownModel)
1370 ? selectionsByInstance(baseSelection)
1371 : null,
1372 );
1373
1374 return {
1375 selectedModel,
1376 modelOptions: draftOptions || storedOptions ? { ...storedOptions, ...draftOptions } : null,
1377 };
1378 }
1379
1380 /**
1381 * When the requested instance is disabled or unavailable, the composer shows another instance of
1382 * the same driver. When that instance has no options of its own and shows the model the requested
1383 * instance's options were picked with, it takes those options instead of the model's defaults.
1384 */
1385 function withFallbackInstanceOptions(input: {
1386 readonly modelOptions: ProviderOptionSelectionsByProvider | null;
1387 readonly optionSelections: Partial<Record<string, ModelSelection>> | null;
1388 readonly selectedModel: string;
1389 readonly providers: ReadonlyArray<ServerProvider>;
1390 readonly selectedProvider: ProviderDriverKind;
1391 readonly selectedInstanceId?: ProviderInstanceId | null | undefined;
1392 readonly requestedInstanceId?: ProviderInstanceId | null | undefined;
1393 readonly settings: UnifiedSettings;
1394 }): ProviderOptionSelectionsByProvider | null {
1395 const { modelOptions, selectedInstanceId, requestedInstanceId } = input;
1396 if (
1397 !modelOptions ||
1398 !selectedInstanceId ||
1399 !requestedInstanceId ||
1400 selectedInstanceId === requestedInstanceId ||
1401 modelOptions[selectedInstanceId] !== undefined
1402 ) {
1403 return modelOptions;
1404 }
1405 const requestedOptions = modelOptions[requestedInstanceId];
1406 const requestedProvider = input.providers.find(
1407 (provider) => provider.instanceId === requestedInstanceId,
1408 );
1409 const sameModel = isSameModel(
1410 input,
1411 {
1412 instanceId: requestedInstanceId,
1413 model: input.optionSelections?.[requestedInstanceId]?.model,
1414 },
1415 { instanceId: selectedInstanceId, model: input.selectedModel },
1416 );
1417 if (!requestedOptions || requestedProvider?.driver !== input.selectedProvider || !sameModel) {
1418 return modelOptions;
1419 }
1420 return { ...modelOptions, [selectedInstanceId]: requestedOptions };
1421 }
1422
1423 interface InstanceModel {
1424 readonly instanceId: ProviderInstanceId;
1425 readonly model: string | undefined;
1426 }
1427
1428 export function isSameModel(
1429 input: {
1430 readonly providers: ReadonlyArray<ServerProvider>;
1431 readonly selectedProvider: ProviderDriverKind;
1432 readonly settings: UnifiedSettings;
1433 },
1434 a: InstanceModel,
1435 b: InstanceModel,
1436 ): boolean {
1437 return (
1438 a.model === b.model ||
1439 composerModelIdentity(input, a.instanceId, a.model) ===
1440 composerModelIdentity(input, b.instanceId, b.model)
1441 );
1442 }
1443
1444 function revokeObjectPreviewUrl(previewUrl: string): void {
1445 if (typeof URL === "undefined") {
1446 return;
1447 }
1448 if (!previewUrl.startsWith("blob:")) {
1449 return;
1450 }
1451 URL.revokeObjectURL(previewUrl);
1452 }
1453
1454 function revokeDraftThreadPreviewUrls(draft: ComposerThreadDraftState | undefined): void {
1455 if (!draft) {
1456 return;
1457 }
1458 for (const image of draft.images) {
1459 revokeObjectPreviewUrl(image.previewUrl);
1460 }
1461 }
1462
1463 function normalizePersistedAttachment(value: unknown): PersistedComposerImageAttachment | null {
1464 if (!value || typeof value !== "object") {
1465 return null;
1466 }
1467 const candidate = value as Record<string, unknown>;
1468 const id = candidate.id;
1469 const name = candidate.name;
1470 const mimeType = candidate.mimeType;
1471 const sizeBytes = candidate.sizeBytes;
1472 const dataUrl = candidate.dataUrl;
1473 if (
1474 typeof id !== "string" ||
1475 typeof name !== "string" ||
1476 typeof mimeType !== "string" ||
1477 typeof sizeBytes !== "number" ||
1478 !Number.isFinite(sizeBytes) ||
1479 typeof dataUrl !== "string" ||
1480 id.length === 0 ||
1481 dataUrl.length === 0
1482 ) {
1483 return null;
1484 }
1485 return {
1486 id,
1487 name,
1488 mimeType,
1489 sizeBytes,
1490 dataUrl,
1491 ...(isSnapShotSource(candidate.source) ? { source: candidate.source } : {}),
1492 };
1493 }
1494
1495 function normalizePersistedTerminalContextDraft(
1496 value: unknown,
1497 ): PersistedTerminalContextDraft | null {
1498 if (!value || typeof value !== "object") {
1499 return null;
1500 }
1501 const candidate = value as Record<string, unknown>;
1502 const id = candidate.id;
1503 const threadId = candidate.threadId;
1504 const createdAt = candidate.createdAt;
1505 const lineStart = candidate.lineStart;
1506 const lineEnd = candidate.lineEnd;
1507 if (
1508 typeof id !== "string" ||
1509 id.length === 0 ||
1510 typeof threadId !== "string" ||
1511 threadId.length === 0 ||
1512 typeof createdAt !== "string" ||
1513 createdAt.length === 0 ||
1514 typeof lineStart !== "number" ||
1515 !Number.isFinite(lineStart) ||
1516 typeof lineEnd !== "number" ||
1517 !Number.isFinite(lineEnd)
1518 ) {
1519 return null;
1520 }
1521 const terminalId = typeof candidate.terminalId === "string" ? candidate.terminalId.trim() : "";
1522 const terminalLabel =
1523 typeof candidate.terminalLabel === "string" ? candidate.terminalLabel.trim() : "";
1524 if (terminalId.length === 0 || terminalLabel.length === 0) {
1525 return null;
1526 }
1527 const normalizedLineStart = Math.max(1, Math.floor(lineStart));
1528 const normalizedLineEnd = Math.max(normalizedLineStart, Math.floor(lineEnd));
1529 return {
1530 id: toComposerContextId(id),
1531 threadId: threadId as ThreadId,
1532 createdAt,
1533 terminalId,
1534 terminalLabel,
1535 lineStart: normalizedLineStart,
1536 lineEnd: normalizedLineEnd,
1537 ...(typeof candidate.text === "string" ? { text: candidate.text } : {}),
1538 };
1539 }
1540
1541 function normalizeDraftThreadEnvMode(
1542 value: unknown,
1543 fallbackWorktreePath: string | null,
1544 ): DraftThreadEnvMode {
1545 if (value === "local" || value === "worktree") {
1546 return value;
1547 }
1548 return fallbackWorktreePath ? "worktree" : "local";
1549 }
1550
1551 function projectDraftKey(projectRef: ScopedProjectRef): string {
1552 return scopedProjectKey(projectRef);
1553 }
1554
1555 function logicalProjectDraftKey(logicalProjectKey: string): string {
1556 return logicalProjectKey.trim();
1557 }
1558
1559 export function composerTargetKey(target: ScopedThreadRef | DraftId): string {
1560 if (typeof target === "string") {
1561 return target.trim();
1562 }
1563 return scopedThreadKey(target);
1564 }
1565
1566 function normalizeLegacyComposerStorageKey(
1567 threadKeyOrId: string,
1568 options?: {
1569 environmentId?: EnvironmentId;
1570 },
1571 ): string {
1572 const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
1573 if (parsedThreadRef) {
1574 return composerTargetKey(parsedThreadRef);
1575 }
1576 if (options?.environmentId) {
1577 return composerTargetKey(scopeThreadRef(options.environmentId, threadKeyOrId as ThreadId));
1578 }
1579 return threadKeyOrId;
1580 }
1581
1582 function composerThreadRefFromKey(threadKey: string): ScopedThreadRef | null {
1583 return parseScopedThreadKey(threadKey);
1584 }
1585
1586 type ComposerThreadLookupState = Pick<
1587 ComposerDraftStoreState,
1588 "draftsByThreadKey" | "draftThreadsByThreadKey"
1589 >;
1590
1591 function normalizeComposerTarget(
1592 state: ComposerThreadLookupState,
1593 target: ComposerThreadTarget,
1594 ): ComposerThreadTarget | null {
1595 if (typeof target === "string") {
1596 const draftId = target.trim();
1597 return draftId.length > 0 ? DraftId.make(draftId) : null;
1598 }
1599 return target;
1600 }
1601
1602 export function resolveComposerDraftKey(
1603 state: ComposerThreadLookupState,
1604 target: ComposerThreadTarget,
1605 ): string | null {
1606 const normalizedTarget = normalizeComposerTarget(state, target);
1607 if (!normalizedTarget) {
1608 return null;
1609 }
1610 if (typeof normalizedTarget !== "string") {
1611 const scopedKey = composerTargetKey(normalizedTarget);
1612 if (state.draftsByThreadKey[scopedKey]) {
1613 return scopedKey;
1614 }
1615 for (const [draftId, draftSession] of Object.entries(state.draftThreadsByThreadKey)) {
1616 if (
1617 draftSession.environmentId === normalizedTarget.environmentId &&
1618 draftSession.threadId === normalizedTarget.threadId
1619 ) {
1620 return draftId;
1621 }
1622 }
1623 return scopedKey;
1624 }
1625 const threadKey = composerTargetKey(normalizedTarget);
1626 return threadKey.length > 0 ? threadKey : null;
1627 }
1628
1629 const QUEUED_RUN_EDIT_DRAFT_PREFIX = "queued-edit:";
1630
1631 // Thread and run ids both contain colons, so the run id is encoded to keep the thread key parseable.
1632 export function queuedRunEditDraftId(threadRef: ScopedThreadRef, runId: string): DraftId {
1633 return DraftId.make(
1634 `${QUEUED_RUN_EDIT_DRAFT_PREFIX}${scopedThreadKey(threadRef)}:${encodeURIComponent(runId)}`,
1635 );
1636 }
1637
1638 function queuedRunEditThreadId(draftId: string): ThreadId | null {
1639 if (!draftId.startsWith(QUEUED_RUN_EDIT_DRAFT_PREFIX)) return null;
1640 const rest = draftId.slice(QUEUED_RUN_EDIT_DRAFT_PREFIX.length);
1641 return parseScopedThreadKey(rest.slice(0, rest.lastIndexOf(":")))?.threadId ?? null;
1642 }
1643
1644 function resolveComposerThreadId(
1645 state: ComposerThreadLookupState,
1646 target: ComposerThreadTarget,
1647 ): ThreadId | null {
1648 const normalizedTarget = normalizeComposerTarget(state, target);
1649 if (!normalizedTarget) {
1650 return null;
1651 }
1652 if (typeof normalizedTarget !== "string") {
1653 return normalizedTarget.threadId;
1654 }
1655 return (
1656 state.draftThreadsByThreadKey[normalizedTarget]?.threadId ??
1657 queuedRunEditThreadId(normalizedTarget)
1658 );
1659 }
1660
1661 function getComposerDraftState(
1662 state: Pick<ComposerDraftStoreState, "draftsByThreadKey" | "draftThreadsByThreadKey">,
1663 target: ComposerThreadTarget,
1664 ): ComposerThreadDraftState | null {
1665 const threadKey = resolveComposerDraftKey(state, target);
1666 if (!threadKey) {
1667 return null;
1668 }
1669 return state.draftsByThreadKey[threadKey] ?? null;
1670 }
1671
1672 /** Where a draft lives now: its thread once promoted, or null once it was discarded. */
1673 export function resolveLiveComposerDraftTarget(
1674 target: ComposerThreadTarget,
1675 ): ComposerThreadTarget | null {
1676 if (typeof target !== "string") return target;
1677 const state = composerDraftStore.getState();
1678 const promoted = state.promotedDraftRedirects[target];
1679 if (promoted) return promoted;
1680 return state.draftThreadsByThreadKey[target] || state.draftsByThreadKey[target] ? target : null;
1681 }
1682
1683 /** The stored prompt for a target, empty when it has no draft, or null when the target is gone. */
1684 export function readComposerDraftPrompt(target: ComposerThreadTarget): string | null {
1685 const live = resolveLiveComposerDraftTarget(target);
1686 if (live === null) return null;
1687 const state = composerDraftStore.getState();
1688 const threadKey = resolveComposerDraftKey(state, live);
1689 if (!threadKey) return null;
1690 return state.draftsByThreadKey[threadKey]?.prompt ?? "";
1691 }
1692
1693 function draftThreadHasOpenPreview(draftThread: DraftThreadState | undefined): boolean {
1694 if (draftThread === undefined) return false;
1695 const ref = scopeThreadRef(draftThread.environmentId, draftThread.threadId);
1696 return Object.keys(readThreadPreviewState(ref).sessions).length > 0;
1697 }
1698
1699 function isComposerThreadKeyInUse(mappings: Record<string, string>, threadKey: string): boolean {
1700 return Object.values(mappings).includes(threadKey);
1701 }
1702
1703 function toProjectDraftSession(
1704 draftId: DraftId,
1705 draftSession: DraftSessionState,
1706 ): ProjectDraftSession {
1707 return {
1708 draftId,
1709 ...draftSession,
1710 };
1711 }
1712
1713 function createDraftThreadState(
1714 projectRef: ScopedProjectRef,
1715 threadId: ThreadId,
1716 logicalProjectKey: string,
1717 existingThread: DraftThreadState | undefined,
1718 options?: {
1719 threadId?: ThreadId;
1720 branch?: string | null;
1721 worktreePath?: string | null;
1722 createdAt?: string;
1723 envMode?: DraftThreadEnvMode;
1724 startFromOrigin?: boolean;
1725 runtimeMode?: RuntimeMode;
1726 interactionMode?: ProviderInteractionMode;
1727 environmentSelection?: "auto" | "manual";
1728 loadBalancedEnvironmentId?: EnvironmentId | null;
1729 checkoutPullRequest?: DraftCheckoutPullRequest | null;
1730 },
1731 ): DraftThreadState {
1732 const projectChanged =
1733 existingThread !== undefined &&
1734 (existingThread.environmentId !== projectRef.environmentId ||
1735 existingThread.projectId !== projectRef.projectId);
1736 const nextWorktreePath =
1737 options?.worktreePath === undefined
1738 ? projectChanged
1739 ? null
1740 : (existingThread?.worktreePath ?? null)
1741 : (options.worktreePath ?? null);
1742 const nextBranch =
1743 options?.branch === undefined
1744 ? projectChanged
1745 ? null
1746 : (existingThread?.branch ?? null)
1747 : (options.branch ?? null);
1748 const nextStartFromOrigin =
1749 options?.startFromOrigin === undefined
1750 ? (existingThread?.startFromOrigin ?? false)
1751 : options.startFromOrigin;
1752 const environmentSelection =
1753 options?.environmentSelection ?? existingThread?.environmentSelection;
1754 const checkoutPullRequest = resolveCheckoutPullRequest(
1755 existingThread,
1756 options?.checkoutPullRequest,
1757 projectChanged,
1758 );
1759 return {
1760 threadId,
1761 environmentId: projectRef.environmentId,
1762 projectId: projectRef.projectId,
1763 logicalProjectKey,
1764 ...(environmentSelection ? { environmentSelection } : {}),
1765 ...(options?.loadBalancedEnvironmentId !== undefined
1766 ? { loadBalancedEnvironmentId: options.loadBalancedEnvironmentId }
1767 : existingThread?.loadBalancedEnvironmentId !== undefined
1768 ? {
1769 loadBalancedEnvironmentId: projectChanged
1770 ? null
1771 : existingThread.loadBalancedEnvironmentId,
1772 }
1773 : {}),
1774 createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),
1775 runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
1776 interactionMode:
1777 options?.interactionMode ?? existingThread?.interactionMode ?? DEFAULT_INTERACTION_MODE,
1778 branch: nextBranch,
1779 worktreePath: nextWorktreePath,
1780 envMode:
1781 options?.envMode ?? (nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")),
1782 startFromOrigin: nextStartFromOrigin,
1783 ...(checkoutPullRequest ? { checkoutPullRequest } : {}),
1784 promotedTo: null,
1785 };
1786 }
1787
1788 /** An explicit value wins; otherwise a checkout's pull request stays with its project. */
1789 function resolveCheckoutPullRequest(
1790 existing: DraftThreadState | undefined,
1791 explicit: DraftCheckoutPullRequest | null | undefined,
1792 projectChanged: boolean,
1793 ): DraftCheckoutPullRequest | undefined {
1794 if (explicit !== undefined) return explicit ?? undefined;
1795 return projectChanged ? undefined : existing?.checkoutPullRequest;
1796 }
1797
1798 function checkoutPullRequestsEqual(
1799 left: DraftCheckoutPullRequest | undefined,
1800 right: DraftCheckoutPullRequest | undefined,
1801 ): boolean {
1802 return left === right || (left?.url === right?.url && left?.branch === right?.branch);
1803 }
1804
1805 function scopedThreadRefsEqual(
1806 left: ScopedThreadRef | null | undefined,
1807 right: ScopedThreadRef | null | undefined,
1808 ): boolean {
1809 if (!left || !right) {
1810 return left === right;
1811 }
1812 return left.environmentId === right.environmentId && left.threadId === right.threadId;
1813 }
1814
1815 function isDraftThreadPromoting(draftThread: DraftThreadState | null | undefined): boolean {
1816 return draftThread?.promotedTo !== null && draftThread?.promotedTo !== undefined;
1817 }
1818
1819 function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThreadState): boolean {
1820 return (
1821 !!left &&
1822 left.threadId === right.threadId &&
1823 left.environmentId === right.environmentId &&
1824 left.projectId === right.projectId &&
1825 left.logicalProjectKey === right.logicalProjectKey &&
1826 left.environmentSelection === right.environmentSelection &&
1827 left.loadBalancedEnvironmentId === right.loadBalancedEnvironmentId &&
1828 left.createdAt === right.createdAt &&
1829 left.runtimeMode === right.runtimeMode &&
1830 left.interactionMode === right.interactionMode &&
1831 left.branch === right.branch &&
1832 left.worktreePath === right.worktreePath &&
1833 left.envMode === right.envMode &&
1834 left.startFromOrigin === right.startFromOrigin &&
1835 checkoutPullRequestsEqual(left.checkoutPullRequest, right.checkoutPullRequest) &&
1836 scopedThreadRefsEqual(left.promotedTo, right.promotedTo)
1837 );
1838 }
1839
1840 function removeDraftThreadReferences(
1841 state: Pick<
1842 ComposerDraftStoreState,
1843 | "draftThreadsByThreadKey"
1844 | "draftsByThreadKey"
1845 | "logicalProjectDraftThreadKeyByLogicalProjectKey"
1846 >,
1847 threadKey: string,
1848 composerDestination?: ScopedThreadRef,
1849 ): Pick<
1850 ComposerDraftStoreState,
1851 | "draftThreadsByThreadKey"
1852 | "draftsByThreadKey"
1853 | "logicalProjectDraftThreadKeyByLogicalProjectKey"
1854 > {
1855 const nextLogicalMappings = Object.fromEntries(
1856 Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(
1857 ([, draftThreadKey]) => draftThreadKey !== threadKey,
1858 ),
1859 ) as Record<string, string>;
1860 const { [threadKey]: _removedDraftThread, ...restDraftThreadsByThreadKey } =
1861 state.draftThreadsByThreadKey;
1862 const { [threadKey]: removedComposerDraft, ...restDraftsByThreadKey } = state.draftsByThreadKey;
1863 if (composerDestination && removedComposerDraft) {
1864 restDraftsByThreadKey[composerTargetKey(composerDestination)] = removedComposerDraft;
1865 } else {
1866 revokeDraftThreadPreviewUrls(removedComposerDraft);
1867 }
1868 return {
1869 draftsByThreadKey: restDraftsByThreadKey,
1870 draftThreadsByThreadKey: restDraftThreadsByThreadKey,
1871 logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings,
1872 };
1873 }
1874
1875 function normalizePersistedCheckoutPullRequest(value: unknown): DraftCheckoutPullRequest | null {
1876 if (!value || typeof value !== "object") return null;
1877 const { url, branch } = value as Record<string, unknown>;
1878 return typeof url === "string" &&
1879 url.length > 0 &&
1880 typeof branch === "string" &&
1881 branch.length > 0
1882 ? { url, branch }
1883 : null;
1884 }
1885
1886 function normalizePersistedDraftThreads(
1887 rawDraftThreadsByThreadId: unknown,
1888 rawProjectDraftThreadIdByProjectKey: unknown,
1889 ): Pick<
1890 PersistedComposerDraftStoreState,
1891 "draftThreadsByThreadKey" | "logicalProjectDraftThreadKeyByLogicalProjectKey"
1892 > {
1893 const draftThreadsByThreadKey: Record<string, PersistedDraftThreadState> = {};
1894 const environmentIdByThreadId = new Map<ThreadId, EnvironmentId>();
1895 if (
1896 rawProjectDraftThreadIdByProjectKey &&
1897 typeof rawProjectDraftThreadIdByProjectKey === "object"
1898 ) {
1899 for (const [projectKey, threadId] of Object.entries(
1900 rawProjectDraftThreadIdByProjectKey as Record<string, unknown>,
1901 )) {
1902 if (typeof threadId !== "string" || threadId.length === 0) {
1903 continue;
1904 }
1905 const projectRef = parseScopedProjectKey(projectKey);
1906 if (!projectRef) {
1907 continue;
1908 }
1909 const parsedThreadRef = parseScopedThreadKey(threadId);
1910 if (parsedThreadRef) {
1911 environmentIdByThreadId.set(parsedThreadRef.threadId, parsedThreadRef.environmentId);
1912 continue;
1913 }
1914 environmentIdByThreadId.set(threadId as ThreadId, projectRef.environmentId);
1915 }
1916 }
1917 if (rawDraftThreadsByThreadId && typeof rawDraftThreadsByThreadId === "object") {
1918 for (const [threadKeyOrId, rawDraftThread] of Object.entries(
1919 rawDraftThreadsByThreadId as Record<string, unknown>,
1920 )) {
1921 if (typeof threadKeyOrId !== "string" || threadKeyOrId.length === 0) {
1922 continue;
1923 }
1924 if (!rawDraftThread || typeof rawDraftThread !== "object") {
1925 continue;
1926 }
1927 const candidateDraftThread = rawDraftThread as Record<string, unknown>;
1928 const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
1929 const threadKey = normalizeLegacyComposerStorageKey(threadKeyOrId);
1930 const threadId =
1931 parsedThreadRef?.threadId ??
1932 (typeof candidateDraftThread.threadId === "string" &&
1933 candidateDraftThread.threadId.length > 0
1934 ? (candidateDraftThread.threadId as ThreadId)
1935 : (threadKeyOrId as ThreadId));
1936 const environmentId =
1937 parsedThreadRef?.environmentId ??
1938 (typeof candidateDraftThread.environmentId === "string" &&
1939 candidateDraftThread.environmentId.length > 0
1940 ? (candidateDraftThread.environmentId as EnvironmentId)
1941 : environmentIdByThreadId.get(threadKeyOrId as ThreadId));
1942 const projectId = candidateDraftThread.projectId;
1943 const createdAt = candidateDraftThread.createdAt;
1944 const branch = candidateDraftThread.branch;
1945 const worktreePath = candidateDraftThread.worktreePath;
1946 const startFromOrigin = candidateDraftThread.startFromOrigin === true;
1947 const normalizedWorktreePath = typeof worktreePath === "string" ? worktreePath : null;
1948 const checkoutPullRequest = normalizePersistedCheckoutPullRequest(
1949 candidateDraftThread.checkoutPullRequest,
1950 );
1951 const promotedToCandidate = candidateDraftThread.promotedTo;
1952 const promotedToRecord =
1953 promotedToCandidate && typeof promotedToCandidate === "object"
1954 ? (promotedToCandidate as Record<string, unknown>)
1955 : null;
1956 const promotedTo =
1957 promotedToRecord &&
1958 typeof promotedToRecord.environmentId === "string" &&
1959 promotedToRecord.environmentId.length > 0 &&
1960 typeof promotedToRecord.threadId === "string" &&
1961 promotedToRecord.threadId.length > 0
1962 ? scopeThreadRef(
1963 promotedToRecord.environmentId as EnvironmentId,
1964 promotedToRecord.threadId as ThreadId,
1965 )
1966 : null;
1967 if (typeof projectId !== "string" || projectId.length === 0 || environmentId === undefined) {
1968 continue;
1969 }
1970 const normalizedEnvironmentId = environmentId as EnvironmentId;
1971 draftThreadsByThreadKey[threadKey] = {
1972 threadId,
1973 environmentId: normalizedEnvironmentId,
1974 projectId: projectId as ProjectId,
1975 logicalProjectKey:
1976 typeof candidateDraftThread.logicalProjectKey === "string" &&
1977 candidateDraftThread.logicalProjectKey.length > 0
1978 ? candidateDraftThread.logicalProjectKey
1979 : parsedThreadRef
1980 ? projectDraftKey(scopeProjectRef(normalizedEnvironmentId, projectId as ProjectId))
1981 : threadKeyOrId,
1982 createdAt:
1983 typeof createdAt === "string" && createdAt.length > 0
1984 ? createdAt
1985 : new Date().toISOString(),
1986 runtimeMode: isRuntimeMode(candidateDraftThread.runtimeMode)
1987 ? candidateDraftThread.runtimeMode
1988 : DEFAULT_RUNTIME_MODE,
1989 interactionMode:
1990 candidateDraftThread.interactionMode === "plan" ||
1991 candidateDraftThread.interactionMode === "default"
1992 ? candidateDraftThread.interactionMode
1993 : DEFAULT_INTERACTION_MODE,
1994 branch: typeof branch === "string" ? branch : null,
1995 worktreePath: normalizedWorktreePath,
1996 envMode: normalizeDraftThreadEnvMode(candidateDraftThread.envMode, normalizedWorktreePath),
1997 startFromOrigin,
1998 ...(candidateDraftThread.environmentSelection === "manual" ||
1999 candidateDraftThread.environmentSelection === "auto"
2000 ? { environmentSelection: candidateDraftThread.environmentSelection }
2001 : {}),
2002 ...(typeof candidateDraftThread.loadBalancedEnvironmentId === "string" &&
2003 candidateDraftThread.loadBalancedEnvironmentId.length > 0
2004 ? { loadBalancedEnvironmentId: candidateDraftThread.loadBalancedEnvironmentId }
2005 : candidateDraftThread.loadBalancedEnvironmentId === null
2006 ? { loadBalancedEnvironmentId: null }
2007 : {}),
2008 ...(checkoutPullRequest ? { checkoutPullRequest } : {}),
2009 promotedTo,
2010 };
2011 }
2012 }
2013
2014 const logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string> = {};
2015 if (
2016 rawProjectDraftThreadIdByProjectKey &&
2017 typeof rawProjectDraftThreadIdByProjectKey === "object"
2018 ) {
2019 for (const [logicalProjectKey, threadKeyOrId] of Object.entries(
2020 rawProjectDraftThreadIdByProjectKey as Record<string, unknown>,
2021 )) {
2022 if (typeof threadKeyOrId !== "string" || threadKeyOrId.length === 0) {
2023 continue;
2024 }
2025 const projectRef = parseScopedProjectKey(logicalProjectKey);
2026 const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
2027 const threadKey = normalizeLegacyComposerStorageKey(threadKeyOrId);
2028 logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] = threadKey;
2029 const existingDraftThread = draftThreadsByThreadKey[threadKey];
2030 if (parsedThreadRef) {
2031 environmentIdByThreadId.set(parsedThreadRef.threadId, parsedThreadRef.environmentId);
2032 }
2033 // Logical keys may contain workspace paths; a matching draft's concrete project id wins.
2034 if (existingDraftThread?.logicalProjectKey === logicalProjectKey) {
2035 continue;
2036 }
2037 if (!projectRef) {
2038 if (existingDraftThread) {
2039 draftThreadsByThreadKey[threadKey] = {
2040 ...existingDraftThread,
2041 logicalProjectKey,
2042 };
2043 }
2044 continue;
2045 }
2046 if (!existingDraftThread) {
2047 draftThreadsByThreadKey[threadKey] = {
2048 threadId: parsedThreadRef?.threadId ?? (threadKey as ThreadId),
2049 environmentId: projectRef.environmentId,
2050 projectId: projectRef.projectId,
2051 logicalProjectKey,
2052 createdAt: new Date().toISOString(),
2053 runtimeMode: DEFAULT_RUNTIME_MODE,
2054 interactionMode: DEFAULT_INTERACTION_MODE,
2055 branch: null,
2056 worktreePath: null,
2057 envMode: "local",
2058 startFromOrigin: false,
2059 promotedTo: null,
2060 };
2061 } else if (
2062 existingDraftThread.projectId !== projectRef.projectId ||
2063 existingDraftThread.environmentId !== projectRef.environmentId
2064 ) {
2065 draftThreadsByThreadKey[threadKey] = {
2066 ...existingDraftThread,
2067 threadId: existingDraftThread.threadId,
2068 environmentId: projectRef.environmentId,
2069 projectId: projectRef.projectId,
2070 logicalProjectKey,
2071 };
2072 }
2073 }
2074 }
2075
2076 return { draftThreadsByThreadKey, logicalProjectDraftThreadKeyByLogicalProjectKey };
2077 }
2078
2079 const decodePersistedModelSelection = Schema.decodeUnknownOption(ModelSelection);
2080
2081 /** Storage v3-v5 wrote `provider` and object-shaped options; the schema upgrades both. */
2082 function normalizePersistedModelSelectionByProvider(
2083 value: object,
2084 ): Partial<Record<ProviderInstanceId, ModelSelection>> {
2085 return Object.fromEntries(
2086 Object.entries(value).flatMap(([instanceId, selection]) =>
2087 Option.match(decodePersistedModelSelection(selection), {
2088 onNone: () => [],
2089 onSome: (decoded) => [[instanceId, decoded] as const],
2090 }),
2091 ),
2092 );
2093 }
2094
2095 function normalizePersistedDraftsByThreadId(
2096 rawDraftMap: unknown,
2097 draftThreadsByThreadKey: PersistedComposerDraftStoreState["draftThreadsByThreadKey"],
2098 ): PersistedComposerDraftStoreState["draftsByThreadKey"] {
2099 if (!rawDraftMap || typeof rawDraftMap !== "object") {
2100 return {};
2101 }
2102
2103 const environmentIdByThreadId = new Map<ThreadId, EnvironmentId>();
2104 for (const [threadKey, draftThread] of Object.entries(draftThreadsByThreadKey)) {
2105 const parsedThreadRef = composerThreadRefFromKey(threadKey);
2106 if (!parsedThreadRef) {
2107 continue;
2108 }
2109 environmentIdByThreadId.set(
2110 parsedThreadRef.threadId,
2111 draftThread.environmentId as EnvironmentId,
2112 );
2113 }
2114
2115 const nextDraftsByThreadKey: DeepMutable<PersistedComposerDraftStoreState["draftsByThreadKey"]> =
2116 {};
2117 for (const [threadKeyOrId, draftValue] of Object.entries(
2118 rawDraftMap as Record<string, unknown>,
2119 )) {
2120 if (typeof threadKeyOrId !== "string" || threadKeyOrId.length === 0) {
2121 continue;
2122 }
2123 if (!draftValue || typeof draftValue !== "object") {
2124 continue;
2125 }
2126 const draftCandidate = draftValue as PersistedComposerThreadDraftState;
2127 const promptCandidate = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
2128 const attachments = Array.isArray(draftCandidate.attachments)
2129 ? draftCandidate.attachments.flatMap((entry) => {
2130 const normalized = normalizePersistedAttachment(entry);
2131 return normalized ? [normalized] : [];
2132 })
2133 : [];
2134 const files = Array.isArray(draftCandidate.files)
2135 ? draftCandidate.files.filter(isPersistedComposerDraftFileAttachment)
2136 : [];
2137 const terminalContexts = Array.isArray(draftCandidate.terminalContexts)
2138 ? draftCandidate.terminalContexts.flatMap((entry) => {
2139 const normalized = normalizePersistedTerminalContextDraft(entry);
2140 return normalized ? [normalized] : [];
2141 })
2142 : [];
2143 const reviewComments = Array.isArray(draftCandidate.reviewComments)
2144 ? draftCandidate.reviewComments.filter(isReviewCommentContext)
2145 : [];
2146 const threadContexts = Array.isArray(draftCandidate.threadContexts)
2147 ? draftCandidate.threadContexts.filter(isThreadContextRecord)
2148 : [];
2149 const environmentContexts = Array.isArray(draftCandidate.environmentContexts)
2150 ? draftCandidate.environmentContexts.filter(isEnvironmentContextRecord)
2151 : [];
2152 const previewAnnotations = Array.isArray(draftCandidate.previewAnnotations)
2153 ? draftCandidate.previewAnnotations.filter(isPreviewAnnotationPayload)
2154 : [];
2155 const replyTo = isResponseContextRecord(draftCandidate.replyTo) ? draftCandidate.replyTo : null;
2156 const legacyElements =
2157 "elementContexts" in draftValue && Array.isArray(draftValue.elementContexts)
2158 ? draftValue.elementContexts
2159 : [];
2160 for (const element of legacyElements) {
2161 if (
2162 !isElementContextDetails(element) ||
2163 !("id" in element) ||
2164 typeof element.id !== "string" ||
2165 !("pickedAt" in element) ||
2166 typeof element.pickedAt !== "string"
2167 )
2168 continue;
2169 if (!previewAnnotations.some((annotation) => annotation.id === element.id)) {
2170 previewAnnotations.push(
2171 elementContextToPreviewAnnotation(element, element.id, element.pickedAt),
2172 );
2173 }
2174 }
2175 const runtimeMode = isRuntimeMode(draftCandidate.runtimeMode)
2176 ? draftCandidate.runtimeMode
2177 : null;
2178 const interactionMode =
2179 draftCandidate.interactionMode === "plan" || draftCandidate.interactionMode === "default"
2180 ? draftCandidate.interactionMode
2181 : null;
2182 const contextIds = new Map<string, string>();
2183 for (const [kind, entries] of [
2184 ["image", attachments],
2185 ["file", files],
2186 ["terminal", terminalContexts],
2187 ["review-comment", reviewComments],
2188 ["preview-annotation", previewAnnotations],
2189 ] as const) {
2190 for (const entry of entries) {
2191 const contextId = toKindScopedComposerContextId(kind, entry.id);
2192 contextIds.set(`${kind}/${entry.id}`, contextId);
2193 contextIds.set(`${kind}/${toComposerContextId(entry.id)}`, contextId);
2194 if (kind === "preview-annotation") {
2195 contextIds.set(`${kind}/${toComposerContextId(`annotation-${entry.id}`)}`, contextId);
2196 }
2197 }
2198 for (const entry of entries) {
2199 const contextId = toKindScopedComposerContextId(kind, entry.id);
2200 contextIds.set(`${kind}/${contextId}`, contextId);
2201 }
2202 }
2203 const migratedPrompt = promptCandidate.replace(
2204 /!?\[([^\]\r\n]*)\]\(t3-context:\/\/v1\/([a-z-]+)\/([^/()\r\n]+)\)/g,
2205 (source, label: string, kind: string, id: string) => {
2206 const contextId = contextIds.get(`${kind}/${id}`);
2207 return contextId ? formatInlineContextReference({ kind, contextId, label }) : source;
2208 },
2209 );
2210 const prompt = ensureInlineContextReferences(
2211 migrateLegacyTerminalContextPlaceholders(migratedPrompt, terminalContexts),
2212 terminalContexts.map((context) => terminalContextReference({ ...context, text: "" })),
2213 );
2214 const legacyDraftCandidate = draftValue as LegacyPersistedComposerThreadDraftState;
2215 let modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> = {};
2216 let activeProvider: ProviderInstanceId | null = null;
2217 let modelSelectionExplicit: true | undefined = undefined;
2218
2219 if (
2220 draftCandidate.modelSelectionByProvider &&
2221 typeof draftCandidate.modelSelectionByProvider === "object"
2222 ) {
2223 modelSelectionByProvider = normalizePersistedModelSelectionByProvider(
2224 draftCandidate.modelSelectionByProvider,
2225 );
2226 activeProvider = normalizeProviderInstanceId(draftCandidate.activeProvider);
2227 modelSelectionExplicit = draftCandidate.modelSelectionExplicit === true ? true : undefined;
2228 } else {
2229 const normalizedModelOptions =
2230 normalizeProviderModelOptions(
2231 legacyDraftCandidate.modelOptions,
2232 undefined,
2233 legacyDraftCandidate,
2234 ) ?? null;
2235 const normalizedModelSelection = normalizeModelSelection(
2236 legacyDraftCandidate.modelSelection,
2237 {
2238 provider: legacyDraftCandidate.provider,
2239 model: legacyDraftCandidate.model,
2240 modelOptions: normalizedModelOptions ?? (legacyDraftCandidate.modelOptions as unknown),
2241 legacyCodex: legacyDraftCandidate,
2242 },
2243 );
2244 const mergedModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
2245 normalizedModelSelection,
2246 normalizedModelOptions,
2247 );
2248 const modelSelection = legacySyncModelSelectionOptions(
2249 normalizedModelSelection,
2250 mergedModelOptions,
2251 );
2252 modelSelectionByProvider = legacyToModelSelectionByProvider(
2253 modelSelection,
2254 mergedModelOptions,
2255 );
2256 activeProvider = modelSelection?.instanceId ?? null;
2257 }
2258
2259 const hasModelData =
2260 Object.keys(modelSelectionByProvider).length > 0 || activeProvider !== null;
2261 if (
2262 promptCandidate.length === 0 &&
2263 attachments.length === 0 &&
2264 files.length === 0 &&
2265 terminalContexts.length === 0 &&
2266 previewAnnotations.length === 0 &&
2267 reviewComments.length === 0 &&
2268 threadContexts.length === 0 &&
2269 environmentContexts.length === 0 &&
2270 replyTo === null &&
2271 !hasModelData &&
2272 !runtimeMode &&
2273 !interactionMode
2274 ) {
2275 continue;
2276 }
2277 const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
2278 const normalizedThreadKey =
2279 parsedThreadRef !== null
2280 ? normalizeLegacyComposerStorageKey(threadKeyOrId)
2281 : draftThreadsByThreadKey[threadKeyOrId] !== undefined
2282 ? threadKeyOrId
2283 : (() => {
2284 const environmentId = environmentIdByThreadId.get(threadKeyOrId as ThreadId);
2285 return environmentId
2286 ? normalizeLegacyComposerStorageKey(threadKeyOrId, { environmentId })
2287 : threadKeyOrId;
2288 })();
2289 nextDraftsByThreadKey[normalizedThreadKey] = {
2290 prompt,
2291 attachments,
2292 ...(files.length > 0 ? { files } : {}),
2293 ...(terminalContexts.length > 0 ? { terminalContexts } : {}),
2294 ...(previewAnnotations.length > 0 ? { previewAnnotations } : {}),
2295 ...(reviewComments.length > 0 ? { reviewComments } : {}),
2296 ...(threadContexts.length > 0 ? { threadContexts } : {}),
2297 ...(environmentContexts.length > 0 ? { environmentContexts } : {}),
2298 ...(replyTo ? { replyTo: replyTo as DeepMutable<ResponseContextRecord> } : {}),
2299 ...(hasModelData
2300 ? {
2301 modelSelectionByProvider: compactModelSelectionByProvider(modelSelectionByProvider),
2302 activeProvider,
2303 ...(modelSelectionExplicit ? { modelSelectionExplicit: true } : {}),
2304 }
2305 : {}),
2306 ...(runtimeMode ? { runtimeMode } : {}),
2307 ...(interactionMode ? { interactionMode } : {}),
2308 };
2309 }
2310
2311 return nextDraftsByThreadKey;
2312 }
2313
2314 function persistedComposerDraftHasUserContent(draft: PersistedComposerThreadDraftState): boolean {
2315 return (
2316 draft.prompt.trim().length > 0 ||
2317 draft.attachments.length > 0 ||
2318 (draft.files?.length ?? 0) > 0 ||
2319 (draft.terminalContexts?.length ?? 0) > 0 ||
2320 (draft.previewAnnotations?.length ?? 0) > 0 ||
2321 (draft.reviewComments?.length ?? 0) > 0 ||
2322 (draft.threadContexts?.length ?? 0) > 0 ||
2323 (draft.environmentContexts?.length ?? 0) > 0 ||
2324 draft.replyTo !== undefined
2325 );
2326 }
2327
2328 function stripLegacyModelSeedsFromEmptyDraftSessions(
2329 draftsByThreadKey: PersistedComposerDraftStoreState["draftsByThreadKey"],
2330 draftThreadsByThreadKey: PersistedComposerDraftStoreState["draftThreadsByThreadKey"],
2331 ): PersistedComposerDraftStoreState["draftsByThreadKey"] {
2332 return Object.fromEntries(
2333 Object.entries(draftsByThreadKey).flatMap(([threadKey, draft]) => {
2334 if (
2335 draftThreadsByThreadKey[threadKey] === undefined ||
2336 draft.modelSelectionExplicit === true ||
2337 persistedComposerDraftHasUserContent(draft)
2338 ) {
2339 return [[threadKey, draft]];
2340 }
2341
2342 const {
2343 activeProvider: _activeProvider,
2344 modelSelectionByProvider: _modelSelectionByProvider,
2345 modelSelectionExplicit: _modelSelectionExplicit,
2346 ...retained
2347 } = draft;
2348 return retained.runtimeMode || retained.interactionMode ? [[threadKey, retained]] : [];
2349 }),
2350 );
2351 }
2352
2353 function migratePersistedComposerDraftStoreState(
2354 persistedState: unknown,
2355 ): PersistedComposerDraftStoreState {
2356 const normalized = normalizeCurrentPersistedComposerDraftStoreState(persistedState);
2357 return {
2358 ...normalized,
2359 draftsByThreadKey: stripLegacyModelSeedsFromEmptyDraftSessions(
2360 normalized.draftsByThreadKey,
2361 normalized.draftThreadsByThreadKey,
2362 ),
2363 };
2364 }
2365
2366 export function partializeComposerDraftStoreState(
2367 state: ComposerDraftStoreState,
2368 ): PersistedComposerDraftStoreState {
2369 const mappedDraftKeys = new Set(
2370 Object.values(state.logicalProjectDraftThreadKeyByLogicalProjectKey),
2371 );
2372 const keptSessionKeys = new Set(
2373 Object.entries(state.draftThreadsByThreadKey)
2374 .filter(
2375 ([threadKey, draftThread]) =>
2376 mappedDraftKeys.has(threadKey) ||
2377 isDraftThreadPromoting(draftThread) ||
2378 composerDraftHasUserContent(state.draftsByThreadKey[threadKey]) ||
2379 draftThreadHasOpenPreview(draftThread),
2380 )
2381 .map(([threadKey]) => threadKey),
2382 );
2383 const persistedDraftsByThreadKey: DeepMutable<
2384 PersistedComposerDraftStoreState["draftsByThreadKey"]
2385 > = {};
2386 for (const [threadKey, draft] of Object.entries(state.draftsByThreadKey)) {
2387 if (typeof threadKey !== "string" || threadKey.length === 0) {
2388 continue;
2389 }
2390 if (state.draftThreadsByThreadKey[threadKey] !== undefined && !keptSessionKeys.has(threadKey)) {
2391 continue;
2392 }
2393 const hasModelData =
2394 Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
2395 if (
2396 draft.prompt.length === 0 &&
2397 draft.persistedAttachments.length === 0 &&
2398 draft.files.length === 0 &&
2399 draft.terminalContexts.length === 0 &&
2400 draft.previewAnnotations.length === 0 &&
2401 draft.reviewComments.length === 0 &&
2402 draft.threadContexts.length === 0 &&
2403 draft.environmentContexts.length === 0 &&
2404 draft.replyTo === null &&
2405 !hasModelData &&
2406 draft.runtimeMode === null &&
2407 draft.interactionMode === null
2408 ) {
2409 continue;
2410 }
2411 const persistedDraft: DeepMutable<PersistedComposerThreadDraftState> = {
2412 prompt: draft.prompt,
2413 attachments: draft.persistedAttachments,
2414 ...(draft.files.length > 0
2415 ? {
2416 files: draft.files.map((file) => ({
2417 id: file.id,
2418 name: file.name,
2419 mimeType: file.mimeType,
2420 sizeBytes: file.sizeBytes,
2421 ...(file.source ? { source: file.source } : {}),
2422 ...(file.uploadedAttachmentId && file.uploadEnvironmentId
2423 ? {
2424 attachmentId: file.uploadedAttachmentId,
2425 environmentId: file.uploadEnvironmentId,
2426 }
2427 : {}),
2428 })),
2429 }
2430 : {}),
2431 ...(draft.terminalContexts.length > 0
2432 ? {
2433 terminalContexts: draft.terminalContexts.map((context) => ({
2434 id: context.id,
2435 threadId: context.threadId,
2436 createdAt: context.createdAt,
2437 terminalId: context.terminalId,
2438 terminalLabel: context.terminalLabel,
2439 lineStart: context.lineStart,
2440 lineEnd: context.lineEnd,
2441 text: context.text,
2442 })),
2443 }
2444 : {}),
2445 ...(draft.previewAnnotations.length > 0
2446 ? {
2447 previewAnnotations: draft.previewAnnotations.map(
2448 (annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
2449 ),
2450 }
2451 : {}),
2452 ...(draft.reviewComments.length > 0
2453 ? {
2454 reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
2455 }
2456 : {}),
2457 ...(draft.threadContexts.length > 0
2458 ? { threadContexts: draft.threadContexts.map((record) => ({ ...record })) }
2459 : {}),
2460 ...(draft.environmentContexts.length > 0
2461 ? { environmentContexts: draft.environmentContexts.map((record) => ({ ...record })) }
2462 : {}),
2463 ...(draft.replyTo
2464 ? { replyTo: { ...draft.replyTo } as DeepMutable<ResponseContextRecord> }
2465 : {}),
2466 ...(hasModelData
2467 ? {
2468 modelSelectionByProvider: compactModelSelectionByProvider(
2469 draft.modelSelectionByProvider,
2470 ),
2471 activeProvider: draft.activeProvider,
2472 ...(draft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}),
2473 }
2474 : {}),
2475 ...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
2476 ...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
2477 };
2478 persistedDraftsByThreadKey[threadKey] = persistedDraft;
2479 }
2480 const persistedDraftThreadsByThreadKey: DeepMutable<
2481 PersistedComposerDraftStoreState["draftThreadsByThreadKey"]
2482 > = {};
2483 for (const [threadKey, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
2484 if (!keptSessionKeys.has(threadKey)) {
2485 continue;
2486 }
2487 persistedDraftThreadsByThreadKey[threadKey] = draftThread;
2488 }
2489 return {
2490 draftsByThreadKey: persistedDraftsByThreadKey,
2491 draftThreadsByThreadKey: persistedDraftThreadsByThreadKey,
2492 logicalProjectDraftThreadKeyByLogicalProjectKey:
2493 state.logicalProjectDraftThreadKeyByLogicalProjectKey,
2494 stickyModelSelectionByProvider: compactModelSelectionByProvider(
2495 state.stickyModelSelectionByProvider,
2496 ),
2497 stickyOptionsByModelByProvider: compactStickyOptionsByModel(
2498 state.stickyOptionsByModelByProvider,
2499 ),
2500 stickyActiveProvider: state.stickyActiveProvider,
2501 };
2502 }
2503
2504 function normalizeCurrentPersistedComposerDraftStoreState(
2505 persistedState: unknown,
2506 ): PersistedComposerDraftStoreState {
2507 if (!persistedState || typeof persistedState !== "object") {
2508 return EMPTY_PERSISTED_DRAFT_STORE_STATE;
2509 }
2510 const normalizedPersistedState = persistedState as LegacyPersistedComposerDraftStoreState;
2511 const { draftThreadsByThreadKey, logicalProjectDraftThreadKeyByLogicalProjectKey } =
2512 normalizePersistedDraftThreads(
2513 normalizedPersistedState.draftThreadsByThreadKey ??
2514 normalizedPersistedState.draftThreadsByThreadId,
2515 normalizedPersistedState.logicalProjectDraftThreadKeyByLogicalProjectKey ??
2516 normalizedPersistedState.projectDraftThreadKeyByProjectKey ??
2517 normalizedPersistedState.projectDraftThreadIdByProjectKey ??
2518 normalizedPersistedState.projectDraftThreadIdByProjectId,
2519 );
2520
2521 let stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> = {};
2522 let stickyActiveProvider: ProviderInstanceId | null = null;
2523 if (
2524 normalizedPersistedState.stickyModelSelectionByProvider &&
2525 typeof normalizedPersistedState.stickyModelSelectionByProvider === "object"
2526 ) {
2527 stickyModelSelectionByProvider = normalizePersistedModelSelectionByProvider(
2528 normalizedPersistedState.stickyModelSelectionByProvider,
2529 );
2530 stickyActiveProvider = normalizeProviderInstanceId(
2531 normalizedPersistedState.stickyActiveProvider,
2532 );
2533 } else {
2534 const stickyModelOptions =
2535 normalizeProviderModelOptions(normalizedPersistedState.stickyModelOptions) ?? {};
2536 const normalizedStickyModelSelection = normalizeModelSelection(
2537 normalizedPersistedState.stickyModelSelection,
2538 {
2539 provider: normalizedPersistedState.stickyProvider ?? "codex",
2540 model: normalizedPersistedState.stickyModel,
2541 modelOptions: stickyModelOptions,
2542 },
2543 );
2544 const nextStickyModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
2545 normalizedStickyModelSelection,
2546 stickyModelOptions,
2547 );
2548 const stickyModelSelection = legacySyncModelSelectionOptions(
2549 normalizedStickyModelSelection,
2550 nextStickyModelOptions,
2551 );
2552 stickyModelSelectionByProvider = legacyToModelSelectionByProvider(
2553 stickyModelSelection,
2554 nextStickyModelOptions,
2555 );
2556 stickyActiveProvider = normalizeProviderInstanceId(normalizedPersistedState.stickyProvider);
2557 }
2558
2559 return {
2560 draftsByThreadKey: normalizePersistedDraftsByThreadId(
2561 normalizedPersistedState.draftsByThreadKey ?? normalizedPersistedState.draftsByThreadId,
2562 draftThreadsByThreadKey,
2563 ),
2564 draftThreadsByThreadKey,
2565 logicalProjectDraftThreadKeyByLogicalProjectKey,
2566 stickyModelSelectionByProvider: compactModelSelectionByProvider(stickyModelSelectionByProvider),
2567 stickyOptionsByModelByProvider:
2568 normalizedPersistedState.stickyOptionsByModelByProvider === undefined
2569 ? seedStickyOptionsByModel(stickyModelSelectionByProvider)
2570 : compactStickyOptionsByModel(normalizedPersistedState.stickyOptionsByModelByProvider),
2571 stickyActiveProvider,
2572 };
2573 }
2574
2575 function readPersistedAttachmentIdsFromStorage(threadKey: string): string[] {
2576 if (threadKey.length === 0) {
2577 return [];
2578 }
2579 try {
2580 const persisted = getLocalStorageItem(
2581 COMPOSER_DRAFT_STORAGE_KEY,
2582 PersistedComposerDraftStoreStorage,
2583 );
2584 if (!persisted || persisted.version !== COMPOSER_DRAFT_STORAGE_VERSION) {
2585 return [];
2586 }
2587 return (persisted.state.draftsByThreadKey[threadKey]?.attachments ?? []).map(
2588 (attachment) => attachment.id,
2589 );
2590 } catch {
2591 return [];
2592 }
2593 }
2594
2595 function verifyPersistedAttachments(
2596 threadKey: string,
2597 set: (
2598 partial:
2599 | ComposerDraftStoreState
2600 | Partial<ComposerDraftStoreState>
2601 | ((
2602 state: ComposerDraftStoreState,
2603 ) => ComposerDraftStoreState | Partial<ComposerDraftStoreState>),
2604 replace?: false,
2605 ) => void,
2606 ): void {
2607 let persistedIdSet = new Set<string>();
2608 try {
2609 composerDebouncedStorage.flush();
2610 persistedIdSet = new Set(readPersistedAttachmentIdsFromStorage(threadKey));
2611 } catch {
2612 persistedIdSet = new Set();
2613 }
2614 set((state) => {
2615 const current = state.draftsByThreadKey[threadKey];
2616 if (!current) {
2617 return state;
2618 }
2619 const imageIdSet = new Set(current.images.map((image) => image.id));
2620 const persistedAttachments = current.persistedAttachments.filter(
2621 (attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
2622 );
2623 const nonPersistedImageIds: string[] = [];
2624 for (const image of current.images) {
2625 if (!persistedIdSet.has(image.id)) {
2626 nonPersistedImageIds.push(image.id);
2627 }
2628 }
2629 const nextDraft: ComposerThreadDraftState = {
2630 ...current,
2631 persistedAttachments,
2632 nonPersistedImageIds,
2633 };
2634 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
2635 if (shouldRemoveDraft(nextDraft)) {
2636 delete nextDraftsByThreadKey[threadKey];
2637 } else {
2638 nextDraftsByThreadKey[threadKey] = nextDraft;
2639 }
2640 return { draftsByThreadKey: nextDraftsByThreadKey };
2641 });
2642 }
2643
2644 function hydratePersistedComposerImageAttachment(
2645 attachment: PersistedComposerImageAttachment,
2646 ): File | null {
2647 const commaIndex = attachment.dataUrl.indexOf(",");
2648 const header = commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);
2649 const payload = commaIndex === -1 ? "" : attachment.dataUrl.slice(commaIndex + 1);
2650 if (payload.length === 0) {
2651 return null;
2652 }
2653 try {
2654 const isBase64 = header.includes(";base64");
2655 if (!isBase64) {
2656 const decodedText = decodeURIComponent(payload);
2657 const inferredMimeType =
2658 header.startsWith("data:") && header.includes(";")
2659 ? header.slice("data:".length, header.indexOf(";"))
2660 : attachment.mimeType;
2661 const textBytes = new TextEncoder().encode(decodedText);
2662 const textFile = new File([textBytes], attachment.name, {
2663 type: inferredMimeType || attachment.mimeType,
2664 });
2665 rememberComposerImageBytes(textFile, textBytes);
2666 return textFile;
2667 }
2668 const binary = atob(payload);
2669 const bytes = new Uint8Array(binary.length);
2670 for (let index = 0; index < binary.length; index += 1) {
2671 bytes[index] = binary.charCodeAt(index);
2672 }
2673 const file = new File([bytes], attachment.name, { type: attachment.mimeType });
2674 rememberComposerImageBytes(file, bytes);
2675 return file;
2676 } catch {
2677 return null;
2678 }
2679 }
2680
2681 export function hydrateImagesFromPersisted(
2682 attachments: ReadonlyArray<PersistedComposerImageAttachment>,
2683 ): ComposerImageAttachment[] {
2684 return attachments.flatMap((attachment) => {
2685 const file = hydratePersistedComposerImageAttachment(attachment);
2686 if (!file) return [];
2687
2688 return [
2689 {
2690 type: "image" as const,
2691 id: attachment.id,
2692 name: attachment.name,
2693 mimeType: attachment.mimeType,
2694 sizeBytes: attachment.sizeBytes,
2695 previewUrl: attachment.dataUrl,
2696 file,
2697 ...(attachment.source ? { source: attachment.source } : {}),
2698 } satisfies ComposerImageAttachment,
2699 ];
2700 });
2701 }
2702
2703 function toHydratedThreadDraft(
2704 persistedDraft: PersistedComposerThreadDraftState,
2705 ): ComposerThreadDraftState {
2706 const modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> =
2707 persistedDraft.modelSelectionByProvider ?? {};
2708 const activeProvider = normalizeProviderInstanceId(persistedDraft.activeProvider) ?? null;
2709 const files: ComposerFileAttachment[] =
2710 persistedDraft.files?.map((file) => ({
2711 type: "file" as const,
2712 id: file.id,
2713 name: file.name,
2714 mimeType: file.mimeType,
2715 sizeBytes: file.sizeBytes,
2716 file: null,
2717 ...(file.source ? { source: file.source } : {}),
2718 ...(file.attachmentId !== undefined && file.environmentId !== undefined
2719 ? { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: file.environmentId }
2720 : {}),
2721 })) ?? [];
2722
2723 return {
2724 prompt: ensureInlineContextReferences(persistedDraft.prompt, [
2725 ...(persistedDraft.reviewComments ?? []).map(reviewCommentContextReference),
2726 ...(persistedDraft.previewAnnotations ?? []).map(previewAnnotationContextReference),
2727 ...(persistedDraft.threadContexts ?? []).map(threadContextReference),
2728 ...(persistedDraft.environmentContexts ?? []).map(environmentContextReference),
2729 ...files.map(fileContextReference),
2730 ]),
2731 images: hydrateImagesFromPersisted(persistedDraft.attachments),
2732 files,
2733 nonPersistedImageIds: [],
2734 persistedAttachments: [...persistedDraft.attachments],
2735 terminalContexts:
2736 persistedDraft.terminalContexts?.map((context) => ({
2737 ...context,
2738 text: context.text ?? "",
2739 })) ?? [],
2740 previewAnnotations:
2741 persistedDraft.previewAnnotations?.map((annotation) => ({ ...annotation })) ?? [],
2742 reviewComments: persistedDraft.reviewComments?.map((comment) => ({ ...comment })) ?? [],
2743 threadContexts: persistedDraft.threadContexts?.map((record) => ({ ...record })) ?? [],
2744 environmentContexts: persistedDraft.environmentContexts?.map((record) => ({ ...record })) ?? [],
2745 replyTo: persistedDraft.replyTo ?? null,
2746 modelSelectionByProvider,
2747 activeProvider,
2748 ...(persistedDraft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}),
2749 runtimeMode: persistedDraft.runtimeMode ?? null,
2750 interactionMode: persistedDraft.interactionMode ?? null,
2751 };
2752 }
2753
2754 function toHydratedDraftThreadState(
2755 persistedDraftThread: PersistedDraftThreadState,
2756 ): DraftThreadState {
2757 return {
2758 threadId: persistedDraftThread.threadId,
2759 environmentId: persistedDraftThread.environmentId as EnvironmentId,
2760 projectId: persistedDraftThread.projectId,
2761 logicalProjectKey:
2762 persistedDraftThread.logicalProjectKey ??
2763 projectDraftKey(
2764 scopeProjectRef(
2765 persistedDraftThread.environmentId as EnvironmentId,
2766 persistedDraftThread.projectId,
2767 ),
2768 ),
2769 createdAt: persistedDraftThread.createdAt,
2770 runtimeMode: persistedDraftThread.runtimeMode,
2771 interactionMode: persistedDraftThread.interactionMode,
2772 branch: persistedDraftThread.branch,
2773 worktreePath: persistedDraftThread.worktreePath,
2774 envMode: persistedDraftThread.envMode,
2775 startFromOrigin: persistedDraftThread.startFromOrigin,
2776 ...(persistedDraftThread.environmentSelection
2777 ? { environmentSelection: persistedDraftThread.environmentSelection }
2778 : {}),
2779 ...(persistedDraftThread.loadBalancedEnvironmentId !== undefined
2780 ? {
2781 loadBalancedEnvironmentId:
2782 persistedDraftThread.loadBalancedEnvironmentId as EnvironmentId | null,
2783 }
2784 : {}),
2785 ...(persistedDraftThread.checkoutPullRequest
2786 ? { checkoutPullRequest: persistedDraftThread.checkoutPullRequest }
2787 : {}),
2788 promotedTo: persistedDraftThread.promotedTo
2789 ? scopeThreadRef(
2790 persistedDraftThread.promotedTo.environmentId as EnvironmentId,
2791 persistedDraftThread.promotedTo.threadId as ThreadId,
2792 )
2793 : null,
2794 };
2795 }
2796
2797 const composerDraftStore = create<ComposerDraftStoreState>()(
2798 persist(
2799 (setBase, get) => {
2800 const set = setBase;
2801
2802 return {
2803 draftsByThreadKey: {},
2804 draftThreadsByThreadKey: {},
2805 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
2806 backgroundSubmissionThreadKeys: {},
2807 promotedDraftRedirects: {},
2808 rewindingThreadKeys: new Set<string>(),
2809 stickyModelSelectionByProvider: {},
2810 stickyOptionsByModelByProvider: {},
2811 stickyActiveProvider: null,
2812 getComposerDraft: (target) => getComposerDraftState(get(), target),
2813 getDraftSessionByLogicalProjectKey: (logicalProjectKey) => {
2814 const normalizedLogicalProjectKey = logicalProjectDraftKey(logicalProjectKey);
2815 if (normalizedLogicalProjectKey.length === 0) {
2816 return null;
2817 }
2818 const draftId =
2819 get().logicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey];
2820 if (!draftId) {
2821 return null;
2822 }
2823 const draftThread = get().draftThreadsByThreadKey[draftId];
2824 if (!draftThread || isDraftThreadPromoting(draftThread)) {
2825 return null;
2826 }
2827 return toProjectDraftSession(DraftId.make(draftId), draftThread);
2828 },
2829 getDraftThreadByProjectRef: (projectRef) => {
2830 return get().getDraftSessionByProjectRef(projectRef);
2831 },
2832 getDraftSessionByProjectRef: (projectRef) => {
2833 const state = get();
2834 for (const draftId of Object.values(
2835 state.logicalProjectDraftThreadKeyByLogicalProjectKey,
2836 )) {
2837 const draftThread = state.draftThreadsByThreadKey[draftId];
2838 if (!draftThread || isDraftThreadPromoting(draftThread)) {
2839 continue;
2840 }
2841 if (
2842 draftThread.projectId === projectRef.projectId &&
2843 draftThread.environmentId === projectRef.environmentId
2844 ) {
2845 return toProjectDraftSession(DraftId.make(draftId), draftThread);
2846 }
2847 }
2848 for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
2849 if (isDraftThreadPromoting(draftThread)) {
2850 continue;
2851 }
2852 if (
2853 draftThread.projectId === projectRef.projectId &&
2854 draftThread.environmentId === projectRef.environmentId
2855 ) {
2856 return toProjectDraftSession(DraftId.make(draftId), draftThread);
2857 }
2858 }
2859 return null;
2860 },
2861 getDraftSession: (draftId) => get().draftThreadsByThreadKey[draftId] ?? null,
2862 getDraftSessionByRef: (threadRef) => {
2863 for (const draftSession of Object.values(get().draftThreadsByThreadKey)) {
2864 if (
2865 draftSession.environmentId === threadRef.environmentId &&
2866 draftSession.threadId === threadRef.threadId
2867 ) {
2868 return draftSession;
2869 }
2870 }
2871 return null;
2872 },
2873 getDraftIdByRef: (threadRef) => {
2874 for (const [draftId, draftSession] of Object.entries(get().draftThreadsByThreadKey)) {
2875 if (
2876 draftSession.environmentId === threadRef.environmentId &&
2877 draftSession.threadId === threadRef.threadId
2878 ) {
2879 return DraftId.make(draftId);
2880 }
2881 }
2882 return null;
2883 },
2884 getPromotedDraftRedirect: (draftId) => get().promotedDraftRedirects[draftId] ?? null,
2885 getDraftThread: (threadRef) => {
2886 if (typeof threadRef === "string") {
2887 return get().getDraftSession(DraftId.make(threadRef));
2888 }
2889 return get().getDraftSessionByRef(threadRef);
2890 },
2891 getDraftThreadByRef: (threadRef) => {
2892 return get().getDraftSessionByRef(threadRef);
2893 },
2894 listDraftThreadKeys: () =>
2895 Object.values(get().draftThreadsByThreadKey).map((draftThread) =>
2896 scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
2897 ),
2898 hasDraftThreadsInEnvironment: (environmentId) =>
2899 Object.values(get().draftThreadsByThreadKey).some(
2900 (draftThread) => draftThread.environmentId === environmentId,
2901 ),
2902 setLogicalProjectDraftThreadId: (logicalProjectKey, projectRef, draftId, options) => {
2903 const normalizedLogicalProjectKey = logicalProjectDraftKey(logicalProjectKey);
2904 if (normalizedLogicalProjectKey.length === 0 || draftId.length === 0) {
2905 return;
2906 }
2907 set((state) => {
2908 const existingThread = state.draftThreadsByThreadKey[draftId];
2909 const previousThreadKeyForLogicalProject =
2910 state.logicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey];
2911 const nextDraftThread = createDraftThreadState(
2912 projectRef,
2913 options?.threadId ?? existingThread?.threadId ?? ThreadId.make(draftId),
2914 normalizedLogicalProjectKey,
2915 existingThread,
2916 options,
2917 );
2918 const hasSameLogicalMapping = previousThreadKeyForLogicalProject === draftId;
2919 const hasNoStaleMappingsForDraft = Object.entries(
2920 state.logicalProjectDraftThreadKeyByLogicalProjectKey,
2921 ).every(
2922 ([logicalKey, mappedDraftId]) =>
2923 mappedDraftId !== draftId || logicalKey === normalizedLogicalProjectKey,
2924 );
2925 if (
2926 hasSameLogicalMapping &&
2927 hasNoStaleMappingsForDraft &&
2928 draftThreadsEqual(existingThread, nextDraftThread)
2929 ) {
2930 return state;
2931 }
2932 const nextLogicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string> =
2933 Object.fromEntries(
2934 Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(
2935 ([logicalKey, mappedDraftId]) =>
2936 mappedDraftId !== draftId || logicalKey === normalizedLogicalProjectKey,
2937 ),
2938 );
2939 nextLogicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey] =
2940 draftId;
2941 const nextDraftThreadsByThreadKey: Record<string, DraftThreadState> = {
2942 ...state.draftThreadsByThreadKey,
2943 [draftId]: nextDraftThread,
2944 };
2945 const existingDraft = state.draftsByThreadKey[draftId];
2946 let nextDraftsByThreadKey = state.draftsByThreadKey;
2947 if (
2948 existingThread &&
2949 existingThread.environmentId !== projectRef.environmentId &&
2950 existingDraft !== undefined
2951 ) {
2952 const nextDraft = clearStaleFileUploadMetadata(
2953 existingDraft,
2954 projectRef.environmentId,
2955 );
2956 if (nextDraft !== existingDraft) {
2957 nextDraftsByThreadKey = {
2958 ...state.draftsByThreadKey,
2959 [draftId]: nextDraft,
2960 };
2961 }
2962 }
2963 const previousDraftThread =
2964 previousThreadKeyForLogicalProject === undefined
2965 ? undefined
2966 : nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
2967 // Keep populated drafts unmapped: sidebar rows still expose them when a new draft is opened.
2968 if (
2969 previousThreadKeyForLogicalProject &&
2970 previousThreadKeyForLogicalProject !== draftId &&
2971 !isComposerThreadKeyInUse(
2972 nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
2973 previousThreadKeyForLogicalProject,
2974 ) &&
2975 !isDraftThreadPromoting(previousDraftThread) &&
2976 !composerDraftHasUserContent(
2977 state.draftsByThreadKey[previousThreadKeyForLogicalProject],
2978 ) &&
2979 !draftThreadHasOpenPreview(previousDraftThread)
2980 ) {
2981 delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
2982 if (state.draftsByThreadKey[previousThreadKeyForLogicalProject] !== undefined) {
2983 nextDraftsByThreadKey = { ...nextDraftsByThreadKey };
2984 delete nextDraftsByThreadKey[previousThreadKeyForLogicalProject];
2985 }
2986 }
2987 return {
2988 draftsByThreadKey: nextDraftsByThreadKey,
2989 draftThreadsByThreadKey: nextDraftThreadsByThreadKey,
2990 logicalProjectDraftThreadKeyByLogicalProjectKey:
2991 nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
2992 };
2993 });
2994 },
2995 setProjectDraftThreadId: (projectRef, draftId, options) => {
2996 get().setLogicalProjectDraftThreadId(
2997 projectDraftKey(projectRef),
2998 projectRef,
2999 draftId,
3000 options,
3001 );
3002 },
3003 setDraftThreadContext: (threadRef, options) => {
3004 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3005 if (threadKey.length === 0) {
3006 return;
3007 }
3008 set((state) => {
3009 const existing = state.draftThreadsByThreadKey[threadKey];
3010 if (!existing) {
3011 return state;
3012 }
3013 const nextProjectRef = options.projectRef ?? {
3014 environmentId: existing.environmentId,
3015 projectId: existing.projectId,
3016 };
3017 if (
3018 nextProjectRef.projectId.length === 0 ||
3019 nextProjectRef.environmentId.length === 0
3020 ) {
3021 return state;
3022 }
3023 const projectChanged =
3024 nextProjectRef.environmentId !== existing.environmentId ||
3025 nextProjectRef.projectId !== existing.projectId;
3026 const nextWorktreePath =
3027 options.worktreePath === undefined
3028 ? projectChanged
3029 ? null
3030 : existing.worktreePath
3031 : (options.worktreePath ?? null);
3032 const nextBranch =
3033 options.branch === undefined
3034 ? projectChanged
3035 ? null
3036 : existing.branch
3037 : (options.branch ?? null);
3038 const nextStartFromOrigin =
3039 options.startFromOrigin === undefined
3040 ? existing.startFromOrigin
3041 : options.startFromOrigin;
3042 const environmentSelection =
3043 options.environmentSelection ??
3044 (options.branch != null || options.worktreePath != null
3045 ? "manual"
3046 : existing.environmentSelection);
3047 const checkoutPullRequest = resolveCheckoutPullRequest(
3048 existing,
3049 options.checkoutPullRequest,
3050 projectChanged,
3051 );
3052 const nextDraftThread: DraftThreadState = {
3053 threadId: existing.threadId,
3054 environmentId: nextProjectRef.environmentId,
3055 projectId: nextProjectRef.projectId,
3056 logicalProjectKey: existing.logicalProjectKey,
3057 ...(environmentSelection ? { environmentSelection } : {}),
3058 loadBalancedEnvironmentId:
3059 options.loadBalancedEnvironmentId === undefined
3060 ? projectChanged
3061 ? null
3062 : (existing.loadBalancedEnvironmentId ?? null)
3063 : options.loadBalancedEnvironmentId,
3064 createdAt:
3065 options.createdAt === undefined
3066 ? existing.createdAt
3067 : options.createdAt || existing.createdAt,
3068 runtimeMode: options.runtimeMode ?? existing.runtimeMode,
3069 interactionMode: options.interactionMode ?? existing.interactionMode,
3070 branch: nextBranch,
3071 worktreePath: nextWorktreePath,
3072 envMode:
3073 options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
3074 startFromOrigin: nextStartFromOrigin,
3075 ...(checkoutPullRequest ? { checkoutPullRequest } : {}),
3076 promotedTo: existing.promotedTo ?? null,
3077 };
3078 const isUnchanged =
3079 nextDraftThread.environmentId === existing.environmentId &&
3080 nextDraftThread.projectId === existing.projectId &&
3081 nextDraftThread.logicalProjectKey === existing.logicalProjectKey &&
3082 nextDraftThread.environmentSelection === existing.environmentSelection &&
3083 nextDraftThread.loadBalancedEnvironmentId === existing.loadBalancedEnvironmentId &&
3084 nextDraftThread.createdAt === existing.createdAt &&
3085 nextDraftThread.runtimeMode === existing.runtimeMode &&
3086 nextDraftThread.interactionMode === existing.interactionMode &&
3087 nextDraftThread.branch === existing.branch &&
3088 nextDraftThread.worktreePath === existing.worktreePath &&
3089 nextDraftThread.envMode === existing.envMode &&
3090 nextDraftThread.startFromOrigin === existing.startFromOrigin &&
3091 checkoutPullRequestsEqual(
3092 nextDraftThread.checkoutPullRequest,
3093 existing.checkoutPullRequest,
3094 ) &&
3095 scopedThreadRefsEqual(nextDraftThread.promotedTo, existing.promotedTo);
3096 if (isUnchanged) {
3097 return state;
3098 }
3099 return {
3100 draftThreadsByThreadKey: {
3101 ...state.draftThreadsByThreadKey,
3102 [threadKey]: nextDraftThread,
3103 },
3104 };
3105 });
3106 },
3107 clearProjectDraftThreadId: (projectRef) => {
3108 set((state) => {
3109 const matchingThreadKeys = Object.entries(state.draftThreadsByThreadKey)
3110 .filter(
3111 ([, draftThread]) =>
3112 draftThread.projectId === projectRef.projectId &&
3113 draftThread.environmentId === projectRef.environmentId,
3114 )
3115 .map(([threadKey]) => threadKey);
3116 if (matchingThreadKeys.length === 0) {
3117 return state;
3118 }
3119 let nextState = {
3120 draftsByThreadKey: state.draftsByThreadKey,
3121 draftThreadsByThreadKey: state.draftThreadsByThreadKey,
3122 logicalProjectDraftThreadKeyByLogicalProjectKey:
3123 state.logicalProjectDraftThreadKeyByLogicalProjectKey,
3124 };
3125 for (const threadKey of matchingThreadKeys) {
3126 nextState = removeDraftThreadReferences(nextState, threadKey);
3127 }
3128 return nextState;
3129 });
3130 },
3131 clearProjectDraftThreadById: (projectRef, threadRef) => {
3132 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3133 if (threadKey.length === 0) {
3134 return;
3135 }
3136 set((state) => {
3137 const draftThread = state.draftThreadsByThreadKey[threadKey];
3138 if (
3139 !draftThread ||
3140 draftThread.projectId !== projectRef.projectId ||
3141 draftThread.environmentId !== projectRef.environmentId
3142 ) {
3143 return state;
3144 }
3145 return removeDraftThreadReferences(state, threadKey);
3146 });
3147 },
3148 markDraftThreadPromoting: (threadRef, promotedTo) => {
3149 const threadKey = resolveComposerDraftKey(get(), threadRef);
3150 if (!threadKey) {
3151 return;
3152 }
3153 set((state) => {
3154 const existing = state.draftThreadsByThreadKey[threadKey];
3155 if (!existing) {
3156 return state;
3157 }
3158 const nextPromotedTo =
3159 promotedTo ?? scopeThreadRef(existing.environmentId, existing.threadId);
3160 if (scopedThreadRefsEqual(existing.promotedTo, nextPromotedTo)) {
3161 return state;
3162 }
3163 return {
3164 draftThreadsByThreadKey: {
3165 ...state.draftThreadsByThreadKey,
3166 [threadKey]: {
3167 ...existing,
3168 promotedTo: nextPromotedTo,
3169 },
3170 },
3171 };
3172 });
3173 },
3174 finalizePromotedDraftThread: (threadRef) => {
3175 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3176 if (threadKey.length === 0) {
3177 return;
3178 }
3179 set((state) => {
3180 const existing = state.draftThreadsByThreadKey[threadKey];
3181 if (!existing?.promotedTo) {
3182 return state;
3183 }
3184 return {
3185 ...removeDraftThreadReferences(state, threadKey, existing.promotedTo),
3186 promotedDraftRedirects: {
3187 ...state.promotedDraftRedirects,
3188 [threadKey]: existing.promotedTo,
3189 },
3190 };
3191 });
3192 },
3193 clearDraftThread: (threadRef) => {
3194 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3195 if (threadKey.length === 0) {
3196 return;
3197 }
3198 set((state) => {
3199 const hasDraftThread = state.draftThreadsByThreadKey[threadKey] !== undefined;
3200 const hasLogicalProjectMapping = Object.values(
3201 state.logicalProjectDraftThreadKeyByLogicalProjectKey,
3202 ).includes(threadKey);
3203 const hasComposerDraft = state.draftsByThreadKey[threadKey] !== undefined;
3204 if (!hasDraftThread && !hasLogicalProjectMapping && !hasComposerDraft) {
3205 return state;
3206 }
3207 return removeDraftThreadReferences(state, threadKey);
3208 });
3209 },
3210 setStickyModelSelection: (modelSelection) => {
3211 const normalized = normalizeModelSelection(modelSelection);
3212 set((state) => {
3213 if (!normalized) {
3214 return state;
3215 }
3216 const current = state.stickyModelSelectionByProvider[normalized.instanceId];
3217 // Model-only updates omit options; preserve sticky traits across model switches and new chats.
3218 const nextSelection =
3219 normalized.options !== undefined
3220 ? normalized
3221 : createModelSelection(normalized.instanceId, normalized.model, current?.options);
3222 const nextMap: Partial<Record<ProviderInstanceId, ModelSelection>> = {
3223 ...state.stickyModelSelectionByProvider,
3224 [normalized.instanceId]: nextSelection,
3225 };
3226 if (Equal.equals(state.stickyModelSelectionByProvider, nextMap)) {
3227 return state.stickyActiveProvider === normalized.instanceId
3228 ? state
3229 : { stickyActiveProvider: normalized.instanceId };
3230 }
3231 return {
3232 stickyModelSelectionByProvider: nextMap,
3233 stickyActiveProvider: normalized.instanceId,
3234 };
3235 });
3236 },
3237 applyStickyState: (threadRef) => {
3238 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3239 if (threadKey.length === 0) {
3240 return;
3241 }
3242 set((state) => {
3243 const stickyMap = state.stickyModelSelectionByProvider;
3244 const stickyActiveProvider = state.stickyActiveProvider;
3245 const existing = state.draftsByThreadKey[threadKey];
3246 const base = existing ?? createEmptyThreadDraft();
3247 const nextMap = compactModelSelectionByProvider(stickyMap);
3248 if (
3249 Equal.equals(base.modelSelectionByProvider, nextMap) &&
3250 base.activeProvider === stickyActiveProvider &&
3251 base.modelSelectionExplicit === undefined
3252 ) {
3253 return state;
3254 }
3255 const { modelSelectionExplicit: _modelSelectionExplicit, ...retained } = base;
3256 const nextDraft: ComposerThreadDraftState = {
3257 ...retained,
3258 modelSelectionByProvider: nextMap,
3259 activeProvider: stickyActiveProvider,
3260 };
3261 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3262 if (shouldRemoveDraft(nextDraft)) {
3263 delete nextDraftsByThreadKey[threadKey];
3264 } else {
3265 nextDraftsByThreadKey[threadKey] = nextDraft;
3266 }
3267 return { draftsByThreadKey: nextDraftsByThreadKey };
3268 });
3269 },
3270 setPrompt: (threadRef, prompt) => {
3271 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3272 if (threadKey.length === 0) {
3273 return;
3274 }
3275 set((state) => {
3276 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
3277 const nextDraft: ComposerThreadDraftState = {
3278 ...existing,
3279 prompt,
3280 };
3281 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3282 if (shouldRemoveDraft(nextDraft)) {
3283 delete nextDraftsByThreadKey[threadKey];
3284 } else {
3285 nextDraftsByThreadKey[threadKey] = nextDraft;
3286 }
3287 return { draftsByThreadKey: nextDraftsByThreadKey };
3288 });
3289 },
3290 setTerminalContexts: (threadRef, contexts) => {
3291 const threadKey = resolveComposerDraftKey(get(), threadRef);
3292 const threadId = resolveComposerThreadId(get(), threadRef);
3293 if (!threadKey || !threadId) {
3294 return;
3295 }
3296 const normalizedContexts = normalizeTerminalContextsForThread(threadId, contexts);
3297 set((state) => {
3298 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
3299 const nextDraft: ComposerThreadDraftState = {
3300 ...existing,
3301 prompt: ensureInlineContextReferences(
3302 existing.terminalContexts
3303 .filter((context) => !normalizedContexts.some((next) => next.id === context.id))
3304 .reduce(
3305 (prompt, context) =>
3306 removeInlineContextReference(
3307 prompt,
3308 terminalContextReference(context).contextId,
3309 ).prompt,
3310 existing.prompt,
3311 ),
3312 normalizedContexts.map(terminalContextReference),
3313 ),
3314 terminalContexts: normalizedContexts,
3315 };
3316 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3317 if (shouldRemoveDraft(nextDraft)) {
3318 delete nextDraftsByThreadKey[threadKey];
3319 } else {
3320 nextDraftsByThreadKey[threadKey] = nextDraft;
3321 }
3322 return { draftsByThreadKey: nextDraftsByThreadKey };
3323 });
3324 },
3325 setModelSelection: (threadRef, modelSelection, opts) => {
3326 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3327 if (threadKey.length === 0) {
3328 return;
3329 }
3330 const normalized = normalizeModelSelection(modelSelection);
3331 set((state) => {
3332 const existing = state.draftsByThreadKey[threadKey];
3333 if (!existing && normalized === null) {
3334 return state;
3335 }
3336 const base = existing ?? createEmptyThreadDraft();
3337 const nextMap = { ...base.modelSelectionByProvider };
3338 if (normalized) {
3339 const current = nextMap[normalized.instanceId];
3340 if (normalized.options !== undefined || opts?.replaceOptions) {
3341 nextMap[normalized.instanceId] = normalized as ModelSelection;
3342 } else {
3343 nextMap[normalized.instanceId] = createModelSelection(
3344 normalized.instanceId,
3345 normalized.model,
3346 current?.options,
3347 );
3348 }
3349 }
3350 const nextActiveProvider = normalized?.instanceId ?? base.activeProvider;
3351 if (
3352 opts?.explicit !== true &&
3353 Equal.equals(base.modelSelectionByProvider, nextMap) &&
3354 base.activeProvider === nextActiveProvider &&
3355 !base.modelSelectionExplicit
3356 ) {
3357 return state;
3358 }
3359 const { modelSelectionExplicit: _previousExplicit, ...restBase } = base;
3360 const nextDraft: ComposerThreadDraftState = {
3361 ...restBase,
3362 modelSelectionByProvider: nextMap,
3363 activeProvider: nextActiveProvider,
3364 ...(opts?.explicit === true ? { modelSelectionExplicit: true as const } : {}),
3365 };
3366 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3367 if (shouldRemoveDraft(nextDraft)) {
3368 delete nextDraftsByThreadKey[threadKey];
3369 } else {
3370 nextDraftsByThreadKey[threadKey] = nextDraft;
3371 }
3372 return { draftsByThreadKey: nextDraftsByThreadKey };
3373 });
3374 },
3375 releaseModelSelection: (threadRef, modelSelection) => {
3376 const threadKey = scopedThreadKey(threadRef);
3377 set((state) => {
3378 const draft = state.draftsByThreadKey[threadKey];
3379 // A newer pick, even of the same model, is still waiting for its own reply.
3380 if (
3381 !draft?.activeProvider ||
3382 draft.modelSelectionByProvider[draft.activeProvider] !== modelSelection
3383 ) {
3384 return state;
3385 }
3386 const { modelSelectionExplicit: _explicit, ...retained } = draft;
3387 const next = { ...retained, activeProvider: null, modelSelectionByProvider: {} };
3388 const draftsByThreadKey = { ...state.draftsByThreadKey };
3389 if (shouldRemoveDraft(next)) delete draftsByThreadKey[threadKey];
3390 else draftsByThreadKey[threadKey] = next;
3391 return { draftsByThreadKey };
3392 });
3393 },
3394 setProviderModelOptions: (threadRef, provider, nextProviderOptions, options) => {
3395 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3396 if (threadKey.length === 0) {
3397 return;
3398 }
3399 const normalizedProvider = normalizeProviderDriverKind(provider);
3400 if (normalizedProvider === null) {
3401 return;
3402 }
3403 const instanceKey = options?.instanceId ?? defaultInstanceIdForDriver(normalizedProvider);
3404 const fallbackModel =
3405 normalizeCustomModelSlug(options?.model) ??
3406 DEFAULT_MODEL_BY_PROVIDER[normalizedProvider] ??
3407 DEFAULT_MODEL;
3408 const providerOpts =
3409 nextProviderOptions && nextProviderOptions.length > 0 ? nextProviderOptions : undefined;
3410
3411 set((state) => {
3412 const existing = state.draftsByThreadKey[threadKey];
3413 const base = existing ?? createEmptyThreadDraft();
3414
3415 const nextMap = { ...base.modelSelectionByProvider };
3416 // Traits apply to the model the composer shows, which on a started
3417 // thread is the thread's model rather than a stored seed.
3418 nextMap[instanceKey] = createModelSelection(
3419 instanceKey,
3420 normalizeCustomModelSlug(options?.model) ??
3421 nextMap[instanceKey]?.model ??
3422 fallbackModel,
3423 providerOpts,
3424 );
3425
3426 let nextStickyMap = state.stickyModelSelectionByProvider;
3427 let nextOptionsByModel = state.stickyOptionsByModelByProvider;
3428 let nextStickyActiveProvider = state.stickyActiveProvider;
3429 if (options?.persistSticky === true) {
3430 nextStickyMap = { ...state.stickyModelSelectionByProvider };
3431 const stickyBase =
3432 nextStickyMap[instanceKey] ??
3433 base.modelSelectionByProvider[instanceKey] ??
3434 createModelSelection(instanceKey, fallbackModel);
3435 const rememberedModel = normalizeCustomModelSlug(options?.model) ?? stickyBase.model;
3436 // Traits for another shown model belong in per-model memory only;
3437 // the sticky selection keeps its own model's traits.
3438 const appliesToSticky = rememberedModel === stickyBase.model;
3439 if (providerOpts) {
3440 if (appliesToSticky) {
3441 nextStickyMap[instanceKey] = createModelSelection(
3442 instanceKey,
3443 stickyBase.model,
3444 providerOpts,
3445 );
3446 }
3447 nextOptionsByModel = {
3448 ...state.stickyOptionsByModelByProvider,
3449 [instanceKey]: {
3450 ...state.stickyOptionsByModelByProvider[instanceKey],
3451 [rememberedModel]: providerOpts,
3452 },
3453 };
3454 } else {
3455 if (appliesToSticky && (stickyBase.options?.length ?? 0) > 0) {
3456 const { options: _, ...rest } = stickyBase;
3457 nextStickyMap[instanceKey] = rest as ModelSelection;
3458 }
3459 const rememberedByModel = {
3460 ...state.stickyOptionsByModelByProvider[instanceKey],
3461 };
3462 delete rememberedByModel[rememberedModel];
3463 nextOptionsByModel = {
3464 ...state.stickyOptionsByModelByProvider,
3465 [instanceKey]: rememberedByModel,
3466 };
3467 }
3468 nextStickyActiveProvider = options.instanceId
3469 ? instanceKey
3470 : (base.activeProvider ?? instanceKey);
3471 }
3472
3473 const { modelSelectionExplicit: _previousExplicit, ...restBase } = base;
3474 const nextDraft: ComposerThreadDraftState = {
3475 ...restBase,
3476 ...(options?.instanceId ? { activeProvider: instanceKey } : {}),
3477 modelSelectionByProvider: nextMap,
3478 modelSelectionExplicit: true,
3479 };
3480 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3481 if (shouldRemoveDraft(nextDraft)) {
3482 delete nextDraftsByThreadKey[threadKey];
3483 } else {
3484 nextDraftsByThreadKey[threadKey] = nextDraft;
3485 }
3486
3487 return {
3488 draftsByThreadKey: nextDraftsByThreadKey,
3489 ...(options?.persistSticky === true
3490 ? {
3491 stickyModelSelectionByProvider: nextStickyMap,
3492 stickyOptionsByModelByProvider: nextOptionsByModel,
3493 stickyActiveProvider: nextStickyActiveProvider,
3494 }
3495 : {}),
3496 };
3497 });
3498 },
3499 setRuntimeMode: (threadRef, runtimeMode) => {
3500 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3501 if (threadKey.length === 0) {
3502 return;
3503 }
3504 const nextRuntimeMode = isRuntimeMode(runtimeMode) ? runtimeMode : null;
3505 set((state) => {
3506 const existing = state.draftsByThreadKey[threadKey];
3507 if (!existing && nextRuntimeMode === null) {
3508 return state;
3509 }
3510 const base = existing ?? createEmptyThreadDraft();
3511 if (base.runtimeMode === nextRuntimeMode) {
3512 return state;
3513 }
3514 const nextDraft: ComposerThreadDraftState = {
3515 ...base,
3516 runtimeMode: nextRuntimeMode,
3517 };
3518 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3519 if (shouldRemoveDraft(nextDraft)) {
3520 delete nextDraftsByThreadKey[threadKey];
3521 } else {
3522 nextDraftsByThreadKey[threadKey] = nextDraft;
3523 }
3524 return { draftsByThreadKey: nextDraftsByThreadKey };
3525 });
3526 },
3527 setInteractionMode: (threadRef, interactionMode) => {
3528 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3529 if (threadKey.length === 0) {
3530 return;
3531 }
3532 const nextInteractionMode =
3533 interactionMode === "plan" || interactionMode === "default" ? interactionMode : null;
3534 set((state) => {
3535 const existing = state.draftsByThreadKey[threadKey];
3536 if (!existing && nextInteractionMode === null) {
3537 return state;
3538 }
3539 const base = existing ?? createEmptyThreadDraft();
3540 if (base.interactionMode === nextInteractionMode) {
3541 return state;
3542 }
3543 const nextDraft: ComposerThreadDraftState = {
3544 ...base,
3545 interactionMode: nextInteractionMode,
3546 };
3547 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3548 if (shouldRemoveDraft(nextDraft)) {
3549 delete nextDraftsByThreadKey[threadKey];
3550 } else {
3551 nextDraftsByThreadKey[threadKey] = nextDraft;
3552 }
3553 return { draftsByThreadKey: nextDraftsByThreadKey };
3554 });
3555 },
3556 addImage: (threadRef, image) => {
3557 const threadKey = resolveComposerDraftKey(get(), threadRef);
3558 const threadId = resolveComposerThreadId(get(), threadRef);
3559 if (!threadKey || !threadId) {
3560 return false;
3561 }
3562 const acceptedIds = get().addImages(
3563 typeof threadRef === "string" ? DraftId.make(threadKey) : threadRef,
3564 [image],
3565 );
3566 return acceptedIds.includes(image.id);
3567 },
3568 addImages: (threadRef, images, options) => {
3569 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3570 if (threadKey.length === 0 || images.length === 0) {
3571 return [];
3572 }
3573 let acceptedIds: string[] = [];
3574 const capacityRejections: ComposerImageAttachment[] = [];
3575 set((state) => {
3576 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
3577 const existingIds = new Set(existing.images.map((image) => image.id));
3578 const existingDedupKeys = new Set(
3579 existing.images.map((image) => composerImageDedupKey(image)),
3580 );
3581 const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
3582 const dedupedIncoming: ComposerImageAttachment[] = [];
3583 for (const image of images) {
3584 const dedupKey = composerImageDedupKey(image);
3585 if (
3586 existingIds.has(image.id) ||
3587 (!options?.allowDuplicates && existingDedupKeys.has(dedupKey))
3588 ) {
3589 // Avoid revoking a blob URL that's still referenced by an accepted image.
3590 if (!acceptedPreviewUrls.has(image.previewUrl)) {
3591 revokeObjectPreviewUrl(image.previewUrl);
3592 }
3593 continue;
3594 }
3595 if (
3596 existing.images.length + existing.files.length + dedupedIncoming.length >=
3597 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
3598 ) {
3599 capacityRejections.push(image);
3600 if (!acceptedPreviewUrls.has(image.previewUrl)) {
3601 revokeObjectPreviewUrl(image.previewUrl);
3602 }
3603 continue;
3604 }
3605 dedupedIncoming.push(image);
3606 existingIds.add(image.id);
3607 existingDedupKeys.add(dedupKey);
3608 acceptedPreviewUrls.add(image.previewUrl);
3609 }
3610 if (dedupedIncoming.length === 0) {
3611 return state;
3612 }
3613 acceptedIds = dedupedIncoming.map((image) => image.id);
3614 return {
3615 draftsByThreadKey: {
3616 ...state.draftsByThreadKey,
3617 [threadKey]: {
3618 ...existing,
3619 images: [...existing.images, ...dedupedIncoming],
3620 },
3621 },
3622 };
3623 });
3624 capacityRejections.forEach((image) => options?.onCapacityExceeded?.(image));
3625 return acceptedIds;
3626 },
3627 removeImage: (threadRef, imageId) => {
3628 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3629 if (threadKey.length === 0) {
3630 return;
3631 }
3632 const existing = get().draftsByThreadKey[threadKey];
3633 if (!existing) {
3634 return;
3635 }
3636 const removedImage = existing.images.find((image) => image.id === imageId);
3637 if (removedImage) {
3638 revokeObjectPreviewUrl(removedImage.previewUrl);
3639 }
3640 set((state) => {
3641 const current = state.draftsByThreadKey[threadKey];
3642 if (!current) {
3643 return state;
3644 }
3645 const nextDraft: ComposerThreadDraftState = {
3646 ...current,
3647 prompt: removeInlineContextReference(
3648 current.prompt,
3649 toKindScopedComposerContextId("image", imageId),
3650 ).prompt,
3651 images: current.images.filter((image) => image.id !== imageId),
3652 nonPersistedImageIds: current.nonPersistedImageIds.filter((id) => id !== imageId),
3653 persistedAttachments: current.persistedAttachments.filter(
3654 (attachment) => attachment.id !== imageId,
3655 ),
3656 };
3657 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3658 if (shouldRemoveDraft(nextDraft)) {
3659 delete nextDraftsByThreadKey[threadKey];
3660 } else {
3661 nextDraftsByThreadKey[threadKey] = nextDraft;
3662 }
3663 return { draftsByThreadKey: nextDraftsByThreadKey };
3664 });
3665 },
3666 addFiles: (threadRef, files, options) => {
3667 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3668 if (threadKey.length === 0 || files.length === 0) {
3669 return [];
3670 }
3671 let acceptedIds: string[] = [];
3672 set((state) => {
3673 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
3674 const knownIds = new Set(existing.files.map((file) => file.id));
3675 const knownFiles = new Map<string, ComposerFileAttachment>(
3676 existing.files.map((file) => [composerFileDedupKey(file), file]),
3677 );
3678 const accepted: ComposerFileAttachment[] = [];
3679 const replacements = new Map<string, ComposerFileAttachment>();
3680 for (const file of files) {
3681 const key = composerFileDedupKey(file);
3682 if (knownIds.has(file.id)) {
3683 continue;
3684 }
3685 const duplicate = options?.allowDuplicates
3686 ? undefined
3687 : (knownFiles.get(key) ??
3688 existing.files.find(
3689 (candidate) =>
3690 composerFileNeedsReattach(candidate) &&
3691 !replacements.has(candidate.id) &&
3692 composerFileMatchesReattachMarker(candidate, file),
3693 ));
3694 if (duplicate) {
3695 if (composerFileNeedsReattach(duplicate) && !replacements.has(duplicate.id)) {
3696 replacements.set(duplicate.id, file);
3697 knownIds.add(file.id);
3698 knownFiles.set(key, file);
3699 }
3700 continue;
3701 }
3702 if (
3703 existing.images.length + existing.files.length + accepted.length >=
3704 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
3705 ) {
3706 break;
3707 }
3708 accepted.push(file);
3709 knownIds.add(file.id);
3710 knownFiles.set(key, file);
3711 }
3712 if (accepted.length === 0 && replacements.size === 0) {
3713 return state;
3714 }
3715 acceptedIds = accepted.map((file) => file.id);
3716 const retained = existing.files.map((file) => replacements.get(file.id) ?? file);
3717 const prompt =
3718 replacements.size === 0
3719 ? existing.prompt
3720 : replaceComposerContextReferences(existing.prompt, (occurrence) => {
3721 const original = existing.files.find(
3722 (file) => fileContextReference(file).contextId === occurrence.contextId,
3723 );
3724 const replacement = original ? replacements.get(original.id) : undefined;
3725 return replacement
3726 ? formatInlineContextReference(fileContextReference(replacement))
3727 : occurrence.source;
3728 });
3729 return {
3730 draftsByThreadKey: {
3731 ...state.draftsByThreadKey,
3732 [threadKey]: {
3733 ...existing,
3734 prompt: options?.appendReference
3735 ? ensureInlineContextReferences(
3736 prompt,
3737 [...accepted, ...replacements.values()].map(fileContextReference),
3738 )
3739 : prompt,
3740 files: [...retained, ...accepted],
3741 },
3742 },
3743 };
3744 });
3745 return acceptedIds;
3746 },
3747 removeFile: (threadRef, fileId) => {
3748 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3749 if (threadKey.length === 0) {
3750 return;
3751 }
3752 set((state) => {
3753 const current = state.draftsByThreadKey[threadKey];
3754 if (!current?.files.some((file) => file.id === fileId)) {
3755 return state;
3756 }
3757 const nextDraft = {
3758 ...current,
3759 prompt: removeInlineContextReference(
3760 current.prompt,
3761 toKindScopedComposerContextId("file", fileId),
3762 ).prompt,
3763 files: current.files.filter((file) => file.id !== fileId),
3764 } satisfies ComposerThreadDraftState;
3765 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3766 if (shouldRemoveDraft(nextDraft)) {
3767 delete nextDraftsByThreadKey[threadKey];
3768 } else {
3769 nextDraftsByThreadKey[threadKey] = nextDraft;
3770 }
3771 return { draftsByThreadKey: nextDraftsByThreadKey };
3772 });
3773 },
3774 setFileUpload: (threadRef, fileId, environmentId, attachmentId) => {
3775 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3776 if (threadKey.length === 0) {
3777 return;
3778 }
3779 set((state) => {
3780 const current = state.draftsByThreadKey[threadKey];
3781 const file = current?.files.find((entry) => entry.id === fileId);
3782 if (
3783 !current ||
3784 !file ||
3785 (file.uploadEnvironmentId === environmentId &&
3786 file.uploadedAttachmentId === attachmentId)
3787 ) {
3788 return state;
3789 }
3790 return {
3791 draftsByThreadKey: {
3792 ...state.draftsByThreadKey,
3793 [threadKey]: {
3794 ...current,
3795 files: current.files.map((entry) =>
3796 entry.id === fileId
3797 ? {
3798 ...entry,
3799 uploadedAttachmentId: attachmentId,
3800 uploadEnvironmentId: environmentId,
3801 }
3802 : entry,
3803 ),
3804 },
3805 },
3806 };
3807 });
3808 },
3809 markFileUploadMissing: (threadRef, fileId, environmentId, attachmentId) => {
3810 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3811 if (threadKey.length === 0) {
3812 return false;
3813 }
3814 let markedMissing = false;
3815 set((state) => {
3816 const current = state.draftsByThreadKey[threadKey];
3817 const file = current?.files.find((entry) => entry.id === fileId);
3818 if (
3819 !current ||
3820 !file ||
3821 file.file !== null ||
3822 file.uploadEnvironmentId !== environmentId ||
3823 file.uploadedAttachmentId !== attachmentId
3824 ) {
3825 return state;
3826 }
3827 markedMissing = true;
3828 return {
3829 draftsByThreadKey: {
3830 ...state.draftsByThreadKey,
3831 [threadKey]: {
3832 ...current,
3833 files: current.files.map((entry) => {
3834 if (entry.id !== fileId) {
3835 return entry;
3836 }
3837 const marker = { ...entry };
3838 delete marker.uploadedAttachmentId;
3839 delete marker.uploadEnvironmentId;
3840 return marker;
3841 }),
3842 },
3843 },
3844 };
3845 });
3846 return markedMissing;
3847 },
3848 insertTerminalContext: (threadRef, prompt, context, index) => {
3849 const threadKey = resolveComposerDraftKey(get(), threadRef);
3850 const threadId = resolveComposerThreadId(get(), threadRef);
3851 if (!threadKey || !threadId) {
3852 return false;
3853 }
3854 let inserted = false;
3855 set((state) => {
3856 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
3857 const normalizedContext = normalizeTerminalContextForThread(threadId, context);
3858 if (!normalizedContext) {
3859 return state;
3860 }
3861 const dedupKey = terminalContextDedupKey(normalizedContext);
3862 if (
3863 existing.terminalContexts.some((entry) => entry.id === normalizedContext.id) ||
3864 existing.terminalContexts.some((entry) => terminalContextDedupKey(entry) === dedupKey)
3865 ) {
3866 return state;
3867 }
3868 inserted = true;
3869 const boundedIndex = Math.max(0, Math.min(existing.terminalContexts.length, index));
3870 const nextDraft: ComposerThreadDraftState = {
3871 ...existing,
3872 prompt,
3873 terminalContexts: [
3874 ...existing.terminalContexts.slice(0, boundedIndex),
3875 normalizedContext,
3876 ...existing.terminalContexts.slice(boundedIndex),
3877 ],
3878 };
3879 return {
3880 draftsByThreadKey: {
3881 ...state.draftsByThreadKey,
3882 [threadKey]: nextDraft,
3883 },
3884 };
3885 });
3886 return inserted;
3887 },
3888 addTerminalContexts: (threadRef, contexts, options) => {
3889 const threadKey = resolveComposerDraftKey(get(), threadRef);
3890 const threadId = resolveComposerThreadId(get(), threadRef);
3891 if (!threadKey || !threadId || contexts.length === 0) {
3892 return;
3893 }
3894 const currentContexts = get().draftsByThreadKey[threadKey]?.terminalContexts ?? [];
3895 const incoming = normalizeTerminalContextsForThread(threadId, [
3896 ...currentContexts,
3897 ...contexts,
3898 ]).slice(currentContexts.length);
3899 if (incoming.length === 0) return;
3900 const placedAtCaret =
3901 options?.appendReference !== false &&
3902 options?.insertAtCaret !== false &&
3903 (contextInsertionHandlers.get(threadKey)?.(incoming.map(terminalContextReference)) ??
3904 false);
3905 set((state) => {
3906 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
3907 const acceptedContexts = normalizeTerminalContextsForThread(threadId, [
3908 ...existing.terminalContexts,
3909 ...contexts,
3910 ]).slice(existing.terminalContexts.length);
3911 if (acceptedContexts.length === 0) {
3912 return state;
3913 }
3914 return {
3915 draftsByThreadKey: {
3916 ...state.draftsByThreadKey,
3917 [threadKey]: {
3918 ...existing,
3919 prompt:
3920 placedAtCaret || options?.appendReference === false
3921 ? existing.prompt
3922 : ensureInlineContextReferences(
3923 existing.prompt,
3924 [...existing.terminalContexts, ...acceptedContexts].map(
3925 terminalContextReference,
3926 ),
3927 ),
3928 terminalContexts: [...existing.terminalContexts, ...acceptedContexts],
3929 },
3930 },
3931 };
3932 });
3933 },
3934 removeTerminalContext: (threadRef, contextId) => {
3935 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3936 if (threadKey.length === 0 || contextId.length === 0) {
3937 return;
3938 }
3939 set((state) => {
3940 const current = state.draftsByThreadKey[threadKey];
3941 if (!current) {
3942 return state;
3943 }
3944 const nextDraft: ComposerThreadDraftState = {
3945 ...current,
3946 prompt: removeInlineContextReference(
3947 current.prompt,
3948 toKindScopedComposerContextId("terminal", contextId),
3949 ).prompt,
3950 terminalContexts: current.terminalContexts.filter(
3951 (context) => context.id !== contextId,
3952 ),
3953 };
3954 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3955 if (shouldRemoveDraft(nextDraft)) {
3956 delete nextDraftsByThreadKey[threadKey];
3957 } else {
3958 nextDraftsByThreadKey[threadKey] = nextDraft;
3959 }
3960 return { draftsByThreadKey: nextDraftsByThreadKey };
3961 });
3962 },
3963 clearTerminalContexts: (threadRef) => {
3964 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
3965 if (threadKey.length === 0) {
3966 return;
3967 }
3968 set((state) => {
3969 const current = state.draftsByThreadKey[threadKey];
3970 if (!current || current.terminalContexts.length === 0) {
3971 return state;
3972 }
3973 const nextDraft: ComposerThreadDraftState = {
3974 ...current,
3975 prompt: current.terminalContexts.reduce(
3976 (prompt, context) =>
3977 removeInlineContextReference(prompt, terminalContextReference(context).contextId)
3978 .prompt,
3979 current.prompt,
3980 ),
3981 terminalContexts: [],
3982 };
3983 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
3984 if (shouldRemoveDraft(nextDraft)) {
3985 delete nextDraftsByThreadKey[threadKey];
3986 } else {
3987 nextDraftsByThreadKey[threadKey] = nextDraft;
3988 }
3989 return { draftsByThreadKey: nextDraftsByThreadKey };
3990 });
3991 },
3992 addPreviewAnnotation: (threadRef, annotation, options) => {
3993 const threadKey = resolveComposerDraftKey(get(), threadRef);
3994 if (!threadKey) return;
3995 const compactAnnotation: PreviewAnnotationPayload = {
3996 ...annotation,
3997 screenshot: annotation.screenshot ? { ...annotation.screenshot, dataUrl: "" } : null,
3998 };
3999 const reference = previewAnnotationContextReference(compactAnnotation);
4000 const current = get().draftsByThreadKey[threadKey];
4001 const alreadyPresent =
4002 current?.previewAnnotations.some((entry) => entry.id === annotation.id) ?? false;
4003 // The handler calls setPrompt; running it inside the updater would overwrite the inserted reference.
4004 const placedAtCaret =
4005 !alreadyPresent &&
4006 options?.appendReference !== false &&
4007 options?.insertAtCaret !== false &&
4008 (contextInsertionHandlers.get(threadKey)?.([reference]) ?? false);
4009 set((state) => {
4010 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4011 const nextAnnotations = existing.previewAnnotations.filter(
4012 (entry) => entry.id !== annotation.id,
4013 );
4014 return {
4015 draftsByThreadKey: {
4016 ...state.draftsByThreadKey,
4017 [threadKey]: {
4018 ...existing,
4019 prompt:
4020 alreadyPresent || placedAtCaret || options?.appendReference === false
4021 ? existing.prompt
4022 : appendInlineContextReference(existing.prompt, reference),
4023 previewAnnotations: [...nextAnnotations, compactAnnotation],
4024 },
4025 },
4026 };
4027 });
4028 },
4029 setPreviewAnnotations: (threadRef, annotations) => {
4030 const threadKey = resolveComposerDraftKey(get(), threadRef);
4031 if (!threadKey) return;
4032 set((state) => {
4033 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4034 const retainedIds = new Set(annotations.map((annotation) => annotation.id));
4035 let prompt = existing.prompt;
4036 for (const previous of existing.previewAnnotations) {
4037 if (retainedIds.has(previous.id)) continue;
4038 prompt = removeInlineContextReference(
4039 prompt,
4040 previewAnnotationContextId(previous.id),
4041 ).prompt;
4042 }
4043 prompt = ensureInlineContextReferences(
4044 prompt,
4045 annotations.map(previewAnnotationContextReference),
4046 );
4047 const nextDraft = { ...existing, prompt, previewAnnotations: [...annotations] };
4048 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4049 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4050 else nextDraftsByThreadKey[threadKey] = nextDraft;
4051 return { draftsByThreadKey: nextDraftsByThreadKey };
4052 });
4053 },
4054 setReplyTo: (threadRef, response) => {
4055 const threadKey = resolveComposerDraftKey(get(), threadRef);
4056 if (!threadKey) return;
4057 set((state) => {
4058 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4059 const nextDraft = { ...existing, replyTo: response };
4060 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4061 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4062 else nextDraftsByThreadKey[threadKey] = nextDraft;
4063 return { draftsByThreadKey: nextDraftsByThreadKey };
4064 });
4065 },
4066 removePreviewAnnotation: (threadRef, annotationId) => {
4067 const threadKey = resolveComposerDraftKey(get(), threadRef);
4068 if (!threadKey || !annotationId) return;
4069 set((state) => {
4070 const current = state.draftsByThreadKey[threadKey];
4071 if (!current) return state;
4072 const previewAnnotations = current.previewAnnotations.filter(
4073 (entry) => entry.id !== annotationId,
4074 );
4075 if (previewAnnotations.length === current.previewAnnotations.length) return state;
4076 const nextDraft = {
4077 ...current,
4078 prompt: removeInlineContextReference(
4079 current.prompt,
4080 previewAnnotationContextId(annotationId),
4081 ).prompt,
4082 previewAnnotations,
4083 images: current.images.filter((image) => image.id !== annotationId),
4084 persistedAttachments: current.persistedAttachments.filter(
4085 (image) => image.id !== annotationId,
4086 ),
4087 nonPersistedImageIds: current.nonPersistedImageIds.filter(
4088 (imageId) => imageId !== annotationId,
4089 ),
4090 };
4091 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4092 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4093 else nextDraftsByThreadKey[threadKey] = nextDraft;
4094 return { draftsByThreadKey: nextDraftsByThreadKey };
4095 });
4096 },
4097 addReviewComment: (threadRef, comment, options) => {
4098 const threadKey = resolveComposerDraftKey(get(), threadRef);
4099 if (!threadKey || !isReviewCommentContext(comment)) return;
4100 const reference = reviewCommentContextReference(comment);
4101 const current = get().draftsByThreadKey[threadKey];
4102 const alreadyPresent =
4103 current?.reviewComments.some((entry) => entry.id === comment.id) ?? false;
4104 const shouldPlaceReference =
4105 options?.appendReference !== false &&
4106 (!alreadyPresent || options?.allowDuplicateReference === true);
4107 // Editor insertion must finish before this update reads the draft it extends.
4108 const placedAtCaret =
4109 shouldPlaceReference &&
4110 options?.insertAtCaret !== false &&
4111 (contextInsertionHandlers.get(threadKey)?.([reference]) ?? false);
4112 set((state) => {
4113 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4114 const reviewComments = existing.reviewComments.filter(
4115 (entry) => entry.id !== comment.id,
4116 );
4117 return {
4118 draftsByThreadKey: {
4119 ...state.draftsByThreadKey,
4120 [threadKey]: {
4121 ...existing,
4122 prompt:
4123 !shouldPlaceReference || placedAtCaret
4124 ? existing.prompt
4125 : appendInlineContextReference(existing.prompt, reference),
4126 reviewComments: [...reviewComments, { ...comment }],
4127 },
4128 },
4129 };
4130 });
4131 },
4132 setContextInsertionHandler: (threadRef, handler) => {
4133 const threadKey = resolveComposerDraftKey(get(), threadRef);
4134 if (!threadKey) return;
4135 if (handler) contextInsertionHandlers.set(threadKey, handler);
4136 else contextInsertionHandlers.delete(threadKey);
4137 return () => {
4138 if (contextInsertionHandlers.get(threadKey) === handler) {
4139 contextInsertionHandlers.delete(threadKey);
4140 }
4141 };
4142 },
4143 setReviewComments: (threadRef, comments) => {
4144 const threadKey = resolveComposerDraftKey(get(), threadRef);
4145 if (!threadKey) return;
4146 const reviewComments = comments
4147 .filter(isReviewCommentContext)
4148 .map((comment) => ({ ...comment }));
4149 set((state) => {
4150 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4151 const retainedIds = new Set(reviewComments.map((comment) => comment.id));
4152 let prompt = existing.prompt;
4153 for (const previous of existing.reviewComments) {
4154 if (retainedIds.has(previous.id)) continue;
4155 prompt = removeInlineContextReference(
4156 prompt,
4157 reviewCommentContextId(previous.id),
4158 ).prompt;
4159 }
4160 prompt = ensureInlineContextReferences(
4161 prompt,
4162 reviewComments.map(reviewCommentContextReference),
4163 );
4164 const nextDraft = { ...existing, prompt, reviewComments };
4165 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4166 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4167 else nextDraftsByThreadKey[threadKey] = nextDraft;
4168 return { draftsByThreadKey: nextDraftsByThreadKey };
4169 });
4170 },
4171 addThreadContexts: (threadRef, records, options) => {
4172 const threadKey = resolveComposerDraftKey(get(), threadRef);
4173 if (!threadKey) return;
4174 const existingIds = new Set(
4175 (get().draftsByThreadKey[threadKey]?.threadContexts ?? []).map(
4176 (record) => record.contextId,
4177 ),
4178 );
4179 const incoming = records.filter((record) => {
4180 if (existingIds.has(record.contextId)) return false;
4181 existingIds.add(record.contextId);
4182 return true;
4183 });
4184 if (incoming.length === 0) return;
4185 const references = incoming.map(threadContextReference);
4186 const placedAtCaret =
4187 options?.appendReference !== false &&
4188 options?.insertAtCaret !== false &&
4189 (contextInsertionHandlers.get(threadKey)?.(references) ?? false);
4190 set((state) => {
4191 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4192 const known = new Set(existing.threadContexts.map((record) => record.contextId));
4193 const accepted = incoming.filter((record) => !known.has(record.contextId));
4194 if (accepted.length === 0) return state;
4195 return {
4196 draftsByThreadKey: {
4197 ...state.draftsByThreadKey,
4198 [threadKey]: {
4199 ...existing,
4200 prompt:
4201 placedAtCaret || options?.appendReference === false
4202 ? existing.prompt
4203 : ensureInlineContextReferences(
4204 existing.prompt,
4205 accepted.map(threadContextReference),
4206 ),
4207 threadContexts: [...existing.threadContexts, ...accepted],
4208 },
4209 },
4210 };
4211 });
4212 },
4213 setThreadContexts: (threadRef, records) => {
4214 const threadKey = resolveComposerDraftKey(get(), threadRef);
4215 if (!threadKey) return;
4216 const threadContexts = records
4217 .filter(isThreadContextRecord)
4218 .map((record) => ({ ...record }));
4219 set((state) => {
4220 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4221 const retainedIds = new Set(threadContexts.map((record) => record.contextId));
4222 let prompt = existing.prompt;
4223 for (const previous of existing.threadContexts) {
4224 if (retainedIds.has(previous.contextId)) continue;
4225 prompt = removeInlineContextReference(prompt, previous.contextId).prompt;
4226 }
4227 prompt = ensureInlineContextReferences(
4228 prompt,
4229 threadContexts.map(threadContextReference),
4230 );
4231 const nextDraft = { ...existing, prompt, threadContexts };
4232 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4233 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4234 else nextDraftsByThreadKey[threadKey] = nextDraft;
4235 return { draftsByThreadKey: nextDraftsByThreadKey };
4236 });
4237 },
4238 addEnvironmentContexts: (threadRef, records, options) => {
4239 const threadKey = resolveComposerDraftKey(get(), threadRef);
4240 if (!threadKey) return;
4241 const existingIds = new Set(
4242 (get().draftsByThreadKey[threadKey]?.environmentContexts ?? []).map(
4243 (record) => record.contextId,
4244 ),
4245 );
4246 const incoming = records.filter((record) => {
4247 if (existingIds.has(record.contextId)) return false;
4248 existingIds.add(record.contextId);
4249 return true;
4250 });
4251 if (incoming.length === 0) return;
4252 const references = incoming.map(environmentContextReference);
4253 const placedAtCaret =
4254 options?.appendReference !== false &&
4255 options?.insertAtCaret !== false &&
4256 (contextInsertionHandlers.get(threadKey)?.(references) ?? false);
4257 set((state) => {
4258 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4259 const known = new Set(existing.environmentContexts.map((record) => record.contextId));
4260 const accepted = incoming.filter((record) => !known.has(record.contextId));
4261 if (accepted.length === 0) return state;
4262 return {
4263 draftsByThreadKey: {
4264 ...state.draftsByThreadKey,
4265 [threadKey]: {
4266 ...existing,
4267 prompt:
4268 placedAtCaret || options?.appendReference === false
4269 ? existing.prompt
4270 : ensureInlineContextReferences(
4271 existing.prompt,
4272 accepted.map(environmentContextReference),
4273 ),
4274 environmentContexts: [...existing.environmentContexts, ...accepted],
4275 },
4276 },
4277 };
4278 });
4279 },
4280 setEnvironmentContexts: (threadRef, records) => {
4281 const threadKey = resolveComposerDraftKey(get(), threadRef);
4282 if (!threadKey) return;
4283 const environmentContexts = records
4284 .filter(isEnvironmentContextRecord)
4285 .map((record) => ({ ...record }));
4286 set((state) => {
4287 const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
4288 const retainedIds = new Set(environmentContexts.map((record) => record.contextId));
4289 let prompt = existing.prompt;
4290 for (const previous of existing.environmentContexts) {
4291 if (retainedIds.has(previous.contextId)) continue;
4292 prompt = removeInlineContextReference(prompt, previous.contextId).prompt;
4293 }
4294 prompt = ensureInlineContextReferences(
4295 prompt,
4296 environmentContexts.map(environmentContextReference),
4297 );
4298 const nextDraft = { ...existing, prompt, environmentContexts };
4299 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4300 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4301 else nextDraftsByThreadKey[threadKey] = nextDraft;
4302 return { draftsByThreadKey: nextDraftsByThreadKey };
4303 });
4304 },
4305 removeReviewComment: (threadRef, commentId) => {
4306 const threadKey = resolveComposerDraftKey(get(), threadRef);
4307 if (!threadKey || !commentId) return;
4308 set((state) => {
4309 const current = state.draftsByThreadKey[threadKey];
4310 if (!current) return state;
4311 const reviewComments = current.reviewComments.filter((entry) => entry.id !== commentId);
4312 if (reviewComments.length === current.reviewComments.length) return state;
4313 const nextDraft = {
4314 ...current,
4315 prompt: removeInlineContextReference(
4316 current.prompt,
4317 reviewCommentContextId(commentId),
4318 ).prompt,
4319 reviewComments,
4320 };
4321 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4322 if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
4323 else nextDraftsByThreadKey[threadKey] = nextDraft;
4324 return { draftsByThreadKey: nextDraftsByThreadKey };
4325 });
4326 },
4327 clearPersistedAttachments: (threadRef) => {
4328 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
4329 if (threadKey.length === 0) {
4330 return;
4331 }
4332 set((state) => {
4333 const current = state.draftsByThreadKey[threadKey];
4334 if (!current) {
4335 return state;
4336 }
4337 const nextDraft: ComposerThreadDraftState = {
4338 ...current,
4339 persistedAttachments: [],
4340 nonPersistedImageIds: [],
4341 };
4342 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4343 if (shouldRemoveDraft(nextDraft)) {
4344 delete nextDraftsByThreadKey[threadKey];
4345 } else {
4346 nextDraftsByThreadKey[threadKey] = nextDraft;
4347 }
4348 return { draftsByThreadKey: nextDraftsByThreadKey };
4349 });
4350 },
4351 syncPersistedAttachments: async (threadRef, attachments) => {
4352 const threadKey = resolveComposerDraftKey(get(), threadRef);
4353 if (!threadKey) {
4354 return;
4355 }
4356 const attachmentIdSet = new Set(attachments.map((attachment) => attachment.id));
4357 set((state) => {
4358 const current = state.draftsByThreadKey[threadKey];
4359 if (!current) {
4360 return state;
4361 }
4362 const nextDraft: ComposerThreadDraftState = {
4363 ...current,
4364 persistedAttachments: attachments,
4365 nonPersistedImageIds: current.nonPersistedImageIds.filter(
4366 (id) => !attachmentIdSet.has(id),
4367 ),
4368 };
4369 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4370 if (shouldRemoveDraft(nextDraft)) {
4371 delete nextDraftsByThreadKey[threadKey];
4372 } else {
4373 nextDraftsByThreadKey[threadKey] = nextDraft;
4374 }
4375 return { draftsByThreadKey: nextDraftsByThreadKey };
4376 });
4377 await Promise.resolve();
4378 verifyPersistedAttachments(threadKey, set);
4379 },
4380 appendPersistedAttachments: async (threadRef, images, attachments) => {
4381 const current = get().getComposerDraft(threadRef);
4382 if (!current || attachments.length === 0) return;
4383 const ownedImages = new Set(current.images);
4384 const ownedIds = new Set(
4385 images.filter((image) => ownedImages.has(image)).map(({ id }) => id),
4386 );
4387 const ownedRecords = attachments.filter(({ id }) => ownedIds.has(id));
4388 if (ownedRecords.length === 0) return;
4389 const persistedById = new Map(
4390 current.persistedAttachments.map((record) => [record.id, record]),
4391 );
4392 for (const record of ownedRecords) {
4393 if (!persistedById.has(record.id)) persistedById.set(record.id, record);
4394 }
4395 await get().syncPersistedAttachments(threadRef, [...persistedById.values()]);
4396 },
4397 clearComposerContent: (threadRef) => {
4398 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
4399 if (threadKey.length === 0) {
4400 return;
4401 }
4402 set((state) => {
4403 const current = state.draftsByThreadKey[threadKey];
4404 if (!current) {
4405 return state;
4406 }
4407 const nextDraft: ComposerThreadDraftState = {
4408 ...current,
4409 ...composerDraftContent(createEmptyThreadDraft()),
4410 };
4411 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4412 if (shouldRemoveDraft(nextDraft)) {
4413 delete nextDraftsByThreadKey[threadKey];
4414 } else {
4415 nextDraftsByThreadKey[threadKey] = nextDraft;
4416 }
4417 return { draftsByThreadKey: nextDraftsByThreadKey };
4418 });
4419 },
4420 clearComposerPromptAndImages: (threadRef) => {
4421 const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
4422 if (threadKey.length === 0) {
4423 return;
4424 }
4425 set((state) => {
4426 const current = state.draftsByThreadKey[threadKey];
4427 if (!current) {
4428 return state;
4429 }
4430 for (const image of current.images) {
4431 revokeObjectPreviewUrl(image.previewUrl);
4432 }
4433 const nextDraft: ComposerThreadDraftState = {
4434 ...current,
4435 prompt: ensureInlineContextReferences("", [
4436 ...current.terminalContexts.map(terminalContextReference),
4437 ...current.reviewComments.map(reviewCommentContextReference),
4438 ...current.threadContexts.map(threadContextReference),
4439 ...current.environmentContexts.map(environmentContextReference),
4440 ...current.previewAnnotations.map(previewAnnotationContextReference),
4441 ]),
4442 images: [],
4443 files: [],
4444 nonPersistedImageIds: [],
4445 persistedAttachments: [],
4446 };
4447 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4448 if (shouldRemoveDraft(nextDraft)) {
4449 delete nextDraftsByThreadKey[threadKey];
4450 } else {
4451 nextDraftsByThreadKey[threadKey] = nextDraft;
4452 }
4453 return { draftsByThreadKey: nextDraftsByThreadKey };
4454 });
4455 },
4456 moveComposerContent: (from, to) => {
4457 const fromKey = resolveComposerDraftKey(get(), from) ?? "";
4458 const toKey = resolveComposerDraftKey(get(), to) ?? "";
4459 if (fromKey.length === 0 || toKey.length === 0 || fromKey === toKey) {
4460 return;
4461 }
4462 set((state) => {
4463 const source = state.draftsByThreadKey[fromKey];
4464 const destination = state.draftsByThreadKey[toKey] ?? createEmptyThreadDraft();
4465 if (!source || composerDraftHasUserContent(destination)) {
4466 return state;
4467 }
4468 const destinationEnvironmentId =
4469 typeof to === "string"
4470 ? (state.draftThreadsByThreadKey[toKey]?.environmentId ??
4471 parseScopedThreadKey(toKey)?.environmentId ??
4472 null)
4473 : to.environmentId;
4474 const nextDestination = clearStaleFileUploadMetadata(
4475 { ...destination, ...composerDraftContent(source) },
4476 destinationEnvironmentId,
4477 );
4478 // Moved images still use these blob URLs at the destination; do not revoke them.
4479 const nextSource: ComposerThreadDraftState = {
4480 ...source,
4481 ...composerDraftContent(createEmptyThreadDraft()),
4482 };
4483 const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
4484 if (shouldRemoveDraft(nextSource)) {
4485 delete nextDraftsByThreadKey[fromKey];
4486 } else {
4487 nextDraftsByThreadKey[fromKey] = nextSource;
4488 }
4489 if (shouldRemoveDraft(nextDestination)) {
4490 delete nextDraftsByThreadKey[toKey];
4491 } else {
4492 nextDraftsByThreadKey[toKey] = nextDestination;
4493 }
4494 return { draftsByThreadKey: nextDraftsByThreadKey };
4495 });
4496 },
4497 };
4498 },
4499 {
4500 name: COMPOSER_DRAFT_STORAGE_KEY,
4501 version: COMPOSER_DRAFT_STORAGE_VERSION,
4502 storage: composerPersistStorage,
4503 migrate: migratePersistedComposerDraftStoreState,
4504 partialize: (state): ComposerPersistState => ({ capturedState: state }),
4505 merge: (persistedState, currentState) => {
4506 const normalizedPersisted =
4507 normalizeCurrentPersistedComposerDraftStoreState(persistedState);
4508 const draftsByThreadKey = Object.fromEntries(
4509 Object.entries(normalizedPersisted.draftsByThreadKey).map(([threadKey, draft]) => [
4510 threadKey,
4511 toHydratedThreadDraft(draft),
4512 ]),
4513 );
4514 const draftThreadsByThreadKey = Object.fromEntries(
4515 Object.entries(normalizedPersisted.draftThreadsByThreadKey).map(
4516 ([threadKey, draftThread]) => [threadKey, toHydratedDraftThreadState(draftThread)],
4517 ),
4518 ) as Record<string, DraftThreadState>;
4519 return {
4520 ...currentState,
4521 draftsByThreadKey,
4522 draftThreadsByThreadKey,
4523 logicalProjectDraftThreadKeyByLogicalProjectKey:
4524 normalizedPersisted.logicalProjectDraftThreadKeyByLogicalProjectKey,
4525 stickyModelSelectionByProvider: normalizedPersisted.stickyModelSelectionByProvider ?? {},
4526 stickyOptionsByModelByProvider: normalizedPersisted.stickyOptionsByModelByProvider ?? {},
4527 stickyActiveProvider: normalizedPersisted.stickyActiveProvider ?? null,
4528 };
4529 },
4530 },
4531 ),
4532 );
4533
4534 composerDraftLoadedState = partializeComposerDraftStoreState(composerDraftStore.getState());
4535
4536 export const useComposerDraftStore = composerDraftStore;
4537
4538 export function subscribeComposerDraftModelReconciliation(input: {
4539 readonly registry: AtomRegistry.AtomRegistry;
4540 readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
4541 readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
4542 readonly shellStateAtom: (
4543 environmentId: EnvironmentId,
4544 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
4545 readonly pendingThreadIdsAtom: (environmentId: EnvironmentId) => Atom.Atom<ReadonlySet<ThreadId>>;
4546 }): () => void {
4547 const draftsAtom = Atom.make(composerDraftStore.getState());
4548 const unsubscribeDrafts = composerDraftStore.subscribe((state) =>
4549 input.registry.set(draftsAtom, state),
4550 );
4551 const threadKeysAtom = Atom.map(
4552 input.threadRefsAtom,
4553 (refs) => new Set(refs.map(scopedThreadKey)),
4554 );
4555 const matchesAtom = Atom.make((get) => {
4556 const state = get(draftsAtom);
4557 const threadKeys = get(threadKeysAtom);
4558 const matches: Array<readonly [string, ComposerThreadDraftState]> = [];
4559 for (const [key, draft] of Object.entries(state.draftsByThreadKey)) {
4560 // Local drafts can materialize a shell before their first turn is submitted.
4561 if (state.draftThreadsByThreadKey[key] || draft.activeProvider === null) continue;
4562 const ref = parseScopedThreadKey(key);
4563 const pick = draft.modelSelectionByProvider[draft.activeProvider];
4564 if (!ref || !pick || !threadKeys.has(key)) continue;
4565 const thread = get(input.threadShellAtom(ref));
4566 if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;
4567 // The pick can match an old model while an earlier pick in flight still replaces it.
4568 if (get(input.pendingThreadIdsAtom(ref.environmentId)).has(ref.threadId)) continue;
4569 // Status and selection must come from the same emission; derived atoms can update apart.
4570 const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
4571 if (shell?.status !== "live") continue;
4572 const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
4573 (candidate) => candidate.id === ref.threadId,
4574 );
4575 if (
4576 authoritativeThread &&
4577 draftModelPickMatchesThread(pick, authoritativeThread.modelSelection)
4578 ) {
4579 matches.push([key, draft]);
4580 }
4581 }
4582 return matches;
4583 });
4584 const unsubscribeMatches = input.registry.subscribe(
4585 matchesAtom,
4586 (matches) => {
4587 if (matches.length === 0) return;
4588 composerDraftStore.setState((state) => {
4589 const drafts = { ...state.draftsByThreadKey };
4590 for (const [key, matchedDraft] of matches) {
4591 if (drafts[key] !== matchedDraft) continue;
4592 const { modelSelectionExplicit: _explicit, ...retained } = matchedDraft;
4593 const draft = { ...retained, activeProvider: null, modelSelectionByProvider: {} };
4594 if (shouldRemoveDraft(draft)) delete drafts[key];
4595 else drafts[key] = draft;
4596 }
4597 return { draftsByThreadKey: drafts };
4598 });
4599 },
4600 { immediate: true },
4601 );
4602 return () => {
4603 unsubscribeMatches();
4604 unsubscribeDrafts();
4605 };
4606 }
4607
4608 export function beginBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): void {
4609 const threadKey = scopedThreadKey(threadRef);
4610 useComposerDraftStore.setState((state) => ({
4611 backgroundSubmissionThreadKeys: { ...state.backgroundSubmissionThreadKeys, [threadKey]: true },
4612 }));
4613 }
4614
4615 export function clearBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): void {
4616 const threadKey = scopedThreadKey(threadRef);
4617 useComposerDraftStore.setState((state) => {
4618 if (!state.backgroundSubmissionThreadKeys[threadKey]) {
4619 return state;
4620 }
4621 const backgroundSubmissionThreadKeys = { ...state.backgroundSubmissionThreadKeys };
4622 delete backgroundSubmissionThreadKeys[threadKey];
4623 return { backgroundSubmissionThreadKeys };
4624 });
4625 }
4626
4627 export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): void {
4628 useComposerDraftStore.setState((state) => {
4629 const removedThreadKeys = new Set<string>();
4630
4631 for (const [threadKey, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
4632 if (draftThread.environmentId === environmentId) {
4633 removedThreadKeys.add(threadKey);
4634 }
4635 }
4636 for (const threadKey of Object.keys(state.draftsByThreadKey)) {
4637 if (parseScopedThreadKey(threadKey)?.environmentId === environmentId) {
4638 removedThreadKeys.add(threadKey);
4639 }
4640 }
4641 for (const [logicalProjectKey, threadKey] of Object.entries(
4642 state.logicalProjectDraftThreadKeyByLogicalProjectKey,
4643 )) {
4644 if (parseScopedProjectKey(logicalProjectKey)?.environmentId === environmentId) {
4645 removedThreadKeys.add(threadKey);
4646 }
4647 }
4648
4649 const nextLogicalMappings = Object.fromEntries(
4650 Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(
4651 ([logicalProjectKey, threadKey]) =>
4652 parseScopedProjectKey(logicalProjectKey)?.environmentId !== environmentId &&
4653 !removedThreadKeys.has(threadKey),
4654 ),
4655 ) as Record<string, string>;
4656 const nextDraftThreads = Object.fromEntries(
4657 Object.entries(state.draftThreadsByThreadKey).filter(
4658 ([threadKey, draftThread]) =>
4659 draftThread.environmentId !== environmentId && !removedThreadKeys.has(threadKey),
4660 ),
4661 ) as Record<string, DraftThreadState>;
4662 const nextDrafts = Object.fromEntries(
4663 Object.entries(state.draftsByThreadKey).filter(([threadKey, draft]) => {
4664 if (!removedThreadKeys.has(threadKey)) {
4665 return true;
4666 }
4667 revokeDraftThreadPreviewUrls(draft);
4668 return false;
4669 }),
4670 ) as Record<string, ComposerThreadDraftState>;
4671 const nextBackgroundSubmissionThreadKeys = Object.fromEntries(
4672 Object.entries(state.backgroundSubmissionThreadKeys).filter(
4673 ([threadKey]) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,
4674 ),
4675 ) as Record<string, true>;
4676 const nextPromotedDraftRedirects = Object.fromEntries(
4677 Object.entries(state.promotedDraftRedirects).filter(
4678 ([, promotedTo]) => promotedTo.environmentId !== environmentId,
4679 ),
4680 ) as Record<string, ScopedThreadRef>;
4681
4682 return {
4683 draftsByThreadKey: nextDrafts,
4684 draftThreadsByThreadKey: nextDraftThreads,
4685 logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings,
4686 backgroundSubmissionThreadKeys: nextBackgroundSubmissionThreadKeys,
4687 promotedDraftRedirects: nextPromotedDraftRedirects,
4688 rewindingThreadKeys: new Set(
4689 [...state.rewindingThreadKeys].filter(
4690 (threadKey) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,
4691 ),
4692 ),
4693 };
4694 });
4695 composerDebouncedStorage.flush();
4696 }
4697
4698 export function useComposerThreadDraft(threadRef: ComposerThreadTarget): ComposerThreadDraftState {
4699 return useComposerDraftStore((state) => {
4700 return getComposerDraftState(state, threadRef) ?? EMPTY_THREAD_DRAFT;
4701 });
4702 }
4703
4704 export function useThreadHasUnsentDraft(threadRef: ScopedThreadRef): boolean {
4705 return useComposerDraftStore((state) =>
4706 composerDraftHasUserContent(getComposerDraftState(state, threadRef)),
4707 );
4708 }
4709
4710 export function useComposerDraftModelState(
4711 threadRef: ComposerThreadTarget,
4712 ): ComposerDraftModelState {
4713 return useComposerDraftStore(
4714 useShallow((state) => {
4715 const draft = getComposerDraftState(state, threadRef);
4716 return draft
4717 ? {
4718 activeProvider: draft.activeProvider,
4719 modelSelectionByProvider: draft.modelSelectionByProvider,
4720 modelSelectionExplicit: draft.modelSelectionExplicit === true,
4721 }
4722 : EMPTY_COMPOSER_DRAFT_MODEL_STATE;
4723 }),
4724 );
4725 }
4726
4727 /** Threads a sent draft is launching into: from their shell's arrival until the server owns the send. */
4728 export function usePromotingDraftThreadKeys(): ReadonlyArray<string> {
4729 return useComposerDraftStore(
4730 useShallow((state) =>
4731 Object.values(state.draftThreadsByThreadKey).flatMap((draft) =>
4732 draft.promotedTo ? [scopedThreadKey(draft.promotedTo)] : [],
4733 ),
4734 ),
4735 );
4736 }
4737
4738 export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): void {
4739 const draftStore = useComposerDraftStore.getState();
4740 for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) {
4741 if (
4742 draftThread.environmentId === threadRef.environmentId &&
4743 draftThread.threadId === threadRef.threadId
4744 ) {
4745 draftStore.markDraftThreadPromoting(DraftId.make(draftId), threadRef);
4746 }
4747 }
4748 }
4749
4750 export function restoreFailedDraftThread(
4751 draftId: DraftId,
4752 draftThread: DraftThreadState,
4753 threadId: ThreadId,
4754 ): void {
4755 useComposerDraftStore.setState((state) => ({
4756 draftThreadsByThreadKey: {
4757 ...state.draftThreadsByThreadKey,
4758 [draftId]: {
4759 ...(state.draftThreadsByThreadKey[draftId] ?? draftThread),
4760 threadId,
4761 ...(threadId !== draftThread.threadId ? { createdAt: new Date().toISOString() } : {}),
4762 promotedTo: null,
4763 },
4764 },
4765 }));
4766 }
4767
4768 export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): void {
4769 const draftStore = useComposerDraftStore.getState();
4770 for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) {
4771 const promotedRef = draftThread.promotedTo;
4772 const matches = promotedRef
4773 ? promotedRef.environmentId === threadRef.environmentId &&
4774 promotedRef.threadId === threadRef.threadId
4775 : draftThread.environmentId === threadRef.environmentId &&
4776 draftThread.threadId === threadRef.threadId;
4777 if (matches) {
4778 const target = DraftId.make(draftId);
4779 draftStore.markDraftThreadPromoting(target, threadRef);
4780 draftStore.finalizePromotedDraftThread(target);
4781 }
4782 }
4783 clearBackgroundDraftSubmissionByRef(threadRef);
4784 }
4785
4786 type DraftPromotionShell = Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt">;
4787
4788 /** The server owns a draft's send once its message persisted or its run started or stopped. */
4789 export function resolveDraftPromotionNavigationTarget(input: {
4790 serverThreadRef: ScopedThreadRef | null;
4791 serverThread: DraftPromotionShell | null | undefined;
4792 backgroundSubmissionPending: boolean;
4793 }): ScopedThreadRef | null {
4794 if (input.backgroundSubmissionPending) {
4795 return null;
4796 }
4797 const latestRun = input.serverThread?.latestRun ?? null;
4798 const runStarted = latestRun?.startedAt != null;
4799 const startupStopped =
4800 latestRun?.status === "failed" ||
4801 latestRun?.status === "interrupted" ||
4802 latestRun?.status === "cancelled";
4803 const messagePersisted = input.serverThread?.latestUserMessageAt != null;
4804 return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;
4805 }
4806
4807 /**
4808 * Drives every draft through promotion as server shells arrive: a draft whose reserved thread
4809 * appears on the server becomes promoting, and once the server owns its send (and any hero
4810 * transition has played) it finalizes into that thread. The draft route follows the redirect
4811 * that finalization records, so no route has to watch for these milestones.
4812 */
4813 export function subscribeDraftThreadPromotion(input: {
4814 readonly registry: AtomRegistry.AtomRegistry;
4815 readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
4816 readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<DraftPromotionShell | null>;
4817 }): () => void {
4818 // Only the promotion slices: prompt edits replace the store state on every keystroke.
4819 const promotionSlices = (state: ComposerDraftStoreState) => ({
4820 draftThreadsByThreadKey: state.draftThreadsByThreadKey,
4821 backgroundSubmissionThreadKeys: state.backgroundSubmissionThreadKeys,
4822 });
4823 const draftsAtom = Atom.make(promotionSlices(composerDraftStore.getState()));
4824 const unsubscribeDrafts = composerDraftStore.subscribe((state, previous) => {
4825 if (
4826 state.draftThreadsByThreadKey === previous.draftThreadsByThreadKey &&
4827 state.backgroundSubmissionThreadKeys === previous.backgroundSubmissionThreadKeys
4828 ) {
4829 return;
4830 }
4831 input.registry.set(draftsAtom, promotionSlices(state));
4832 });
4833 const threadKeysAtom = Atom.map(
4834 input.threadRefsAtom,
4835 (refs) => new Set(refs.map(scopedThreadKey)),
4836 );
4837 const milestonesAtom = Atom.make((get) => {
4838 const state = get(draftsAtom);
4839 const threadKeys = get(threadKeysAtom);
4840 const arrived: Array<readonly [DraftId, ScopedThreadRef]> = [];
4841 const owned: Array<readonly [DraftId, ScopedThreadRef]> = [];
4842 for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
4843 const ref =
4844 draftThread.promotedTo ?? scopeThreadRef(draftThread.environmentId, draftThread.threadId);
4845 const threadKey = scopedThreadKey(ref);
4846 if (!threadKeys.has(threadKey)) continue;
4847 if (!draftThread.promotedTo) {
4848 arrived.push([DraftId.make(draftId), ref]);
4849 continue;
4850 }
4851 const target = resolveDraftPromotionNavigationTarget({
4852 serverThreadRef: ref,
4853 serverThread: get(input.threadShellAtom(ref)),
4854 backgroundSubmissionPending: state.backgroundSubmissionThreadKeys[threadKey] === true,
4855 });
4856 if (target) owned.push([DraftId.make(draftId), target]);
4857 }
4858 return { arrived, owned };
4859 });
4860 let disposed = false;
4861 const finalizing = new Set<DraftId>();
4862 const unsubscribeMilestones = input.registry.subscribe(
4863 milestonesAtom,
4864 ({ arrived, owned }) => {
4865 const store = composerDraftStore.getState();
4866 for (const [draftId, ref] of arrived) {
4867 store.markDraftThreadPromoting(draftId, ref);
4868 }
4869 for (const [draftId, ref] of owned) {
4870 if (finalizing.has(draftId)) continue;
4871 finalizing.add(draftId);
4872 void waitForDraftHeroTransition().then(() => {
4873 finalizing.delete(draftId);
4874 if (disposed) return;
4875 const current = composerDraftStore.getState().draftThreadsByThreadKey[draftId];
4876 if (!current || !scopedThreadRefsEqual(current.promotedTo, ref)) return;
4877 finalizePromotedDraftThreadByRef(ref);
4878 });
4879 }
4880 },
4881 { immediate: true },
4882 );
4883 return () => {
4884 disposed = true;
4885 unsubscribeMilestones();
4886 unsubscribeDrafts();
4887 };
4888 }