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