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

useComposerStash.ts

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