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