Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerStash.ts

714 lines27.7 KB

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