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

useComposerStash.ts

742 lines28.2 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 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 // Deduplicate the snapshot while encoding, not all stashes: new drafts or
534 // thread switches must still be able to create their own entries.
535 const attachmentKey = images
536 .map((image) => `image:${image.id}`)
537 .concat(files.map((file) => `file:${file.id}`))
538 .join(",");
539 const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n");
540 if (stashInFlightRef.current.has(snapshotKey)) return;
541 stashInFlightRef.current.add(snapshotKey);
542​
543 const stashTarget = composerDraftTarget;
544 const entryId = randomUUID();
545 const stashAndEncode = async () => {
546 // Ordering matters in both directions: writing before clearing means a
547 // crash or closed tab mid-encode still leaves the prompt recoverable,
548 // while clearing before the async image work means edits typed during
549 // encoding are not wiped.
550 const { evicted, written, durable } = stashEntryToQueue({
551 id: entryId,
552 createdAt: new Date().toISOString(),
553 prompt,
554 attachments: [],
555 ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}),
556 droppedImageNames: [],
557 unreadableImageNames: [],
558 pendingImageCount: images.length,
559 ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}),
560 });
561​
562 // If it was rejected (quota) the store has already rolled itself back,
563 // so leave the composer untouched rather than making it the second
564 // casualty of a reload.
565 if (!written) {
566 toastManager.add({
567 type: "error",
568 title: "Could not stash this prompt",
569 description:
570 "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
571 data: { hideCopyButton: true },
572 });
573 return;
574 }
575 if (!durable) {
576 toastManager.add({
577 type: "warning",
578 title: "Stashed prompt will not survive a reload",
579 description:
580 "Browser storage is unavailable, so this stash is kept in memory only for this session.",
581 data: { hideCopyButton: true },
582 });
583 }
584​
585 promptRef.current = "";
586 clearComposerDraftPromptAndImages(stashTarget);
587 clearComposerDraftTerminalContexts(stashTarget);
588 setComposerDraftThreadContexts(stashTarget, []);
589 for (const comment of composerReviewComments) {
590 removeComposerDraftReviewComment(stashTarget, comment.id);
591 }
592 for (const annotation of composerPreviewAnnotations) {
593 releaseAttachmentUpload(annotation.id);
594 removeComposerDraftPreviewAnnotation(stashTarget, annotation.id);
595 }
596 setComposerDraftPrompt(stashTarget, "");
597 for (const image of images) {
598 releaseAttachmentUpload(image.id);
599 }
600 setComposerCursor(0);
601 setComposerTrigger(null);
602 pulseStashBadge();
603​
604 if (evicted) {
605 for (const file of evicted.files ?? []) {
606 releasePersistedAttachmentUpload({
607 id: file.id,
608 environmentId: file.environmentId,
609 attachmentId: file.attachmentId,
610 });
611 }
612 toastManager.add({
613 type: "warning",
614 title: "Oldest stashed prompt discarded",
615 description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
616 data: { hideCopyButton: true },
617 });
618 }
619​
620 // Images are re-encoded for the stash rather than stored verbatim: the
621 // composer allows up to 10MB per image, but localStorage gives the whole
622 // origin ~5MB.
623 const candidateAttachments: PersistedComposerImageAttachment[] = [];
624 const oversizedImageNames: string[] = [];
625 const unreadableImageNames: string[] = [];
626 for (const image of images) {
627 const result = await compressImageForStash(image.file);
628 if (!result.ok) {
629 (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push(
630 image.name,
631 );
632 continue;
633 }
634 candidateAttachments.push({
635 id: image.id,
636 name: image.name,
637 mimeType: result.image.mimeType,
638 sizeBytes: result.image.sizeBytes,
639 dataUrl: result.image.dataUrl,
640 ...(image.source
641 ? { source: resizeSnapShotSource(image.source, result.image.imageSize) }
642 : {}),
643 });
644 }
645 const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
646​
647 const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
648 attachments: kept,
649 droppedImageNames: [...oversizedImageNames, ...droppedNames],
650 unreadableImageNames,
651 });
652 if (attached) {
653 if (!imagesDurable && durable && images.length > 0) {
654 toastManager.add({
655 type: "warning",
656 title: "Stashed images were not saved",
657 description:
658 "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.",
659 data: { hideCopyButton: true },
660 });
661 }
662 } else if (kept.length > 0) {
663 toastManager.add({
664 type: "warning",
665 title: "Stashed images did not attach",
666 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"}.`,
667 data: { hideCopyButton: true },
668 });
669 }
670 };
671 await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey));
672 };
673 const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
674​
675 const toggleStashMenu = () => {
676 if (isComposerCollapsedMobile) {
677 expandMobileComposer();
678 setIsStashMenuOpen(true);
679 return;
680 }
681 setIsStashMenuOpen((open) => !open);
682 };
683 const toggleStashMenuStable = useStableCallback(toggleStashMenu);
684​
685 const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen });
686 if (
687 stashMenuClosesOn.prompt !== prompt ||
688 stashMenuClosesOn.composerMenuOpen !== composerMenuOpen
689 ) {
690 setStashMenuClosesOn({ prompt, composerMenuOpen });
691 if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
692 }
693​
694 useEffect(() => {
695 const handler = (event: globalThis.KeyboardEvent) => {
696 const command = resolveShortcutCommand(event, keybindings, {
697 context: {
698 terminalFocus: getTerminalFocusOwner() !== null,
699 terminalOpen,
700 modelPickerOpen: isComposerModelPickerOpen,
701 },
702 });
703 if (command !== "composer.stash") return;
704 // Always claim the shortcut so the browser save dialog never opens,
705 // even when the composer is in a state that can't stash.
706 event.preventDefault();
707 event.stopPropagation();
708 if (isCommandPaletteOpen() || isRevertingCheckpoint) {
709 return;
710 }
711 if (pendingUserInputs.length > 0) {
712 setIsStashMenuOpen((open) => !open);
713 return;
714 }
715 if (projectSelectionRequired || activePendingProgress !== null) {
716 return;
717 }
718 void stashCurrentPromptStable();
719 };
720 window.addEventListener("keydown", handler, true);
721 return () => window.removeEventListener("keydown", handler, true);
722 }, [
723 activePendingProgress,
724 isComposerModelPickerOpen,
725 keybindings,
726 pendingUserInputs.length,
727 projectSelectionRequired,
728 stashCurrentPromptStable,
729 isRevertingCheckpoint,
730 terminalOpen,
731 ]);
732​
733 return {
734 stashQueue,
735 isStashMenuOpen,
736 setIsStashMenuOpen,
737 stashPulse,
738 restoreStashEntryStable,
739 deleteStashEntryStable,
740 toggleStashMenuStable,
741 };