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

useComposerStash.ts

936 lines37.4 KB

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