Open History to see the last commit
1import type { ChatComposerProps } from "./ChatComposer";
2import {
3 type ComposerContextRecord,
4 type EnvironmentId,
5 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6 type PreviewAnnotationPayload,
7 type ThreadContextRecord,
8} from "@t3tools/contracts";
9import {
10 type ComposerFileAttachment,
11 type PersistedComposerFileAttachment,
12 type PersistedComposerImageAttachment,
13 composerFileDedupKey,
14 composerFileMatchesReattachMarker,
15 composerFileNeedsReattach,
16 composerTargetKey,
17 hydrateImagesFromPersisted,
18 useComposerDraftStore,
19} from "../../composerDraftStore";
20import { type ComposerPromptEditorHandle } from "../ComposerPromptEditor";
21import {
22 MAX_STASH_ENTRIES,
23 type PromptStashEntry,
24 partitionStashAttachments,
25 usePromptStashStore,
26} from "../../promptStashStore";
27import { type PendingUserInput } from "../../session-logic";
28import { type ReviewCommentContext } from "../../reviewCommentContext";
29import { collapseExpandedComposerCursor } from "../../composer-logic";
30import { compressImageForStash } from "../../lib/imageCompression";
31import { formatInlineContextReference } from "~/lib/composerContextReferences";
32import { getTerminalFocusOwner } from "../../lib/terminalFocus";
33import { isCommandPaletteOpen } from "../../commandPaletteBus";
34import { pendingDraftWork } from "./pendingDraftWork";
35import {
36 previewAnnotationContextRecord,
37 reviewCommentContextRecord,
38 terminalContextRecord,
39} from "~/lib/composerContextRecords";
40import { randomUUID } from "~/lib/utils";
41import {
42 readAttachmentUpload,
43 releaseAttachmentUpload,
44 releasePersistedAttachmentUpload,
45 verifyStashedAttachmentUpload,
46} from "../../lib/attachmentUploadQueue";
47import { remainingComposerAttachmentSlots } from "./composerThreadImport";
48import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
49import { resizeSnapShotSource } from "../../lib/snapShotSource";
50import { resolveShortcutCommand } from "../../keybindings";
51import { toastManager } from "../ui/toast";
52import type { useComposerTriggerState } from "./useComposerTriggerState";
53import {
54 type Dispatch,
55 type RefObject,
56 type SetStateAction,
57 use,
58 useEffect,
59 useRef,
60 useState,
61} from "react";
62import { BackgroundThreadContext } from "./backgroundThread";
63import { useStableCallback } from "../../hooks/useStableCallback";
64
65/**
66 * The prompt stash: saving the draft aside, restoring or deleting an entry, the badge pulse,
67 * and the stash shortcut. Its state lives here so the composer body only wires it up.
68 */
69export function useComposerStash(input: {
70 readonly environmentId: EnvironmentId;
71 readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"];
72 readonly promptRef: ChatComposerProps["promptRef"];
73 readonly composerImagesRef: ChatComposerProps["composerImagesRef"];
74 readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
75 readonly composerTerminalContextsRef: ChatComposerProps["composerTerminalContextsRef"];
76 readonly keybindings: ChatComposerProps["keybindings"];
77 readonly terminalOpen: boolean;
78 readonly projectSelectionRequired: boolean;
79 readonly isRevertingCheckpoint: boolean;
80 readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
81 readonly activePendingProgress: ChatComposerProps["activePendingProgress"];
82 readonly prompt: string;
83 readonly composerMenuOpen: boolean;
84 readonly isComposerModelPickerOpen: boolean;
85 readonly isComposerCollapsedMobile: boolean;
86 readonly composerPreviewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
87 readonly composerReviewComments: ReadonlyArray<ReviewCommentContext>;
88 readonly composerThreadContexts: ReadonlyArray<ThreadContextRecord>;
89 readonly attachmentTargetKeyRef: RefObject<string>;
90 readonly composerDraftTargetKeyRef: RefObject<string>;
91 readonly composerEditorRef: RefObject<ComposerPromptEditorHandle | null>;
92 readonly isRevertingCheckpointRef: RefObject<boolean>;
93 readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
94 readonly setComposerCursor: Dispatch<SetStateAction<number>>;
95 readonly setComposerTrigger: ReturnType<typeof useComposerTriggerState>["setTrigger"];
96 readonly importContextRecords: (
97 records: ReadonlyArray<ComposerContextRecord>,
98 sourceEnvironmentId: EnvironmentId | null,
99 threadDraftTarget?: ChatComposerProps["composerDraftTarget"],
100 ) => ReadonlyMap<string, string>;
101 readonly expandMobileComposer: () => void;
102}) {
103 const {
104 environmentId,
105 composerDraftTarget,
106 promptRef,
107 composerImagesRef,
108 composerFilesRef,
109 composerTerminalContextsRef,
110 keybindings,
111 terminalOpen,
112 projectSelectionRequired,
113 isRevertingCheckpoint,
114 pendingUserInputs,
115 activePendingProgress,
116 prompt,
117 composerMenuOpen,
118 isComposerModelPickerOpen,
119 isComposerCollapsedMobile,
120 composerPreviewAnnotations,
121 composerReviewComments,
122 composerThreadContexts,
123 attachmentTargetKeyRef,
124 composerDraftTargetKeyRef,
125 composerEditorRef,
126 isRevertingCheckpointRef,
127 pendingThreadImportsRef,
128 setComposerCursor,
129 setComposerTrigger,
130 importContextRecords,
131 expandMobileComposer,
132 } = input;
133 const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
134 const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
135 const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
136 const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);
137 const removeComposerDraftPreviewAnnotation = useComposerDraftStore(
138 (store) => store.removePreviewAnnotation,
139 );
140 const removeComposerDraftReviewComment = useComposerDraftStore(
141 (store) => store.removeReviewComment,
142 );
143 const clearComposerDraftTerminalContexts = useComposerDraftStore(
144 (store) => store.clearTerminalContexts,
145 );
146 const clearComposerDraftPromptAndImages = useComposerDraftStore(
147 (store) => store.clearComposerPromptAndImages,
148 );
149 const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
150 const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
151 const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
152 key: 0,
153 active: false,
154 });
155 const stashPulseKeyRef = useRef(0);
156 const stashPulseTimeoutRef = useRef<number | null>(null);
157 const stashInFlightRef = useRef<Set<string>>(new Set());
158
159 const stashQueue = usePromptStashStore((state) => state.entries);
160 const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
161 const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
162 const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
163
164 useEffect(() => {
165 return () => {
166 if (stashPulseTimeoutRef.current !== null) {
167 window.clearTimeout(stashPulseTimeoutRef.current);
168 }
169 };
170 }, []);
171
172 const pulseStashBadge = () => {
173 stashPulseKeyRef.current += 1;
174 setStashPulse({ key: stashPulseKeyRef.current, active: true });
175 if (stashPulseTimeoutRef.current !== null) {
176 window.clearTimeout(stashPulseTimeoutRef.current);
177 }
178 stashPulseTimeoutRef.current = window.setTimeout(() => {
179 stashPulseTimeoutRef.current = null;
180 setStashPulse((current) => ({ ...current, active: false }));
181 }, 1200);
182 };
183
184 const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
185 const filesToVerify = menuEntry.files ?? [];
186 if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
187 toastManager.add({
188 type: "error",
189 title: "Stashed files belong to another environment",
190 description: "Restore this prompt in the environment that received its files.",
191 });
192 return;
193 }
194 setIsStashMenuOpen(false);
195
196 // An expired upload restores as a needs-reattach row instead of a reference
197 // the next send would fail to verify. Verify BEFORE taking: the take
198 // removes the entry from durable storage, and a tab closed during this
199 // await must still find it there after reload.
200 const verifications = await Promise.all(
201 filesToVerify.map((file) =>
202 verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }),
203 ),
204 );
205 const expiredAttachmentIds = new Set(
206 filesToVerify
207 .filter((_, index) => verifications[index]?.status === "missing")
208 .map((file) => file.attachmentId),
209 );
210
211 // A thread switch during the verify await would mix the new thread's
212 // prompt with this invocation's captured target. Nothing was taken yet,
213 // so abort and leave the entry restorable where the user now is.
214 if (
215 isRevertingCheckpointRef.current ||
216 composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
217 ) {
218 return;
219 }
220
221 const { entry, durable } = takeStashEntry(menuEntry.id);
222 if (!entry) return;
223 if (!durable) {
224 toastManager.add({
225 type: "warning",
226 title: "Restored prompt may reappear in the stash",
227 description:
228 "Browser storage rejected the update, so this entry could still be there after a reload.",
229 data: { hideCopyButton: true },
230 });
231 }
232
233 const rewrittenContextIds = entry.records
234 ? importContextRecords(entry.records, null, composerDraftTarget)
235 : new Map<string, string>();
236 const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => {
237 const contextId = rewrittenContextIds.get(reference.contextId);
238 return contextId
239 ? formatInlineContextReference({
240 ...reference,
241 contextId,
242 kind: reference.kind === "element" ? "preview-annotation" : reference.kind,
243 })
244 : reference.source;
245 });
246 const currentPrompt = promptRef.current;
247 const nextPrompt =
248 restoredPrompt.length === 0
249 ? currentPrompt
250 : currentPrompt.trim().length
251 ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}`
252 : restoredPrompt;
253 let promptChanged = nextPrompt !== currentPrompt;
254 if (promptChanged) {
255 promptRef.current = nextPrompt;
256 setComposerDraftPrompt(composerDraftTarget, nextPrompt);
257 setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
258 setComposerTrigger(null);
259 }
260
261 let unrestoredFileNames: string[] = [];
262 const expiredFileNames: string[] = [];
263 let restoredFileCount = 0;
264 const stashedFiles = entry.files ?? [];
265 if (stashedFiles.length > 0) {
266 const composerFilesNow = composerFilesRef.current;
267 const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
268 const retainedUploadIds = new Set(
269 composerFilesNow.flatMap((file) =>
270 file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
271 ),
272 );
273 const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey));
274 const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach);
275 const restoredMarkerIds = new Set<string>();
276 const duplicateFiles: PersistedComposerFileAttachment[] = [];
277 const markerReplacements: ComposerFileAttachment[] = [];
278 const appendedFiles: ComposerFileAttachment[] = [];
279 for (const file of stashedFiles) {
280 const expired = expiredAttachmentIds.has(file.attachmentId);
281 const key = composerFileDedupKey(file);
282 const restored: ComposerFileAttachment = {
283 type: "file",
284 id: file.id,
285 name: file.name,
286 mimeType: file.mimeType,
287 sizeBytes: file.sizeBytes,
288 file: null,
289 ...(file.source ? { source: file.source } : {}),
290 ...(expired
291 ? {}
292 : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }),
293 };
294 if (existingFileIds.has(file.id)) {
295 if (!expired && !retainedUploadIds.has(file.attachmentId)) {
296 duplicateFiles.push(file);
297 }
298 continue;
299 }
300 const reattachMarker = reattachMarkers.find(
301 (marker) =>
302 !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file),
303 );
304 if (reattachMarker) {
305 restoredMarkerIds.add(reattachMarker.id);
306 existingFileIds.add(file.id);
307 existingFileKeys.add(key);
308 if (expired) {
309 expiredFileNames.push(file.name);
310 } else {
311 retainedUploadIds.add(file.attachmentId);
312 markerReplacements.push(restored);
313 }
314 continue;
315 }
316 if (existingFileKeys.has(key)) {
317 if (!expired && !retainedUploadIds.has(file.attachmentId)) {
318 duplicateFiles.push(file);
319 }
320 continue;
321 }
322 existingFileIds.add(file.id);
323 existingFileKeys.add(key);
324 if (expired) {
325 expiredFileNames.push(file.name);
326 } else {
327 retainedUploadIds.add(file.attachmentId);
328 }
329 appendedFiles.push(restored);
330 }
331 const capacity = remainingComposerAttachmentSlots(
332 composerImagesRef.current.length + composerFilesNow.length,
333 pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
334 );
335 const filesToAppend = appendedFiles.slice(0, capacity);
336 const skippedFiles = appendedFiles.slice(capacity);
337 unrestoredFileNames = skippedFiles.map((file) => file.name);
338 // A non-durable take can resurrect the stash entry after a reload;
339 // deleting these uploads would leave it pointing at nothing.
340 if (durable) {
341 for (const file of duplicateFiles) {
342 releasePersistedAttachmentUpload({
343 id: file.id,
344 environmentId,
345 attachmentId: file.attachmentId,
346 });
347 }
348 for (const file of skippedFiles) {
349 if (file.uploadedAttachmentId) {
350 releasePersistedAttachmentUpload({
351 id: file.id,
352 environmentId,
353 attachmentId: file.uploadedAttachmentId,
354 });
355 }
356 }
357 }
358 const restoredFiles = [...markerReplacements, ...filesToAppend];
359 if (restoredFiles.length > 0) {
360 addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true });
361 const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt;
362 if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) {
363 promptRef.current = restoredFilePrompt;
364 setComposerCursor(
365 collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length),
366 );
367 setComposerTrigger(null);
368 promptChanged = true;
369 }
370 restoredFileCount = filesToAppend.length;
371 }
372 }
373
374 let unrestoredImageNames: string[] = [];
375 if (entry.attachments.length > 0) {
376 const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
377 // The draft store also dedupes by mimeType+sizeBytes+name, so filter
378 // on the same key here. Counting a duplicate against capacity would
379 // burn a slot the store then refuses to fill, pushing a genuinely
380 // unique image into the overflow list for nothing.
381 const existingDedupKeys = new Set(
382 composerImagesRef.current.map(
383 (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
384 ),
385 );
386 const capacity = remainingComposerAttachmentSlots(
387 composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
388 pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
389 );
390 const pending = entry.attachments.filter(
391 (attachment) =>
392 !existingIds.has(attachment.id) &&
393 !existingDedupKeys.has(
394 `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`,
395 ),
396 );
397 unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name);
398 const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity));
399 if (restoredImages.length > 0) {
400 addComposerDraftImages(composerDraftTarget, restoredImages);
401 }
402 }
403
404 const missingImageReasons: string[] = [];
405 if (entry.droppedImageNames.length > 0) {
406 missingImageReasons.push(
407 `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
408 );
409 }
410 if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
411 missingImageReasons.push(
412 `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
413 );
414 }
415 if (unrestoredImageNames.length > 0) {
416 missingImageReasons.push(
417 `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
418 );
419 }
420 if (unrestoredFileNames.length > 0) {
421 missingImageReasons.push(
422 `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
423 );
424 }
425 if (expiredFileNames.length > 0) {
426 missingImageReasons.push(
427 `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`,
428 );
429 }
430 if (missingImageReasons.length > 0) {
431 toastManager.add({
432 type: "warning",
433 title: "Some attachments were not restored",
434 description: missingImageReasons.join(" "),
435 });
436 }
437
438 if (promptChanged) {
439 window.requestAnimationFrame(() => {
440 composerEditorRef.current?.focusAtEnd();
441 });
442 }
443 };
444 const restoreStashEntryStable = useStableCallback(restoreStashEntry);
445
446 const deleteStashEntry = (entry: PromptStashEntry) => {
447 const { entry: removed, durable } = takeStashEntry(entry.id);
448 if (!stashQueue.some((candidate) => candidate.id !== entry.id)) {
449 setIsStashMenuOpen(false);
450 }
451 if (durable && removed) {
452 for (const file of removed.files ?? []) {
453 releasePersistedAttachmentUpload({
454 id: file.id,
455 environmentId: file.environmentId,
456 attachmentId: file.attachmentId,
457 });
458 }
459 }
460 if (!durable) {
461 toastManager.add({
462 type: "warning",
463 title: "Stash entry may come back",
464 description:
465 "Browser storage rejected the delete, so this prompt could reappear after a reload.",
466 data: { hideCopyButton: true },
467 });
468 }
469 };
470 const deleteStashEntryStable = useStableCallback(deleteStashEntry);
471
472 const stashCurrentPrompt = async () => {
473 // Stashing clears the draft. A pasted attachment still downloading would then land in the
474 // emptied composer instead of travelling with the entry it belongs to.
475 if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
476 toastManager.add({
477 type: "info",
478 title: "Still bringing attached context into this message.",
479 description: "Stash again once its chip resolves.",
480 });
481 return;
482 }
483 const prompt = promptRef.current.trim();
484 const images = [...composerImagesRef.current];
485 const files = [...composerFilesRef.current];
486 const stashedRecords: ComposerContextRecord[] = [
487 ...composerThreadContexts,
488 ...composerTerminalContextsRef.current.map(terminalContextRecord),
489 ...composerReviewComments.map(reviewCommentContextRecord),
490 ...composerPreviewAnnotations.map((annotation) =>
491 previewAnnotationContextRecord(annotation, {
492 screenshotContextId: images.some((image) => image.id === annotation.id)
493 ? annotation.id
494 : undefined,
495 }),
496 ),
497 ];
498 if (prompt.length === 0 && images.length === 0 && files.length === 0) {
499 const entries = usePromptStashStore.getState().entries;
500 const entry = entries.length === 1 ? entries[0] : undefined;
501 if (entry && !entry.pendingImageCount) {
502 await restoreStashEntry(entry);
503 } else {
504 setIsStashMenuOpen((open) => !open);
505 }
506 return;
507 }
508 const stashedFiles: PersistedComposerFileAttachment[] = [];
509 for (const file of files) {
510 if (composerFileNeedsReattach(file)) {
511 toastManager.add({
512 type: "error",
513 title: "Attach dropped files again or remove them before stashing",
514 });
515 return;
516 }
517 const upload = readAttachmentUpload(file.id);
518 if (upload?.status !== "ready" || upload.environmentId !== environmentId) {
519 toastManager.add({
520 type: "error",
521 title: "Wait for file uploads before stashing this prompt",
522 });
523 return;
524 }
525 stashedFiles.push({
526 id: file.id,
527 name: file.name,
528 mimeType: file.mimeType,
529 sizeBytes: file.sizeBytes,
530 attachmentId: upload.attachmentId,
531 environmentId,
532 ...(file.source ? { source: file.source } : {}),
533 });
534 }
535 // Deduplicate the snapshot while encoding, not all stashes: new drafts or
536 // thread switches must still be able to create their own entries.
537 const attachmentKey = images
538 .map((image) => `image:${image.id}`)
539 .concat(files.map((file) => `file:${file.id}`))
540 .join(",");
541 const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n");
542 if (stashInFlightRef.current.has(snapshotKey)) return;
543 stashInFlightRef.current.add(snapshotKey);
544
545 const stashTarget = composerDraftTarget;
546 const entryId = randomUUID();
547 const stashAndEncode = async () => {
548 // Ordering matters in both directions: writing before clearing means a
549 // crash or closed tab mid-encode still leaves the prompt recoverable,
550 // while clearing before the async image work means edits typed during
551 // encoding are not wiped.
552 const { evicted, written, durable } = stashEntryToQueue({
553 id: entryId,
554 createdAt: new Date().toISOString(),
555 prompt,
556 attachments: [],
557 ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}),
558 droppedImageNames: [],
559 unreadableImageNames: [],
560 pendingImageCount: images.length,
561 ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}),
562 });
563
564 // If it was rejected (quota) the store has already rolled itself back,
565 // so leave the composer untouched rather than making it the second
566 // casualty of a reload.
567 if (!written) {
568 toastManager.add({
569 type: "error",
570 title: "Could not stash this prompt",
571 description:
572 "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
573 data: { hideCopyButton: true },
574 });
575 return;
576 }
577 if (!durable) {
578 toastManager.add({
579 type: "warning",
580 title: "Stashed prompt will not survive a reload",
581 description:
582 "Browser storage is unavailable, so this stash is kept in memory only for this session.",
583 data: { hideCopyButton: true },
584 });
585 }
586
587 promptRef.current = "";
588 clearComposerDraftPromptAndImages(stashTarget);
589 clearComposerDraftTerminalContexts(stashTarget);
590 setComposerDraftThreadContexts(stashTarget, []);
591 for (const comment of composerReviewComments) {
592 removeComposerDraftReviewComment(stashTarget, comment.id);
593 }
594 for (const annotation of composerPreviewAnnotations) {
595 releaseAttachmentUpload(annotation.id);
596 removeComposerDraftPreviewAnnotation(stashTarget, annotation.id);
597 }
598 setComposerDraftPrompt(stashTarget, "");
599 for (const image of images) {
600 releaseAttachmentUpload(image.id);
601 }
602 setComposerCursor(0);
603 setComposerTrigger(null);
604 pulseStashBadge();
605
606 if (evicted) {
607 for (const file of evicted.files ?? []) {
608 releasePersistedAttachmentUpload({
609 id: file.id,
610 environmentId: file.environmentId,
611 attachmentId: file.attachmentId,
612 });
613 }
614 toastManager.add({
615 type: "warning",
616 title: "Oldest stashed prompt discarded",
617 description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
618 data: { hideCopyButton: true },
619 });
620 }
621
622 // Images are re-encoded for the stash rather than stored verbatim: the
623 // composer allows up to 10MB per image, but localStorage gives the whole
624 // origin ~5MB.
625 const candidateAttachments: PersistedComposerImageAttachment[] = [];
626 const oversizedImageNames: string[] = [];
627 const unreadableImageNames: string[] = [];
628 for (const image of images) {
629 const result = await compressImageForStash(image.file);
630 if (!result.ok) {
631 (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push(
632 image.name,
633 );
634 continue;
635 }
636 candidateAttachments.push({
637 id: image.id,
638 name: image.name,
639 mimeType: result.image.mimeType,
640 sizeBytes: result.image.sizeBytes,
641 dataUrl: result.image.dataUrl,
642 ...(image.source
643 ? { source: resizeSnapShotSource(image.source, result.image.imageSize) }
644 : {}),
645 });
646 }
647 const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
648
649 const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
650 attachments: kept,
651 droppedImageNames: [...oversizedImageNames, ...droppedNames],
652 unreadableImageNames,
653 });
654 if (attached) {
655 if (!imagesDurable && durable && images.length > 0) {
656 toastManager.add({
657 type: "warning",
658 title: "Stashed images were not saved",
659 description:
660 "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.",
661 data: { hideCopyButton: true },
662 });
663 }
664 } else if (kept.length > 0) {
665 toastManager.add({
666 type: "warning",
667 title: "Stashed images did not attach",
668 description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`,
669 data: { hideCopyButton: true },
670 });
671 }
672 };
673 await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey));
674 };
675 const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
676
677 const toggleStashMenu = () => {
678 if (isComposerCollapsedMobile) {
679 expandMobileComposer();
680 setIsStashMenuOpen(true);
681 return;
682 }
683 setIsStashMenuOpen((open) => !open);
684 };
685 const toggleStashMenuStable = useStableCallback(toggleStashMenu);
686
687 const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen });
688 if (
689 stashMenuClosesOn.prompt !== prompt ||
690 stashMenuClosesOn.composerMenuOpen !== composerMenuOpen
691 ) {
692 setStashMenuClosesOn({ prompt, composerMenuOpen });
693 if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
694 }
695
696 const backgroundThread = use(BackgroundThreadContext);
697 useEffect(() => {
698 if (backgroundThread) return;
699 const handler = (event: globalThis.KeyboardEvent) => {
700 const command = resolveShortcutCommand(event, keybindings, {
701 context: {
702 terminalFocus: getTerminalFocusOwner() !== null,
703 terminalOpen,
704 modelPickerOpen: isComposerModelPickerOpen,
705 },
706 });
707 if (command !== "composer.stash") return;
708 // Always claim the shortcut so the browser save dialog never opens,
709 // even when the composer is in a state that can't stash.
710 event.preventDefault();
711 event.stopPropagation();
712 if (isCommandPaletteOpen() || isRevertingCheckpoint) {
713 return;
714 }
715 if (pendingUserInputs.length > 0) {
716 setIsStashMenuOpen((open) => !open);
717 return;
718 }
719 if (projectSelectionRequired || activePendingProgress !== null) {
720 return;
721 }
722 void stashCurrentPromptStable();
723 };
724 window.addEventListener("keydown", handler, true);
725 return () => window.removeEventListener("keydown", handler, true);
726 }, [
727 activePendingProgress,
728 backgroundThread,
729 isComposerModelPickerOpen,
730 keybindings,
731 pendingUserInputs.length,
732 projectSelectionRequired,
733 stashCurrentPromptStable,
734 isRevertingCheckpoint,
735 terminalOpen,
736 ]);
737
738 return {
739 stashQueue,
740 isStashMenuOpen,
741 setIsStashMenuOpen,
742 stashPulse,
743 restoreStashEntryStable,
744 deleteStashEntryStable,
745 toggleStashMenuStable,
746 };
747}