Open History to see the last commit
1import {
2 DEFAULT_REASONING_EFFORT_BY_PROVIDER,
3 ProjectId,
4 REASONING_EFFORT_OPTIONS_BY_PROVIDER,
5 ThreadId,
6 type CodexReasoningEffort,
7 type ProviderKind,
8 type ProviderInteractionMode,
9 type RuntimeMode,
10} from "@t3tools/contracts";
11import { normalizeModelSlug } from "@t3tools/shared/model";
12import {
13 DEFAULT_INTERACTION_MODE,
14 DEFAULT_RUNTIME_MODE,
15 type ChatImageAttachment,
16} from "./types";
17import { create } from "zustand";
18import { createJSONStorage, persist } from "zustand/middleware";
19
20export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
21export type DraftThreadEnvMode = "local" | "worktree";
22
23export interface PersistedComposerImageAttachment {
24 id: string;
25 name: string;
26 mimeType: string;
27 sizeBytes: number;
28 dataUrl: string;
29}
30
31export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
32 previewUrl: string;
33 file: File;
34}
35
36interface PersistedComposerThreadDraftState {
37 prompt: string;
38 attachments: PersistedComposerImageAttachment[];
39 provider?: ProviderKind | null;
40 model?: string | null;
41 runtimeMode?: RuntimeMode | null;
42 interactionMode?: ProviderInteractionMode | null;
43 effort?: CodexReasoningEffort | null;
44 codexFastMode?: boolean | null;
45 serviceTier?: string | null;
46}
47
48interface PersistedDraftThreadState {
49 projectId: ProjectId;
50 createdAt: string;
51 runtimeMode: RuntimeMode;
52 interactionMode: ProviderInteractionMode;
53 branch: string | null;
54 worktreePath: string | null;
55 envMode: DraftThreadEnvMode;
56}
57
58interface PersistedComposerDraftStoreState {
59 draftsByThreadId: Record<ThreadId, PersistedComposerThreadDraftState>;
60 draftThreadsByThreadId: Record<ThreadId, PersistedDraftThreadState>;
61 projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
62}
63
64interface ComposerThreadDraftState {
65 prompt: string;
66 images: ComposerImageAttachment[];
67 nonPersistedImageIds: string[];
68 persistedAttachments: PersistedComposerImageAttachment[];
69 provider: ProviderKind | null;
70 model: string | null;
71 runtimeMode: RuntimeMode | null;
72 interactionMode: ProviderInteractionMode | null;
73 effort: CodexReasoningEffort | null;
74 codexFastMode: boolean;
75}
76
77export interface DraftThreadState {
78 projectId: ProjectId;
79 createdAt: string;
80 runtimeMode: RuntimeMode;
81 interactionMode: ProviderInteractionMode;
82 branch: string | null;
83 worktreePath: string | null;
84 envMode: DraftThreadEnvMode;
85}
86
87interface ProjectDraftThread extends DraftThreadState {
88 threadId: ThreadId;
89}
90
91interface ComposerDraftStoreState {
92 draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
93 draftThreadsByThreadId: Record<ThreadId, DraftThreadState>;
94 projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
95 getDraftThreadByProjectId: (projectId: ProjectId) => ProjectDraftThread | null;
96 getDraftThread: (threadId: ThreadId) => DraftThreadState | null;
97 setProjectDraftThreadId: (
98 projectId: ProjectId,
99 threadId: ThreadId,
100 options?: {
101 branch?: string | null;
102 worktreePath?: string | null;
103 createdAt?: string;
104 envMode?: DraftThreadEnvMode;
105 runtimeMode?: RuntimeMode;
106 interactionMode?: ProviderInteractionMode;
107 },
108 ) => void;
109 setDraftThreadContext: (
110 threadId: ThreadId,
111 options: {
112 branch?: string | null;
113 worktreePath?: string | null;
114 projectId?: ProjectId;
115 createdAt?: string;
116 envMode?: DraftThreadEnvMode;
117 runtimeMode?: RuntimeMode;
118 interactionMode?: ProviderInteractionMode;
119 },
120 ) => void;
121 clearProjectDraftThreadId: (projectId: ProjectId) => void;
122 clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
123 clearDraftThread: (threadId: ThreadId) => void;
124 setPrompt: (threadId: ThreadId, prompt: string) => void;
125 setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
126 setModel: (threadId: ThreadId, model: string | null | undefined) => void;
127 setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
128 setInteractionMode: (
129 threadId: ThreadId,
130 interactionMode: ProviderInteractionMode | null | undefined,
131 ) => void;
132 setEffort: (threadId: ThreadId, effort: CodexReasoningEffort | null | undefined) => void;
133 setCodexFastMode: (threadId: ThreadId, enabled: boolean | null | undefined) => void;
134 addImage: (threadId: ThreadId, image: ComposerImageAttachment) => void;
135 addImages: (threadId: ThreadId, images: ComposerImageAttachment[]) => void;
136 removeImage: (threadId: ThreadId, imageId: string) => void;
137 clearPersistedAttachments: (threadId: ThreadId) => void;
138 syncPersistedAttachments: (
139 threadId: ThreadId,
140 attachments: PersistedComposerImageAttachment[],
141 ) => void;
142 clearComposerContent: (threadId: ThreadId) => void;
143 clearThreadDraft: (threadId: ThreadId) => void;
144}
145
146const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
147 draftsByThreadId: {},
148 draftThreadsByThreadId: {},
149 projectDraftThreadIdByProjectId: {},
150};
151
152const EMPTY_IMAGES: ComposerImageAttachment[] = [];
153const EMPTY_IDS: string[] = [];
154const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
155Object.freeze(EMPTY_IMAGES);
156Object.freeze(EMPTY_IDS);
157Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
158const EMPTY_THREAD_DRAFT = Object.freeze({
159 prompt: "",
160 images: EMPTY_IMAGES,
161 nonPersistedImageIds: EMPTY_IDS,
162 persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
163 provider: null,
164 model: null,
165 runtimeMode: null,
166 interactionMode: null,
167 effort: null,
168 codexFastMode: false,
169}) as ComposerThreadDraftState;
170
171const REASONING_EFFORT_VALUES = new Set<CodexReasoningEffort>(
172 REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex,
173);
174
175function createEmptyThreadDraft(): ComposerThreadDraftState {
176 return {
177 prompt: "",
178 images: [],
179 nonPersistedImageIds: [],
180 persistedAttachments: [],
181 provider: null,
182 model: null,
183 runtimeMode: null,
184 interactionMode: null,
185 effort: null,
186 codexFastMode: false,
187 };
188}
189
190function composerImageDedupKey(image: ComposerImageAttachment): string {
191 // Keep this independent from File.lastModified so dedupe is stable for hydrated
192 // images reconstructed from localStorage (which get a fresh lastModified value).
193 return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
194}
195
196function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
197 return (
198 draft.prompt.length === 0 &&
199 draft.images.length === 0 &&
200 draft.persistedAttachments.length === 0 &&
201 draft.provider === null &&
202 draft.model === null &&
203 draft.runtimeMode === null &&
204 draft.interactionMode === null &&
205 draft.effort === null &&
206 draft.codexFastMode === false
207 );
208}
209
210function normalizeProviderKind(value: unknown): ProviderKind | null {
211 return value === "codex" ? value : null;
212}
213
214function revokeObjectPreviewUrl(previewUrl: string): void {
215 if (typeof URL === "undefined") {
216 return;
217 }
218 if (!previewUrl.startsWith("blob:")) {
219 return;
220 }
221 URL.revokeObjectURL(previewUrl);
222}
223
224function normalizePersistedAttachment(value: unknown): PersistedComposerImageAttachment | null {
225 if (!value || typeof value !== "object") {
226 return null;
227 }
228 const candidate = value as Record<string, unknown>;
229 const id = candidate.id;
230 const name = candidate.name;
231 const mimeType = candidate.mimeType;
232 const sizeBytes = candidate.sizeBytes;
233 const dataUrl = candidate.dataUrl;
234 if (
235 typeof id !== "string" ||
236 typeof name !== "string" ||
237 typeof mimeType !== "string" ||
238 typeof sizeBytes !== "number" ||
239 !Number.isFinite(sizeBytes) ||
240 typeof dataUrl !== "string" ||
241 id.length === 0 ||
242 dataUrl.length === 0
243 ) {
244 return null;
245 }
246 return {
247 id,
248 name,
249 mimeType,
250 sizeBytes,
251 dataUrl,
252 };
253}
254
255function normalizeDraftThreadEnvMode(
256 value: unknown,
257 fallbackWorktreePath: string | null,
258): DraftThreadEnvMode {
259 if (value === "local" || value === "worktree") {
260 return value;
261 }
262 return fallbackWorktreePath ? "worktree" : "local";
263}
264
265function normalizePersistedComposerDraftState(value: unknown): PersistedComposerDraftStoreState {
266 if (!value || typeof value !== "object") {
267 return EMPTY_PERSISTED_DRAFT_STORE_STATE;
268 }
269 const candidate = value as Record<string, unknown>;
270 const rawDraftMap = candidate.draftsByThreadId;
271 const rawDraftThreadsByThreadId = candidate.draftThreadsByThreadId;
272 const rawProjectDraftThreadIdByProjectId = candidate.projectDraftThreadIdByProjectId;
273 const draftThreadsByThreadId: PersistedComposerDraftStoreState["draftThreadsByThreadId"] = {};
274 if (rawDraftThreadsByThreadId && typeof rawDraftThreadsByThreadId === "object") {
275 for (const [threadId, rawDraftThread] of Object.entries(
276 rawDraftThreadsByThreadId as Record<string, unknown>,
277 )) {
278 if (typeof threadId !== "string" || threadId.length === 0) {
279 continue;
280 }
281 if (!rawDraftThread || typeof rawDraftThread !== "object") {
282 continue;
283 }
284 const candidateDraftThread = rawDraftThread as Record<string, unknown>;
285 const projectId = candidateDraftThread.projectId;
286 const createdAt = candidateDraftThread.createdAt;
287 const branch = candidateDraftThread.branch;
288 const worktreePath = candidateDraftThread.worktreePath;
289 const normalizedWorktreePath = typeof worktreePath === "string" ? worktreePath : null;
290 if (typeof projectId !== "string" || projectId.length === 0) {
291 continue;
292 }
293 draftThreadsByThreadId[threadId as ThreadId] = {
294 projectId: projectId as ProjectId,
295 createdAt:
296 typeof createdAt === "string" && createdAt.length > 0
297 ? createdAt
298 : new Date().toISOString(),
299 runtimeMode:
300 candidateDraftThread.runtimeMode === "approval-required" ||
301 candidateDraftThread.runtimeMode === "full-access"
302 ? candidateDraftThread.runtimeMode
303 : DEFAULT_RUNTIME_MODE,
304 interactionMode:
305 candidateDraftThread.interactionMode === "plan" ||
306 candidateDraftThread.interactionMode === "default"
307 ? candidateDraftThread.interactionMode
308 : DEFAULT_INTERACTION_MODE,
309 branch: typeof branch === "string" ? branch : null,
310 worktreePath: normalizedWorktreePath,
311 envMode: normalizeDraftThreadEnvMode(candidateDraftThread.envMode, normalizedWorktreePath),
312 };
313 }
314 }
315 const projectDraftThreadIdByProjectId: PersistedComposerDraftStoreState["projectDraftThreadIdByProjectId"] =
316 {};
317 if (
318 rawProjectDraftThreadIdByProjectId &&
319 typeof rawProjectDraftThreadIdByProjectId === "object"
320 ) {
321 for (const [projectId, threadId] of Object.entries(
322 rawProjectDraftThreadIdByProjectId as Record<string, unknown>,
323 )) {
324 if (
325 typeof projectId === "string" &&
326 projectId.length > 0 &&
327 typeof threadId === "string" &&
328 threadId.length > 0
329 ) {
330 projectDraftThreadIdByProjectId[projectId as ProjectId] = threadId as ThreadId;
331 if (!draftThreadsByThreadId[threadId as ThreadId]) {
332 draftThreadsByThreadId[threadId as ThreadId] = {
333 projectId: projectId as ProjectId,
334 createdAt: new Date().toISOString(),
335 runtimeMode: DEFAULT_RUNTIME_MODE,
336 interactionMode: DEFAULT_INTERACTION_MODE,
337 branch: null,
338 worktreePath: null,
339 envMode: "local",
340 };
341 } else if (draftThreadsByThreadId[threadId as ThreadId]?.projectId !== projectId) {
342 draftThreadsByThreadId[threadId as ThreadId] = {
343 ...draftThreadsByThreadId[threadId as ThreadId]!,
344 projectId: projectId as ProjectId,
345 };
346 }
347 }
348 }
349 }
350 if (!rawDraftMap || typeof rawDraftMap !== "object") {
351 return { draftsByThreadId: {}, draftThreadsByThreadId, projectDraftThreadIdByProjectId };
352 }
353 const nextDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
354 for (const [threadId, draftValue] of Object.entries(rawDraftMap as Record<string, unknown>)) {
355 if (typeof threadId !== "string" || threadId.length === 0) {
356 continue;
357 }
358 if (!draftValue || typeof draftValue !== "object") {
359 continue;
360 }
361 const draftCandidate = draftValue as Record<string, unknown>;
362 const prompt = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
363 const attachments = Array.isArray(draftCandidate.attachments)
364 ? draftCandidate.attachments.flatMap((entry) => {
365 const normalized = normalizePersistedAttachment(entry);
366 return normalized ? [normalized] : [];
367 })
368 : [];
369 const provider = normalizeProviderKind(draftCandidate.provider);
370 const model =
371 typeof draftCandidate.model === "string"
372 ? normalizeModelSlug(draftCandidate.model, provider ?? "codex")
373 : null;
374 const runtimeMode =
375 draftCandidate.runtimeMode === "approval-required" ||
376 draftCandidate.runtimeMode === "full-access"
377 ? draftCandidate.runtimeMode
378 : null;
379 const interactionMode =
380 draftCandidate.interactionMode === "plan" || draftCandidate.interactionMode === "default"
381 ? draftCandidate.interactionMode
382 : null;
383 const effortCandidate =
384 typeof draftCandidate.effort === "string" ? draftCandidate.effort : null;
385 const effort =
386 effortCandidate && REASONING_EFFORT_VALUES.has(effortCandidate as CodexReasoningEffort)
387 ? (effortCandidate as CodexReasoningEffort)
388 : null;
389 const codexFastMode =
390 draftCandidate.codexFastMode === true ||
391 (typeof draftCandidate.serviceTier === "string" && draftCandidate.serviceTier === "fast");
392 if (
393 prompt.length === 0 &&
394 attachments.length === 0 &&
395 !provider &&
396 !model &&
397 !runtimeMode &&
398 !interactionMode &&
399 !effort &&
400 !codexFastMode
401 ) {
402 continue;
403 }
404 nextDraftsByThreadId[threadId as ThreadId] = {
405 prompt,
406 attachments,
407 ...(provider ? { provider } : {}),
408 ...(model ? { model } : {}),
409 ...(runtimeMode ? { runtimeMode } : {}),
410 ...(interactionMode ? { interactionMode } : {}),
411 ...(effort ? { effort } : {}),
412 ...(codexFastMode ? { codexFastMode } : {}),
413 };
414 }
415 return {
416 draftsByThreadId: nextDraftsByThreadId,
417 draftThreadsByThreadId,
418 projectDraftThreadIdByProjectId,
419 };
420}
421
422function parsePersistedDraftStateRaw(raw: string | null): PersistedComposerDraftStoreState {
423 if (!raw) {
424 return EMPTY_PERSISTED_DRAFT_STORE_STATE;
425 }
426 try {
427 const parsed = JSON.parse(raw) as unknown;
428 if (parsed && typeof parsed === "object" && "state" in parsed) {
429 return normalizePersistedComposerDraftState((parsed as { state?: unknown }).state);
430 }
431 return normalizePersistedComposerDraftState(parsed);
432 } catch {
433 return EMPTY_PERSISTED_DRAFT_STORE_STATE;
434 }
435}
436
437function readPersistedAttachmentIdsFromStorage(threadId: ThreadId): string[] {
438 if (threadId.length === 0) {
439 return [];
440 }
441 try {
442 const raw = localStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY);
443 const persisted = parsePersistedDraftStateRaw(raw);
444 return (persisted.draftsByThreadId[threadId]?.attachments ?? []).map(
445 (attachment) => attachment.id,
446 );
447 } catch {
448 return [];
449 }
450}
451
452function hydreatePersistedComposerImageAttachment(
453 attachment: PersistedComposerImageAttachment,
454): File | null {
455 const commaIndex = attachment.dataUrl.indexOf(",");
456 const header =
457 commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);
458 const payload = commaIndex === -1 ? "" : attachment.dataUrl.slice(commaIndex + 1);
459 if (payload.length === 0) {
460 return null;
461 }
462 try {
463 const isBase64 = header.includes(";base64");
464 if (!isBase64) {
465 const decodedText = decodeURIComponent(payload);
466 const inferredMimeType =
467 header.startsWith("data:") && header.includes(";")
468 ? header.slice("data:".length, header.indexOf(";"))
469 : attachment.mimeType;
470 return new File([decodedText], attachment.name, {
471 type: inferredMimeType || attachment.mimeType,
472 });
473 }
474 const binary = atob(payload);
475 const bytes = new Uint8Array(binary.length);
476 for (let index = 0; index < binary.length; index += 1) {
477 bytes[index] = binary.charCodeAt(index);
478 }
479 return new File([bytes], attachment.name, { type: attachment.mimeType });
480 } catch {
481 return null;
482 }
483}
484
485function hydrateImagesFromPersisted(
486 attachments: PersistedComposerImageAttachment[],
487): ComposerImageAttachment[] {
488 return attachments.flatMap((attachment) => {
489 const file = hydreatePersistedComposerImageAttachment(attachment);
490 if (!file) return [];
491
492 return [
493 {
494 type: "image" as const,
495 id: attachment.id,
496 name: attachment.name,
497 mimeType: attachment.mimeType,
498 sizeBytes: attachment.sizeBytes,
499 previewUrl: attachment.dataUrl,
500 file,
501 } satisfies ComposerImageAttachment,
502 ];
503 });
504}
505
506function toHydratedThreadDraft(
507 persistedDraft: PersistedComposerThreadDraftState,
508): ComposerThreadDraftState {
509 return {
510 prompt: persistedDraft.prompt,
511 images: hydrateImagesFromPersisted(persistedDraft.attachments),
512 nonPersistedImageIds: [],
513 persistedAttachments: persistedDraft.attachments,
514 provider: persistedDraft.provider ?? null,
515 model: persistedDraft.model ?? null,
516 runtimeMode: persistedDraft.runtimeMode ?? null,
517 interactionMode: persistedDraft.interactionMode ?? null,
518 effort: persistedDraft.effort ?? null,
519 codexFastMode: persistedDraft.codexFastMode === true,
520 };
521}
522
523export const useComposerDraftStore = create<ComposerDraftStoreState>()(
524 persist(
525 (set, get) => ({
526 draftsByThreadId: {},
527 draftThreadsByThreadId: {},
528 projectDraftThreadIdByProjectId: {},
529 getDraftThreadByProjectId: (projectId) => {
530 if (projectId.length === 0) {
531 return null;
532 }
533 const threadId = get().projectDraftThreadIdByProjectId[projectId];
534 if (!threadId) {
535 return null;
536 }
537 const draftThread = get().draftThreadsByThreadId[threadId];
538 if (!draftThread || draftThread.projectId !== projectId) {
539 return null;
540 }
541 return {
542 threadId,
543 ...draftThread,
544 };
545 },
546 getDraftThread: (threadId) => {
547 if (threadId.length === 0) {
548 return null;
549 }
550 return get().draftThreadsByThreadId[threadId] ?? null;
551 },
552 setProjectDraftThreadId: (projectId, threadId, options) => {
553 if (projectId.length === 0 || threadId.length === 0) {
554 return;
555 }
556 set((state) => {
557 const existingThread = state.draftThreadsByThreadId[threadId];
558 const previousThreadIdForProject = state.projectDraftThreadIdByProjectId[projectId];
559 const nextWorktreePath =
560 options?.worktreePath === undefined
561 ? (existingThread?.worktreePath ?? null)
562 : (options.worktreePath ?? null);
563 const nextDraftThread: DraftThreadState = {
564 projectId,
565 createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),
566 runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
567 interactionMode:
568 options?.interactionMode ??
569 existingThread?.interactionMode ??
570 DEFAULT_INTERACTION_MODE,
571 branch:
572 options?.branch === undefined
573 ? (existingThread?.branch ?? null)
574 : (options.branch ?? null),
575 worktreePath: nextWorktreePath,
576 envMode:
577 options?.envMode ??
578 (nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")),
579 };
580 const hasSameProjectMapping = previousThreadIdForProject === threadId;
581 const hasSameDraftThread =
582 existingThread &&
583 existingThread.projectId === nextDraftThread.projectId &&
584 existingThread.createdAt === nextDraftThread.createdAt &&
585 existingThread.runtimeMode === nextDraftThread.runtimeMode &&
586 existingThread.interactionMode === nextDraftThread.interactionMode &&
587 existingThread.branch === nextDraftThread.branch &&
588 existingThread.worktreePath === nextDraftThread.worktreePath &&
589 existingThread.envMode === nextDraftThread.envMode;
590 if (hasSameProjectMapping && hasSameDraftThread) {
591 return state;
592 }
593 const nextProjectDraftThreadIdByProjectId: Record<ProjectId, ThreadId> = {
594 ...state.projectDraftThreadIdByProjectId,
595 [projectId]: threadId,
596 };
597 const nextDraftThreadsByThreadId: Record<ThreadId, DraftThreadState> = {
598 ...state.draftThreadsByThreadId,
599 [threadId]: nextDraftThread,
600 };
601 let nextDraftsByThreadId = state.draftsByThreadId;
602 if (
603 previousThreadIdForProject &&
604 previousThreadIdForProject !== threadId &&
605 !Object.values(nextProjectDraftThreadIdByProjectId).includes(previousThreadIdForProject)
606 ) {
607 delete nextDraftThreadsByThreadId[previousThreadIdForProject];
608 if (state.draftsByThreadId[previousThreadIdForProject] !== undefined) {
609 nextDraftsByThreadId = { ...state.draftsByThreadId };
610 delete nextDraftsByThreadId[previousThreadIdForProject];
611 }
612 }
613 return {
614 draftsByThreadId: nextDraftsByThreadId,
615 draftThreadsByThreadId: nextDraftThreadsByThreadId,
616 projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
617 };
618 });
619 },
620 setDraftThreadContext: (threadId, options) => {
621 if (threadId.length === 0) {
622 return;
623 }
624 set((state) => {
625 const existing = state.draftThreadsByThreadId[threadId];
626 if (!existing) {
627 return state;
628 }
629 const nextProjectId = options.projectId ?? existing.projectId;
630 if (nextProjectId.length === 0) {
631 return state;
632 }
633 const nextWorktreePath =
634 options.worktreePath === undefined ? existing.worktreePath : (options.worktreePath ?? null);
635 const nextDraftThread: DraftThreadState = {
636 projectId: nextProjectId,
637 createdAt:
638 options.createdAt === undefined
639 ? existing.createdAt
640 : options.createdAt || existing.createdAt,
641 runtimeMode: options.runtimeMode ?? existing.runtimeMode,
642 interactionMode: options.interactionMode ?? existing.interactionMode,
643 branch: options.branch === undefined ? existing.branch : (options.branch ?? null),
644 worktreePath: nextWorktreePath,
645 envMode:
646 options.envMode ??
647 (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
648 };
649 const isUnchanged =
650 nextDraftThread.projectId === existing.projectId &&
651 nextDraftThread.createdAt === existing.createdAt &&
652 nextDraftThread.runtimeMode === existing.runtimeMode &&
653 nextDraftThread.interactionMode === existing.interactionMode &&
654 nextDraftThread.branch === existing.branch &&
655 nextDraftThread.worktreePath === existing.worktreePath &&
656 nextDraftThread.envMode === existing.envMode;
657 if (isUnchanged) {
658 return state;
659 }
660 const nextProjectDraftThreadIdByProjectId: Record<ProjectId, ThreadId> = {
661 ...state.projectDraftThreadIdByProjectId,
662 [nextProjectId]: threadId,
663 };
664 if (existing.projectId !== nextProjectId) {
665 if (nextProjectDraftThreadIdByProjectId[existing.projectId] === threadId) {
666 delete nextProjectDraftThreadIdByProjectId[existing.projectId];
667 }
668 }
669 return {
670 draftThreadsByThreadId: {
671 ...state.draftThreadsByThreadId,
672 [threadId]: nextDraftThread,
673 },
674 projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
675 };
676 });
677 },
678 clearProjectDraftThreadId: (projectId) => {
679 if (projectId.length === 0) {
680 return;
681 }
682 set((state) => {
683 const threadId = state.projectDraftThreadIdByProjectId[projectId];
684 if (threadId === undefined) {
685 return state;
686 }
687 const { [projectId]: _removed, ...restProjectMappingsRaw } =
688 state.projectDraftThreadIdByProjectId;
689 const restProjectMappings = restProjectMappingsRaw as Record<ProjectId, ThreadId>;
690 const nextDraftThreadsByThreadId: Record<ThreadId, DraftThreadState> = {
691 ...state.draftThreadsByThreadId,
692 };
693 let nextDraftsByThreadId = state.draftsByThreadId;
694 if (!Object.values(restProjectMappings).includes(threadId)) {
695 delete nextDraftThreadsByThreadId[threadId];
696 if (state.draftsByThreadId[threadId] !== undefined) {
697 nextDraftsByThreadId = { ...state.draftsByThreadId };
698 delete nextDraftsByThreadId[threadId];
699 }
700 }
701 return {
702 draftsByThreadId: nextDraftsByThreadId,
703 draftThreadsByThreadId: nextDraftThreadsByThreadId,
704 projectDraftThreadIdByProjectId: restProjectMappings,
705 };
706 });
707 },
708 clearProjectDraftThreadById: (projectId, threadId) => {
709 if (projectId.length === 0 || threadId.length === 0) {
710 return;
711 }
712 set((state) => {
713 if (state.projectDraftThreadIdByProjectId[projectId] !== threadId) {
714 return state;
715 }
716 const { [projectId]: _removed, ...restProjectMappingsRaw } =
717 state.projectDraftThreadIdByProjectId;
718 const restProjectMappings = restProjectMappingsRaw as Record<ProjectId, ThreadId>;
719 const nextDraftThreadsByThreadId: Record<ThreadId, DraftThreadState> = {
720 ...state.draftThreadsByThreadId,
721 };
722 let nextDraftsByThreadId = state.draftsByThreadId;
723 if (!Object.values(restProjectMappings).includes(threadId)) {
724 delete nextDraftThreadsByThreadId[threadId];
725 if (state.draftsByThreadId[threadId] !== undefined) {
726 nextDraftsByThreadId = { ...state.draftsByThreadId };
727 delete nextDraftsByThreadId[threadId];
728 }
729 }
730 return {
731 draftsByThreadId: nextDraftsByThreadId,
732 draftThreadsByThreadId: nextDraftThreadsByThreadId,
733 projectDraftThreadIdByProjectId: restProjectMappings,
734 };
735 });
736 },
737 clearDraftThread: (threadId) => {
738 if (threadId.length === 0) {
739 return;
740 }
741 set((state) => {
742 const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
743 const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
744 threadId,
745 );
746 if (!hasDraftThread && !hasProjectMapping) {
747 return state;
748 }
749 const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
750 Object.entries(state.projectDraftThreadIdByProjectId).filter(
751 ([, draftThreadId]) => draftThreadId !== threadId,
752 ),
753 ) as Record<ProjectId, ThreadId>;
754 const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
755 state.draftThreadsByThreadId;
756 return {
757 draftThreadsByThreadId: restDraftThreadsByThreadId,
758 projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
759 };
760 });
761 },
762 setPrompt: (threadId, prompt) => {
763 if (threadId.length === 0) {
764 return;
765 }
766 set((state) => {
767 const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
768 const nextDraft: ComposerThreadDraftState = {
769 ...existing,
770 prompt,
771 };
772 const nextDraftsByThreadId = { ...state.draftsByThreadId };
773 if (shouldRemoveDraft(nextDraft)) {
774 delete nextDraftsByThreadId[threadId];
775 } else {
776 nextDraftsByThreadId[threadId] = nextDraft;
777 }
778 return { draftsByThreadId: nextDraftsByThreadId };
779 });
780 },
781 setProvider: (threadId, provider) => {
782 if (threadId.length === 0) {
783 return;
784 }
785 const normalizedProvider = normalizeProviderKind(provider);
786 set((state) => {
787 const existing = state.draftsByThreadId[threadId];
788 if (!existing && normalizedProvider === null) {
789 return state;
790 }
791 const base = existing ?? createEmptyThreadDraft();
792 if (base.provider === normalizedProvider) {
793 return state;
794 }
795 const nextDraft: ComposerThreadDraftState = {
796 ...base,
797 provider: normalizedProvider,
798 };
799 const nextDraftsByThreadId = { ...state.draftsByThreadId };
800 if (shouldRemoveDraft(nextDraft)) {
801 delete nextDraftsByThreadId[threadId];
802 } else {
803 nextDraftsByThreadId[threadId] = nextDraft;
804 }
805 return { draftsByThreadId: nextDraftsByThreadId };
806 });
807 },
808 setModel: (threadId, model) => {
809 if (threadId.length === 0) {
810 return;
811 }
812 const normalizedModel = normalizeModelSlug(model) ?? null;
813 set((state) => {
814 const existing = state.draftsByThreadId[threadId];
815 if (!existing && normalizedModel === null) {
816 return state;
817 }
818 const base = existing ?? createEmptyThreadDraft();
819 if (base.model === normalizedModel) {
820 return state;
821 }
822 const nextDraft: ComposerThreadDraftState = {
823 ...base,
824 model: normalizedModel,
825 };
826 const nextDraftsByThreadId = { ...state.draftsByThreadId };
827 if (shouldRemoveDraft(nextDraft)) {
828 delete nextDraftsByThreadId[threadId];
829 } else {
830 nextDraftsByThreadId[threadId] = nextDraft;
831 }
832 return { draftsByThreadId: nextDraftsByThreadId };
833 });
834 },
835 setRuntimeMode: (threadId, runtimeMode) => {
836 if (threadId.length === 0) {
837 return;
838 }
839 const nextRuntimeMode =
840 runtimeMode === "approval-required" || runtimeMode === "full-access" ? runtimeMode : null;
841 set((state) => {
842 const existing = state.draftsByThreadId[threadId];
843 if (!existing && nextRuntimeMode === null) {
844 return state;
845 }
846 const base = existing ?? createEmptyThreadDraft();
847 if (base.runtimeMode === nextRuntimeMode) {
848 return state;
849 }
850 const nextDraft: ComposerThreadDraftState = {
851 ...base,
852 runtimeMode: nextRuntimeMode,
853 };
854 const nextDraftsByThreadId = { ...state.draftsByThreadId };
855 if (shouldRemoveDraft(nextDraft)) {
856 delete nextDraftsByThreadId[threadId];
857 } else {
858 nextDraftsByThreadId[threadId] = nextDraft;
859 }
860 return { draftsByThreadId: nextDraftsByThreadId };
861 });
862 },
863 setInteractionMode: (threadId, interactionMode) => {
864 if (threadId.length === 0) {
865 return;
866 }
867 const nextInteractionMode =
868 interactionMode === "plan" || interactionMode === "default" ? interactionMode : null;
869 set((state) => {
870 const existing = state.draftsByThreadId[threadId];
871 if (!existing && nextInteractionMode === null) {
872 return state;
873 }
874 const base = existing ?? createEmptyThreadDraft();
875 if (base.interactionMode === nextInteractionMode) {
876 return state;
877 }
878 const nextDraft: ComposerThreadDraftState = {
879 ...base,
880 interactionMode: nextInteractionMode,
881 };
882 const nextDraftsByThreadId = { ...state.draftsByThreadId };
883 if (shouldRemoveDraft(nextDraft)) {
884 delete nextDraftsByThreadId[threadId];
885 } else {
886 nextDraftsByThreadId[threadId] = nextDraft;
887 }
888 return { draftsByThreadId: nextDraftsByThreadId };
889 });
890 },
891 setEffort: (threadId, effort) => {
892 if (threadId.length === 0) {
893 return;
894 }
895 const nextEffort =
896 effort &&
897 REASONING_EFFORT_VALUES.has(effort) &&
898 effort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex
899 ? effort
900 : null;
901 set((state) => {
902 const existing = state.draftsByThreadId[threadId];
903 if (!existing && nextEffort === null) {
904 return state;
905 }
906 const base = existing ?? createEmptyThreadDraft();
907 if (base.effort === nextEffort) {
908 return state;
909 }
910 const nextDraft: ComposerThreadDraftState = {
911 ...base,
912 effort: nextEffort,
913 };
914 const nextDraftsByThreadId = { ...state.draftsByThreadId };
915 if (shouldRemoveDraft(nextDraft)) {
916 delete nextDraftsByThreadId[threadId];
917 } else {
918 nextDraftsByThreadId[threadId] = nextDraft;
919 }
920 return { draftsByThreadId: nextDraftsByThreadId };
921 });
922 },
923 setCodexFastMode: (threadId, enabled) => {
924 if (threadId.length === 0) {
925 return;
926 }
927 const nextCodexFastMode = enabled === true;
928 set((state) => {
929 const existing = state.draftsByThreadId[threadId];
930 if (!existing && nextCodexFastMode === false) {
931 return state;
932 }
933 const base = existing ?? createEmptyThreadDraft();
934 if (base.codexFastMode === nextCodexFastMode) {
935 return state;
936 }
937 const nextDraft: ComposerThreadDraftState = {
938 ...base,
939 codexFastMode: nextCodexFastMode,
940 };
941 const nextDraftsByThreadId = { ...state.draftsByThreadId };
942 if (shouldRemoveDraft(nextDraft)) {
943 delete nextDraftsByThreadId[threadId];
944 } else {
945 nextDraftsByThreadId[threadId] = nextDraft;
946 }
947 return { draftsByThreadId: nextDraftsByThreadId };
948 });
949 },
950 addImage: (threadId, image) => {
951 if (threadId.length === 0) {
952 return;
953 }
954 get().addImages(threadId, [image]);
955 },
956 addImages: (threadId, images) => {
957 if (threadId.length === 0 || images.length === 0) {
958 return;
959 }
960 set((state) => {
961 const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
962 const existingIds = new Set(existing.images.map((image) => image.id));
963 const existingDedupKeys = new Set(
964 existing.images.map((image) => composerImageDedupKey(image)),
965 );
966 const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
967 const dedupedIncoming: ComposerImageAttachment[] = [];
968 for (const image of images) {
969 const dedupKey = composerImageDedupKey(image);
970 if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) {
971 // Avoid revoking a blob URL that's still referenced by an accepted image.
972 if (!acceptedPreviewUrls.has(image.previewUrl)) {
973 revokeObjectPreviewUrl(image.previewUrl);
974 }
975 continue;
976 }
977 dedupedIncoming.push(image);
978 existingIds.add(image.id);
979 existingDedupKeys.add(dedupKey);
980 acceptedPreviewUrls.add(image.previewUrl);
981 }
982 if (dedupedIncoming.length === 0) {
983 return state;
984 }
985 return {
986 draftsByThreadId: {
987 ...state.draftsByThreadId,
988 [threadId]: {
989 ...existing,
990 images: [...existing.images, ...dedupedIncoming],
991 },
992 },
993 };
994 });
995 },
996 removeImage: (threadId, imageId) => {
997 if (threadId.length === 0) {
998 return;
999 }
1000 const existing = get().draftsByThreadId[threadId];
1001 if (!existing) {
1002 return;
1003 }
1004 const removedImage = existing.images.find((image) => image.id === imageId);
1005 if (removedImage) {
1006 revokeObjectPreviewUrl(removedImage.previewUrl);
1007 }
1008 set((state) => {
1009 const current = state.draftsByThreadId[threadId];
1010 if (!current) {
1011 return state;
1012 }
1013 const nextDraft: ComposerThreadDraftState = {
1014 ...current,
1015 images: current.images.filter((image) => image.id !== imageId),
1016 nonPersistedImageIds: current.nonPersistedImageIds.filter((id) => id !== imageId),
1017 persistedAttachments: current.persistedAttachments.filter(
1018 (attachment) => attachment.id !== imageId,
1019 ),
1020 };
1021 const nextDraftsByThreadId = { ...state.draftsByThreadId };
1022 if (shouldRemoveDraft(nextDraft)) {
1023 delete nextDraftsByThreadId[threadId];
1024 } else {
1025 nextDraftsByThreadId[threadId] = nextDraft;
1026 }
1027 return { draftsByThreadId: nextDraftsByThreadId };
1028 });
1029 },
1030 clearPersistedAttachments: (threadId) => {
1031 if (threadId.length === 0) {
1032 return;
1033 }
1034 set((state) => {
1035 const current = state.draftsByThreadId[threadId];
1036 if (!current) {
1037 return state;
1038 }
1039 const nextDraft: ComposerThreadDraftState = {
1040 ...current,
1041 persistedAttachments: [],
1042 nonPersistedImageIds: [],
1043 };
1044 const nextDraftsByThreadId = { ...state.draftsByThreadId };
1045 if (shouldRemoveDraft(nextDraft)) {
1046 delete nextDraftsByThreadId[threadId];
1047 } else {
1048 nextDraftsByThreadId[threadId] = nextDraft;
1049 }
1050 return { draftsByThreadId: nextDraftsByThreadId };
1051 });
1052 },
1053 syncPersistedAttachments: (threadId, attachments) => {
1054 if (threadId.length === 0) {
1055 return;
1056 }
1057 const attachmentIdSet = new Set(attachments.map((attachment) => attachment.id));
1058 set((state) => {
1059 const current = state.draftsByThreadId[threadId];
1060 if (!current) {
1061 return state;
1062 }
1063 const nextDraft: ComposerThreadDraftState = {
1064 ...current,
1065 // Stage attempted attachments so persist middleware can try writing them.
1066 persistedAttachments: attachments,
1067 nonPersistedImageIds: current.nonPersistedImageIds.filter(
1068 (id) => !attachmentIdSet.has(id),
1069 ),
1070 };
1071 const nextDraftsByThreadId = { ...state.draftsByThreadId };
1072 if (shouldRemoveDraft(nextDraft)) {
1073 delete nextDraftsByThreadId[threadId];
1074 } else {
1075 nextDraftsByThreadId[threadId] = nextDraft;
1076 }
1077 return { draftsByThreadId: nextDraftsByThreadId };
1078 });
1079 Promise.resolve().then(() => {
1080 const persistedIdSet = new Set(readPersistedAttachmentIdsFromStorage(threadId));
1081 set((state) => {
1082 const current = state.draftsByThreadId[threadId];
1083 if (!current) {
1084 return state;
1085 }
1086 const imageIdSet = new Set(current.images.map((image) => image.id));
1087 const persistedAttachments = attachments.filter(
1088 (attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
1089 );
1090 const nonPersistedImageIds = current.images
1091 .map((image) => image.id)
1092 .filter((imageId) => !persistedIdSet.has(imageId));
1093 const nextDraft: ComposerThreadDraftState = {
1094 ...current,
1095 persistedAttachments,
1096 nonPersistedImageIds,
1097 };
1098 const nextDraftsByThreadId = { ...state.draftsByThreadId };
1099 if (shouldRemoveDraft(nextDraft)) {
1100 delete nextDraftsByThreadId[threadId];
1101 } else {
1102 nextDraftsByThreadId[threadId] = nextDraft;
1103 }
1104 return { draftsByThreadId: nextDraftsByThreadId };
1105 });
1106 });
1107 },
1108 clearComposerContent: (threadId) => {
1109 if (threadId.length === 0) {
1110 return;
1111 }
1112 set((state) => {
1113 const current = state.draftsByThreadId[threadId];
1114 if (!current) {
1115 return state;
1116 }
1117 const nextDraft: ComposerThreadDraftState = {
1118 ...current,
1119 prompt: "",
1120 images: [],
1121 nonPersistedImageIds: [],
1122 persistedAttachments: [],
1123 };
1124 const nextDraftsByThreadId = { ...state.draftsByThreadId };
1125 if (shouldRemoveDraft(nextDraft)) {
1126 delete nextDraftsByThreadId[threadId];
1127 } else {
1128 nextDraftsByThreadId[threadId] = nextDraft;
1129 }
1130 return { draftsByThreadId: nextDraftsByThreadId };
1131 });
1132 },
1133 clearThreadDraft: (threadId) => {
1134 if (threadId.length === 0) {
1135 return;
1136 }
1137 const existing = get().draftsByThreadId[threadId];
1138 if (existing) {
1139 for (const image of existing.images) {
1140 revokeObjectPreviewUrl(image.previewUrl);
1141 }
1142 }
1143 set((state) => {
1144 const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined;
1145 const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
1146 const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
1147 threadId,
1148 );
1149 if (!hasComposerDraft && !hasDraftThread && !hasProjectMapping) {
1150 return state;
1151 }
1152 const { [threadId]: _removedComposerDraft, ...restComposerDraftsByThreadId } =
1153 state.draftsByThreadId;
1154 const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
1155 state.draftThreadsByThreadId;
1156 const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
1157 Object.entries(state.projectDraftThreadIdByProjectId).filter(
1158 ([, draftThreadId]) => draftThreadId !== threadId,
1159 ),
1160 ) as Record<ProjectId, ThreadId>;
1161 return {
1162 draftsByThreadId: restComposerDraftsByThreadId,
1163 draftThreadsByThreadId: restDraftThreadsByThreadId,
1164 projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
1165 };
1166 });
1167 },
1168 }),
1169 {
1170 name: COMPOSER_DRAFT_STORAGE_KEY,
1171 version: 1,
1172 storage: createJSONStorage(() => localStorage),
1173 partialize: (state) => {
1174 const persistedDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
1175 for (const [threadId, draft] of Object.entries(state.draftsByThreadId)) {
1176 if (typeof threadId !== "string" || threadId.length === 0) {
1177 continue;
1178 }
1179 if (
1180 draft.prompt.length === 0 &&
1181 draft.persistedAttachments.length === 0 &&
1182 draft.provider === null &&
1183 draft.model === null &&
1184 draft.runtimeMode === null &&
1185 draft.interactionMode === null &&
1186 draft.effort === null &&
1187 draft.codexFastMode === false
1188 ) {
1189 continue;
1190 }
1191 const persistedDraft: PersistedComposerThreadDraftState = {
1192 prompt: draft.prompt,
1193 attachments: draft.persistedAttachments,
1194 };
1195 if (draft.model) {
1196 persistedDraft.model = draft.model;
1197 }
1198 if (draft.provider) {
1199 persistedDraft.provider = draft.provider;
1200 }
1201 if (draft.runtimeMode) {
1202 persistedDraft.runtimeMode = draft.runtimeMode;
1203 }
1204 if (draft.interactionMode) {
1205 persistedDraft.interactionMode = draft.interactionMode;
1206 }
1207 if (draft.effort) {
1208 persistedDraft.effort = draft.effort;
1209 }
1210 if (draft.codexFastMode) {
1211 persistedDraft.codexFastMode = true;
1212 }
1213 persistedDraftsByThreadId[threadId as ThreadId] = persistedDraft;
1214 }
1215 return {
1216 draftsByThreadId: persistedDraftsByThreadId,
1217 draftThreadsByThreadId: state.draftThreadsByThreadId,
1218 projectDraftThreadIdByProjectId: state.projectDraftThreadIdByProjectId,
1219 };
1220 },
1221 merge: (persistedState, currentState) => {
1222 const normalizedPersisted = normalizePersistedComposerDraftState(persistedState);
1223 const draftsByThreadId = Object.fromEntries(
1224 Object.entries(normalizedPersisted.draftsByThreadId).map(([threadId, draft]) => [
1225 threadId,
1226 toHydratedThreadDraft(draft),
1227 ]),
1228 );
1229 return {
1230 ...currentState,
1231 draftsByThreadId,
1232 draftThreadsByThreadId: normalizedPersisted.draftThreadsByThreadId,
1233 projectDraftThreadIdByProjectId: normalizedPersisted.projectDraftThreadIdByProjectId,
1234 };
1235 },
1236 },
1237 ),
1238);
1239
1240export function useComposerThreadDraft(threadId: ThreadId): ComposerThreadDraftState {
1241 return useComposerDraftStore((state) => state.draftsByThreadId[threadId] ?? EMPTY_THREAD_DRAFT);
1242}