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