The best way to control Claude Code, Codex and more from any computer or phone

main
ts 818 lines 31.6 KB
Raw
1 import { msg } from "gt-react";
2 import { m } from "~/i18n/messages";
3 import type { ChatComposerProps } from "./ChatComposer";
4 import {
5 type ComposerContextRecord,
6 type EnvironmentId,
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 type PreviewAnnotationPayload,
9 type ThreadContextRecord,
10 } from "@t3tools/contracts";
11 import {
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";
23 import { type ComposerPromptEditorHandle } from "../ComposerPromptEditorTiptap";
24 import {
25 MAX_STASH_ENTRIES,
26 type PromptStashEntry,
27 partitionStashAttachments,
28 usePromptStashStore,
29 } from "../../promptStashStore";
30 import type { PendingUserInputProgress } from "../../pendingUserInput";
31 import { type PendingUserInput } from "../../session-logic";
32 import { type ReviewCommentContext } from "../../reviewCommentContext";
33 import { collapseExpandedComposerCursor } from "../../composer-logic";
34 import { collectComposerPromptInlineTokens } from "../../composer-editor-mentions";
35 import { compressImageForStash } from "../../lib/imageCompression";
36 import { formatInlineContextReference } from "~/lib/composerContextReferences";
37 import { isCommandPaletteOpen } from "../../commandPaletteBus";
38 import { pendingDraftWork } from "./pendingDraftWork";
39 import { countPreparingComposerImages } from "./preparingComposerImages";
40 import {
41 isResponseContextRecord,
42 previewAnnotationContextRecord,
43 reviewCommentContextRecord,
44 terminalContextRecord,
45 } from "~/lib/composerContextRecords";
46 import { randomUUID } from "~/lib/utils";
47 import {
48 readAttachmentUpload,
49 releaseAttachmentUpload,
50 releasePersistedAttachmentUpload,
51 verifyStashedAttachmentUpload,
52 } from "../../lib/attachmentUploadQueue";
53 import { remainingComposerAttachmentSlots } from "./composerThreadImport";
54 import { composerImageDedupKey } from "./composerAttachmentFiles";
55 import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
56 import { resizeSnapShotSource } from "../../lib/snapShotSource";
57 import { registerCommands } from "../../shortcuts/dispatcher";
58 import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";
59 import { toastManager } from "../ui/toast";
60 import type { useComposerTriggerState } from "./useComposerTriggerState";
61 import {
62 type Dispatch,
63 type RefObject,
64 type SetStateAction,
65 use,
66 useEffect,
67 useRef,
68 useState,
69 } from "react";
70 import { BackgroundThreadContext } from "./backgroundThread";
71 import { isInSideChatPane } from "../../lib/sideChatPane";
72 import { 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 */
78 export 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 { evicted, 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 // If it was rejected (quota) the store has already rolled itself back,
619 // so leave the composer untouched rather than making it the second
620 // casualty of a reload.
621 if (!written) {
622 toastManager.add({
623 type: "error",
624 title: m(msg("Could not stash this prompt")),
625 description: m(
626 msg(
627 "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
628 ),
629 ),
630 data: { hideCopyButton: true },
631 });
632 return;
633 }
634 if (!durable) {
635 toastManager.add({
636 type: "warning",
637 title: m(msg("Stashed prompt will not survive a reload")),
638 description: m(
639 msg(
640 "Browser storage is unavailable, so this stash is kept in memory only for this session.",
641 ),
642 ),
643 data: { hideCopyButton: true },
644 });
645 }
646
647 promptRef.current = "";
648 clearComposerDraftPromptAndImages(stashTarget);
649 clearComposerDraftTerminalContexts(stashTarget);
650 setComposerDraftThreadContexts(stashTarget, []);
651 setComposerDraftEnvironmentContexts(stashTarget, []);
652 setComposerDraftReplyTo(stashTarget, null);
653 for (const comment of composerReviewComments) {
654 removeComposerDraftReviewComment(stashTarget, comment.id);
655 }
656 for (const annotation of composerPreviewAnnotations) {
657 releaseAttachmentUpload(annotation.id);
658 removeComposerDraftPreviewAnnotation(stashTarget, annotation.id);
659 }
660 setComposerDraftPrompt(stashTarget, "");
661 for (const image of images) {
662 releaseAttachmentUpload(image.id);
663 }
664 setComposerCursor(0);
665 setComposerTrigger(null);
666 pulseStashBadge();
667
668 if (evicted) {
669 for (const file of evicted.files ?? []) {
670 releasePersistedAttachmentUpload({
671 id: file.id,
672 environmentId: file.environmentId,
673 attachmentId: file.attachmentId,
674 });
675 }
676 toastManager.add({
677 type: "warning",
678 title: m(msg("Oldest stashed prompt discarded")),
679 description: m(
680 msg("The stash holds {max} prompts; the oldest was removed to make room.", {
681 max: MAX_STASH_ENTRIES,
682 }),
683 ),
684 data: { hideCopyButton: true },
685 });
686 }
687
688 // Images are re-encoded for the stash rather than stored verbatim: the
689 // composer allows up to 10MB per image, but localStorage gives the whole
690 // origin ~5MB.
691 const candidateAttachments: PersistedComposerImageAttachment[] = [];
692 const oversizedImageNames: string[] = [];
693 const unreadableImageNames: string[] = [];
694 for (const image of images) {
695 const result = await compressImageForStash(image.file);
696 if (!result.ok) {
697 (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push(
698 image.name,
699 );
700 continue;
701 }
702 candidateAttachments.push({
703 id: image.id,
704 name: image.name,
705 mimeType: result.image.mimeType,
706 sizeBytes: result.image.sizeBytes,
707 dataUrl: result.image.dataUrl,
708 ...(image.source
709 ? { source: resizeSnapShotSource(image.source, result.image.imageSize) }
710 : {}),
711 });
712 }
713 const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
714
715 const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
716 attachments: kept,
717 droppedImageNames: [...oversizedImageNames, ...droppedNames],
718 unreadableImageNames,
719 });
720 if (attached) {
721 if (!imagesDurable && durable && images.length > 0) {
722 toastManager.add({
723 type: "warning",
724 title: m(msg("Stashed images were not saved")),
725 description: m(
726 msg(
727 "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.",
728 ),
729 ),
730 data: { hideCopyButton: true },
731 });
732 }
733 } else if (kept.length > 0) {
734 toastManager.add({
735 type: "warning",
736 title: m(msg("Stashed images did not attach")),
737 description: m(
738 msg(
739 "{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.}}",
740 { count: kept.length },
741 ),
742 ),
743 data: { hideCopyButton: true },
744 });
745 }
746 };
747 await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey));
748 };
749 const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
750
751 const toggleStashMenu = () => {
752 if (isComposerCollapsedMobile) {
753 expandMobileComposer();
754 setIsStashMenuOpen(true);
755 return;
756 }
757 setIsStashMenuOpen((open) => !open);
758 };
759 const toggleStashMenuStable = useStableCallback(toggleStashMenu);
760
761 const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen });
762 if (
763 stashMenuClosesOn.prompt !== prompt ||
764 stashMenuClosesOn.composerMenuOpen !== composerMenuOpen
765 ) {
766 setStashMenuClosesOn({ prompt, composerMenuOpen });
767 if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
768 }
769
770 // Read at event time, so the scope registers once per mounted composer instead of
771 // re-registering (and reshuffling capture-scope priority) whenever a guard flips.
772 const handleStashShortcut = useStableCallback((event: KeyboardEvent) => {
773 // Always claim the shortcut so the browser save dialog never opens,
774 // even when the composer is in a state that can't stash.
775 event.preventDefault();
776 event.stopPropagation();
777 if (isCommandPaletteOpen() || isRevertingCheckpoint()) return;
778 if (pendingUserInputs.length > 0) {
779 setIsStashMenuOpen((open) => !open);
780 return;
781 }
782 if (projectSelectionRequired || activePendingProgress !== null) return;
783 void stashCurrentPromptStable();
784 });
785 // Capture phase while the composer is mounted, so Mod+S never reaches the browser's save
786 // dialog even when a focused widget (the model picker search) stops the key.
787 const backgroundThread = use(BackgroundThreadContext);
788 const readShortcutContext = useStableCallback(() => ({
789 terminalOpen: Boolean(
790 selectThreadTerminalUiState(
791 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
792 routeThreadRef,
793 ).terminalOpen,
794 ),
795 }));
796 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the capture-phase stash shortcut with the command registry while the composer is mounted
797 useEffect(() => {
798 if (backgroundThread) return;
799 return registerCommands(
800 { "composer.stash": handleStashShortcut },
801 {
802 capture: true,
803 context: readShortcutContext,
804 when: (event) => !isInSideChatPane(event.target),
805 },
806 );
807 }, [backgroundThread, handleStashShortcut, readShortcutContext]);
808
809 return {
810 stashQueue,
811 isStashMenuOpen,
812 setIsStashMenuOpen,
813 stashPulseKey,
814 restoreStashEntryStable,
815 deleteStashEntryStable,
816 toggleStashMenuStable,
817 };
818 }