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

useComposerStash.ts

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