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