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

useComposerStash.ts

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