The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): the prompt stash lives in useComposerStash (#23046)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 13:23 UTC
0755f98401fec0f3400d4c4ef2294aa92ace39d1
2 files changed
+788
-617
apps/web/src/components/chat/ChatComposer.tsx
+43
-617
@@ -103,23 +103,14 @@ import {
103
type ComposerFileAttachment,
104
type ComposerImageAttachment,
105
type DraftId,
106
- type PersistedComposerFileAttachment,
106
type PersistedComposerImageAttachment,
108
- composerFileDedupKey,
107
composerFileMatchesReattachMarker,
108
composerFileNeedsReattach,
109
composerDraftHasUserContent,
110
composerTargetKey,
113
- hydrateImagesFromPersisted,
111
useComposerDraftStore,
112
useComposerThreadDraft,
113
} from "../../composerDraftStore";
117
-import {
118
- MAX_STASH_ENTRIES,
119
- partitionStashAttachments,
120
- usePromptStashStore,
121
- type PromptStashEntry,
122
-} from "../../promptStashStore";
114
import { ComposerStashBadge } from "./ComposerStashBadge";
115
import { ComposerStashMenu } from "./ComposerStashMenu";
116
import { useComposerTriggerState } from "./useComposerTriggerState";
@@ -146,7 +137,7 @@ import {
137
type ComposerBannerStackContent,
138
type ComposerBannerStackItem,
139
} from "./ComposerBannerStack";
149
-import { compressImageForStash, prepareImageForAttachment } from "../../lib/imageCompression";
140
+import { prepareImageForAttachment } from "../../lib/imageCompression";
141
import {
142
fileAttachmentTooLargeMessage,
143
formatAttachmentSize,
@@ -162,27 +153,19 @@ import {
153
shouldHandleComposerAttachmentPaste,
154
} from "./composerAttachmentFiles";
155
import {
165
- readAttachmentUpload,
156
releaseAttachmentUpload,
157
releaseDraftAttachment,
168
- releasePersistedAttachmentUpload,
158
startAttachmentUpload,
159
useAttachmentUploadStore,
171
- verifyStashedAttachmentUpload,
160
} from "../../lib/attachmentUploadQueue";
161
import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState";
174
-import { isCommandPaletteOpen } from "../../commandPaletteBus";
175
-import { getTerminalFocusOwner } from "../../lib/terminalFocus";
162
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
177
-import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings";
163
+import { shortcutLabelForCommand } from "../../keybindings";
164
import {
165
type TerminalContextDraft,
166
type TerminalContextSelection,
167
} from "../../lib/terminalContext";
182
-import {
183
- replaceComposerContextReferences,
184
- toKindScopedComposerContextId,
185
-} from "@t3tools/shared/composerContextReferences";
168
+import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences";
169
import {
170
shouldUseCompactComposerPrimaryActions,
171
shouldUseCompactComposerFooter,
@@ -292,7 +275,6 @@ import {
275
buildExpandedImagePreview,
276
type ExpandedImagePreview,
277
} from "./ExpandedImagePreview";
295
-import { resizeSnapShotSource } from "../../lib/snapShotSource";
278
import { cn, isMacPlatform, randomUUID } from "~/lib/utils";
279
import {
280
getComposerPromptLengthValidationMessage,
@@ -301,10 +283,7 @@ import {
283
} from "./composerSubmission";
284
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
285
import { pendingDraftWork } from "./pendingDraftWork";
304
-import {
305
- importComposerThreadAttachment,
306
- remainingComposerAttachmentSlots,
307
-} from "./composerThreadImport";
286
+import { importComposerThreadAttachment } from "./composerThreadImport";
287
import { isTimelineScrollTarget } from "./timelineScrollTarget";
288
import {
289
createComposerScrollGestureState,
@@ -367,6 +346,7 @@ import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLa
346
import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh";
347
import { useComposerProviderModel } from "./useComposerProviderModel";
348
import { useComposerImageGroups } from "./useComposerImageGroups";
349
+import { useComposerStash } from "./useComposerStash";
350
351
/** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */
352
function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
@@ -939,12 +919,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
919
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
920
(store) => store.clearPersistedAttachments,
921
);
942
- const clearComposerDraftTerminalContexts = useComposerDraftStore(
943
- (store) => store.clearTerminalContexts,
944
- );
945
- const clearComposerDraftPromptAndImages = useComposerDraftStore(
946
- (store) => store.clearComposerPromptAndImages,
947
- );
922
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
923
(store) => store.syncPersistedAttachments,
924
);
@@ -1198,12 +1172,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1172
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
1173
const hasWrappedPrompt = useComposerMultilinePrompt(composerMenuAnchor);
1174
const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt;
1201
- const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
1175
const [isTasksDrawerOpen, setIsTasksDrawerOpen] = useState(false);
1203
- const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
1204
- key: 0,
1205
- active: false,
1206
- });
1176
// A pending question stays expanded: its card moves into the banner dock,
1177
// so collapsing would leave the surface empty and squashed beneath it.
1178
const isComposerCollapsedMobile =
@@ -1234,9 +1203,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1203
const composerScrollCollapseEligibleRef = useRef(false);
1204
const windowRefocusInFlightRef = useRef(false);
1205
const composerScrollGestureRef = useRef(createComposerScrollGestureState());
1237
- const stashPulseKeyRef = useRef(0);
1238
- const stashPulseTimeoutRef = useRef<number | null>(null);
1239
- const stashInFlightRef = useRef<Set<string>>(new Set());
1206
const pendingImageCompressionsRef = useRef<Map<string, number>>(new Map());
1207
const pendingThreadImportsRef = useRef<Map<string, number>>(new Map());
1208
const isRevertingCheckpointRef = useRef(isRevertingCheckpoint);
@@ -2786,536 +2752,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2752
return false;
2753
};
2754
2789
- const stashQueue = usePromptStashStore((state) => state.entries);
2790
- const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
2791
- const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
2792
- const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
2793
-
2794
- useEffect(() => {
2795
- return () => {
2796
- if (stashPulseTimeoutRef.current !== null) {
2797
- window.clearTimeout(stashPulseTimeoutRef.current);
2798
- }
2799
- };
2800
- }, []);
2801
-
2802
- const pulseStashBadge = () => {
2803
- stashPulseKeyRef.current += 1;
2804
- setStashPulse({ key: stashPulseKeyRef.current, active: true });
2805
- if (stashPulseTimeoutRef.current !== null) {
2806
- window.clearTimeout(stashPulseTimeoutRef.current);
2807
- }
2808
- stashPulseTimeoutRef.current = window.setTimeout(() => {
2809
- stashPulseTimeoutRef.current = null;
2810
- setStashPulse((current) => ({ ...current, active: false }));
2811
- }, 1200);
2812
- };
2813
-
2814
- const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
2815
- const filesToVerify = menuEntry.files ?? [];
2816
- if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
2817
- toastManager.add({
2818
- type: "error",
2819
- title: "Stashed files belong to another environment",
2820
- description: "Restore this prompt in the environment that received its files.",
2821
- });
2822
- return;
2823
- }
2824
- setIsStashMenuOpen(false);
2825
-
2826
- // An expired upload restores as a needs-reattach row instead of a reference
2827
- // the next send would fail to verify. Verify BEFORE taking: the take
2828
- // removes the entry from durable storage, and a tab closed during this
2829
- // await must still find it there after reload.
2830
- const verifications = await Promise.all(
2831
- filesToVerify.map((file) =>
2832
- verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }),
2833
- ),
2834
- );
2835
- const expiredAttachmentIds = new Set(
2836
- filesToVerify
2837
- .filter((_, index) => verifications[index]?.status === "missing")
2838
- .map((file) => file.attachmentId),
2839
- );
2840
-
2841
- // A thread switch during the verify await would mix the new thread's
2842
- // prompt with this invocation's captured target. Nothing was taken yet,
2843
- // so abort and leave the entry restorable where the user now is.
2844
- if (
2845
- isRevertingCheckpointRef.current ||
2846
- composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
2847
- ) {
2848
- return;
2849
- }
2850
-
2851
- const { entry, durable } = takeStashEntry(menuEntry.id);
2852
- if (!entry) return;
2853
- if (!durable) {
2854
- toastManager.add({
2855
- type: "warning",
2856
- title: "Restored prompt may reappear in the stash",
2857
- description:
2858
- "Browser storage rejected the update, so this entry could still be there after a reload.",
2859
- data: { hideCopyButton: true },
2860
- });
2861
- }
2862
-
2863
- const rewrittenContextIds = entry.records
2864
- ? importContextRecords(entry.records, null, composerDraftTarget)
2865
- : new Map<string, string>();
2866
- const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => {
2867
- const contextId = rewrittenContextIds.get(reference.contextId);
2868
- return contextId
2869
- ? formatInlineContextReference({
2870
- ...reference,
2871
- contextId,
2872
- kind: reference.kind === "element" ? "preview-annotation" : reference.kind,
2873
- })
2874
- : reference.source;
2875
- });
2876
- const currentPrompt = promptRef.current;
2877
- const nextPrompt =
2878
- restoredPrompt.length === 0
2879
- ? currentPrompt
2880
- : currentPrompt.trim().length
2881
- ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}`
2882
- : restoredPrompt;
2883
- let promptChanged = nextPrompt !== currentPrompt;
2884
- if (promptChanged) {
2885
- promptRef.current = nextPrompt;
2886
- setComposerDraftPrompt(composerDraftTarget, nextPrompt);
2887
- setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
2888
- setComposerTrigger(null);
2889
- }
2890
-
2891
- let unrestoredFileNames: string[] = [];
2892
- const expiredFileNames: string[] = [];
2893
- let restoredFileCount = 0;
2894
- const stashedFiles = entry.files ?? [];
2895
- if (stashedFiles.length > 0) {
2896
- const composerFilesNow = composerFilesRef.current;
2897
- const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
2898
- const retainedUploadIds = new Set(
2899
- composerFilesNow.flatMap((file) =>
2900
- file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
2901
- ),
2902
- );
2903
- const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey));
2904
- const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach);
2905
- const restoredMarkerIds = new Set<string>();
2906
- const duplicateFiles: PersistedComposerFileAttachment[] = [];
2907
- const markerReplacements: ComposerFileAttachment[] = [];
2908
- const appendedFiles: ComposerFileAttachment[] = [];
2909
- for (const file of stashedFiles) {
2910
- const expired = expiredAttachmentIds.has(file.attachmentId);
2911
- const key = composerFileDedupKey(file);
2912
- const restored: ComposerFileAttachment = {
2913
- type: "file",
2914
- id: file.id,
2915
- name: file.name,
2916
- mimeType: file.mimeType,
2917
- sizeBytes: file.sizeBytes,
2918
- file: null,
2919
- ...(file.source ? { source: file.source } : {}),
2920
- ...(expired
2921
- ? {}
2922
- : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }),
2923
- };
2924
- if (existingFileIds.has(file.id)) {
2925
- if (!expired && !retainedUploadIds.has(file.attachmentId)) {
2926
- duplicateFiles.push(file);
2927
- }
2928
- continue;
2929
- }
2930
- const reattachMarker = reattachMarkers.find(
2931
- (marker) =>
2932
- !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file),
2933
- );
2934
- if (reattachMarker) {
2935
- restoredMarkerIds.add(reattachMarker.id);
2936
- existingFileIds.add(file.id);
2937
- existingFileKeys.add(key);
2938
- if (expired) {
2939
- expiredFileNames.push(file.name);
2940
- } else {
2941
- retainedUploadIds.add(file.attachmentId);
2942
- markerReplacements.push(restored);
2943
- }
2944
- continue;
2945
- }
2946
- if (existingFileKeys.has(key)) {
2947
- if (!expired && !retainedUploadIds.has(file.attachmentId)) {
2948
- duplicateFiles.push(file);
2949
- }
2950
- continue;
2951
- }
2952
- existingFileIds.add(file.id);
2953
- existingFileKeys.add(key);
2954
- if (expired) {
2955
- expiredFileNames.push(file.name);
2956
- } else {
2957
- retainedUploadIds.add(file.attachmentId);
2958
- }
2959
- appendedFiles.push(restored);
2960
- }
2961
- const capacity = remainingComposerAttachmentSlots(
2962
- composerImagesRef.current.length + composerFilesNow.length,
2963
- pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
2964
- );
2965
- const filesToAppend = appendedFiles.slice(0, capacity);
2966
- const skippedFiles = appendedFiles.slice(capacity);
2967
- unrestoredFileNames = skippedFiles.map((file) => file.name);
2968
- // A non-durable take can resurrect the stash entry after a reload;
2969
- // deleting these uploads would leave it pointing at nothing.
2970
- if (durable) {
2971
- for (const file of duplicateFiles) {
2972
- releasePersistedAttachmentUpload({
2973
- id: file.id,
2974
- environmentId,
2975
- attachmentId: file.attachmentId,
2976
- });
2977
- }
2978
- for (const file of skippedFiles) {
2979
- if (file.uploadedAttachmentId) {
2980
- releasePersistedAttachmentUpload({
2981
- id: file.id,
2982
- environmentId,
2983
- attachmentId: file.uploadedAttachmentId,
2984
- });
2985
- }
2986
- }
2987
- }
2988
- const restoredFiles = [...markerReplacements, ...filesToAppend];
2989
- if (restoredFiles.length > 0) {
2990
- addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true });
2991
- const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt;
2992
- if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) {
2993
- promptRef.current = restoredFilePrompt;
2994
- setComposerCursor(
2995
- collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length),
2996
- );
2997
- setComposerTrigger(null);
2998
- promptChanged = true;
2999
- }
3000
- restoredFileCount = filesToAppend.length;
3001
- }
3002
- }
3003
-
3004
- let unrestoredImageNames: string[] = [];
3005
- if (entry.attachments.length > 0) {
3006
- const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
3007
- // The draft store also dedupes by mimeType+sizeBytes+name, so filter
3008
- // on the same key here. Counting a duplicate against capacity would
3009
- // burn a slot the store then refuses to fill, pushing a genuinely
3010
- // unique image into the overflow list for nothing.
3011
- const existingDedupKeys = new Set(
3012
- composerImagesRef.current.map(
3013
- (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
3014
- ),
3015
- );
3016
- const capacity = remainingComposerAttachmentSlots(
3017
- composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
3018
- pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
3019
- );
3020
- const pending = entry.attachments.filter(
3021
- (attachment) =>
3022
- !existingIds.has(attachment.id) &&
3023
- !existingDedupKeys.has(
3024
- `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`,
3025
- ),
3026
- );
3027
- unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name);
3028
- const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity));
3029
- if (restoredImages.length > 0) {
3030
- addComposerDraftImages(composerDraftTarget, restoredImages);
3031
- }
3032
- }
3033
-
3034
- const missingImageReasons: string[] = [];
3035
- if (entry.droppedImageNames.length > 0) {
3036
- missingImageReasons.push(
3037
- `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
3038
- );
3039
- }
3040
- if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
3041
- missingImageReasons.push(
3042
- `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
3043
- );
3044
- }
3045
- if (unrestoredImageNames.length > 0) {
3046
- missingImageReasons.push(
3047
- `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
3048
- );
3049
- }
3050
- if (unrestoredFileNames.length > 0) {
3051
- missingImageReasons.push(
3052
- `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
3053
- );
3054
- }
3055
- if (expiredFileNames.length > 0) {
3056
- missingImageReasons.push(
3057
- `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`,
3058
- );
3059
- }
3060
- if (missingImageReasons.length > 0) {
3061
- toastManager.add({
3062
- type: "warning",
3063
- title: "Some attachments were not restored",
3064
- description: missingImageReasons.join(" "),
3065
- });
3066
- }
3067
-
3068
- if (promptChanged) {
3069
- window.requestAnimationFrame(() => {
3070
- composerEditorRef.current?.focusAtEnd();
3071
- });
3072
- }
3073
- };
3074
- const restoreStashEntryStable = useStableCallback(restoreStashEntry);
3075
-
3076
- const deleteStashEntry = (entry: PromptStashEntry) => {
3077
- const { entry: removed, durable } = takeStashEntry(entry.id);
3078
- if (!stashQueue.some((candidate) => candidate.id !== entry.id)) {
3079
- setIsStashMenuOpen(false);
3080
- }
3081
- if (durable && removed) {
3082
- for (const file of removed.files ?? []) {
3083
- releasePersistedAttachmentUpload({
3084
- id: file.id,
3085
- environmentId: file.environmentId,
3086
- attachmentId: file.attachmentId,
3087
- });
3088
- }
3089
- }
3090
- if (!durable) {
3091
- toastManager.add({
3092
- type: "warning",
3093
- title: "Stash entry may come back",
3094
- description:
3095
- "Browser storage rejected the delete, so this prompt could reappear after a reload.",
3096
- data: { hideCopyButton: true },
3097
- });
3098
- }
3099
- };
3100
- const deleteStashEntryStable = useStableCallback(deleteStashEntry);
3101
-
3102
- const stashCurrentPrompt = async () => {
3103
- // Stashing clears the draft. A pasted attachment still downloading would then land in the
3104
- // emptied composer instead of travelling with the entry it belongs to.
3105
- if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
3106
- toastManager.add({
3107
- type: "info",
3108
- title: "Still bringing attached context into this message.",
3109
- description: "Stash again once its chip resolves.",
3110
- });
3111
- return;
3112
- }
3113
- const prompt = promptRef.current.trim();
3114
- const images = [...composerImagesRef.current];
3115
- const files = [...composerFilesRef.current];
3116
- const stashedRecords: ComposerContextRecord[] = [
3117
- ...composerThreadContexts,
3118
- ...composerTerminalContextsRef.current.map(terminalContextRecord),
3119
- ...composerReviewComments.map(reviewCommentContextRecord),
3120
- ...composerPreviewAnnotations.map((annotation) =>
3121
- previewAnnotationContextRecord(annotation, {
3122
- screenshotContextId: images.some((image) => image.id === annotation.id)
3123
- ? annotation.id
3124
- : undefined,
3125
- }),
3126
- ),
3127
- ];
3128
- if (prompt.length === 0 && images.length === 0 && files.length === 0) {
3129
- const entries = usePromptStashStore.getState().entries;
3130
- const entry = entries.length === 1 ? entries[0] : undefined;
3131
- if (entry && !entry.pendingImageCount) {
3132
- await restoreStashEntry(entry);
3133
- } else {
3134
- setIsStashMenuOpen((open) => !open);
3135
- }
3136
- return;
3137
- }
3138
- const stashedFiles: PersistedComposerFileAttachment[] = [];
3139
- for (const file of files) {
3140
- if (composerFileNeedsReattach(file)) {
3141
- toastManager.add({
3142
- type: "error",
3143
- title: "Attach dropped files again or remove them before stashing",
3144
- });
3145
- return;
3146
- }
3147
- const upload = readAttachmentUpload(file.id);
3148
- if (upload?.status !== "ready" || upload.environmentId !== environmentId) {
3149
- toastManager.add({
3150
- type: "error",
3151
- title: "Wait for file uploads before stashing this prompt",
3152
- });
3153
- return;
3154
- }
3155
- stashedFiles.push({
3156
- id: file.id,
3157
- name: file.name,
3158
- mimeType: file.mimeType,
3159
- sizeBytes: file.sizeBytes,
3160
- attachmentId: upload.attachmentId,
3161
- environmentId,
3162
- ...(file.source ? { source: file.source } : {}),
3163
- });
3164
- }
3165
- // A repeat ⌘S on the *same* still-unencoded snapshot would stash it
3166
- // twice. Guard on the snapshot itself rather than a bare boolean: once
3167
- // the composer has been cleared the user can type something genuinely
3168
- // new (or switch threads) while encoding continues, and that deserves its
3169
- // own entry.
3170
- const attachmentKey = images
3171
- .map((image) => `image:${image.id}`)
3172
- .concat(files.map((file) => `file:${file.id}`))
3173
- .join(",");
3174
- const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n");
3175
- if (stashInFlightRef.current.has(snapshotKey)) return;
3176
- stashInFlightRef.current.add(snapshotKey);
3177
-
3178
- const stashTarget = composerDraftTarget;
3179
- const entryId = randomUUID();
3180
- const stashAndEncode = async () => {
3181
- // Ordering matters in both directions: writing before clearing means a
3182
- // crash or closed tab mid-encode still leaves the prompt recoverable,
3183
- // while clearing before the async image work means edits typed during
3184
- // encoding are not wiped.
3185
- const { evicted, written, durable } = stashEntryToQueue({
3186
- id: entryId,
3187
- createdAt: new Date().toISOString(),
3188
- prompt,
3189
- attachments: [],
3190
- ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}),
3191
- droppedImageNames: [],
3192
- unreadableImageNames: [],
3193
- pendingImageCount: images.length,
3194
- ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}),
3195
- });
3196
-
3197
- // If it was rejected (quota) the store has already rolled itself back,
3198
- // so leave the composer untouched rather than making it the second
3199
- // casualty of a reload.
3200
- if (!written) {
3201
- toastManager.add({
3202
- type: "error",
3203
- title: "Could not stash this prompt",
3204
- description:
3205
- "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
3206
- data: { hideCopyButton: true },
3207
- });
3208
- return;
3209
- }
3210
- if (!durable) {
3211
- toastManager.add({
3212
- type: "warning",
3213
- title: "Stashed prompt will not survive a reload",
3214
- description:
3215
- "Browser storage is unavailable, so this stash is kept in memory only for this session.",
3216
- data: { hideCopyButton: true },
3217
- });
3218
- }
3219
-
3220
- promptRef.current = "";
3221
- clearComposerDraftPromptAndImages(stashTarget);
3222
- clearComposerDraftTerminalContexts(stashTarget);
3223
- setComposerDraftThreadContexts(stashTarget, []);
3224
- for (const comment of composerReviewComments) {
3225
- removeComposerDraftReviewComment(stashTarget, comment.id);
3226
- }
3227
- for (const annotation of composerPreviewAnnotations) {
3228
- releaseAttachmentUpload(annotation.id);
3229
- removeComposerDraftPreviewAnnotation(stashTarget, annotation.id);
3230
- }
3231
- setComposerDraftPrompt(stashTarget, "");
3232
- for (const image of images) {
3233
- releaseAttachmentUpload(image.id);
3234
- }
3235
- setComposerCursor(0);
3236
- setComposerTrigger(null);
3237
- pulseStashBadge();
3238
-
3239
- if (evicted) {
3240
- for (const file of evicted.files ?? []) {
3241
- releasePersistedAttachmentUpload({
3242
- id: file.id,
3243
- environmentId: file.environmentId,
3244
- attachmentId: file.attachmentId,
3245
- });
3246
- }
3247
- toastManager.add({
3248
- type: "warning",
3249
- title: "Oldest stashed prompt discarded",
3250
- description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
3251
- data: { hideCopyButton: true },
3252
- });
3253
- }
3254
-
3255
- // Images are re-encoded for the stash rather than stored verbatim: the
3256
- // composer allows up to 10MB per image, but localStorage gives the whole
3257
- // origin ~5MB.
3258
- const candidateAttachments: PersistedComposerImageAttachment[] = [];
3259
- const oversizedImageNames: string[] = [];
3260
- const unreadableImageNames: string[] = [];
3261
- for (const image of images) {
3262
- const result = await compressImageForStash(image.file);
3263
- if (!result.ok) {
3264
- (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push(
3265
- image.name,
3266
- );
3267
- continue;
3268
- }
3269
- candidateAttachments.push({
3270
- id: image.id,
3271
- name: image.name,
3272
- mimeType: result.image.mimeType,
3273
- sizeBytes: result.image.sizeBytes,
3274
- dataUrl: result.image.dataUrl,
3275
- ...(image.source
3276
- ? { source: resizeSnapShotSource(image.source, result.image.imageSize) }
3277
- : {}),
3278
- });
3279
- }
3280
- const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
3281
-
3282
- const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
3283
- attachments: kept,
3284
- droppedImageNames: [...oversizedImageNames, ...droppedNames],
3285
- unreadableImageNames,
3286
- });
3287
- if (attached) {
3288
- if (!imagesDurable && durable && images.length > 0) {
3289
- toastManager.add({
3290
- type: "warning",
3291
- title: "Stashed images were not saved",
3292
- description:
3293
- "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.",
3294
- data: { hideCopyButton: true },
3295
- });
3296
- }
3297
- } else if (kept.length > 0) {
3298
- toastManager.add({
3299
- type: "warning",
3300
- title: "Stashed images did not attach",
3301
- description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`,
3302
- data: { hideCopyButton: true },
3303
- });
3304
- }
3305
- };
3306
- await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey));
3307
- };
3308
- const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
3309
-
3310
- const toggleStashMenu = () => {
3311
- if (isComposerCollapsedMobile) {
3312
- expandMobileComposer();
3313
- setIsStashMenuOpen(true);
3314
- return;
3315
- }
3316
- setIsStashMenuOpen((open) => !open);
3317
- };
3318
- const toggleStashMenuStable = useStableCallback(toggleStashMenu);
2755
+ const {
2756
+ stashQueue,
2757
+ isStashMenuOpen,
2758
+ setIsStashMenuOpen,
2759
+ stashPulse,
2760
+ restoreStashEntryStable,
2761
+ deleteStashEntryStable,
2762
+ toggleStashMenuStable,
2763
+ } = useComposerStash({
2764
+ environmentId,
2765
+ composerDraftTarget,
2766
+ promptRef,
2767
+ composerImagesRef,
2768
+ composerFilesRef,
2769
+ composerTerminalContextsRef,
2770
+ keybindings,
2771
+ terminalOpen,
2772
+ projectSelectionRequired,
2773
+ isRevertingCheckpoint,
2774
+ pendingUserInputs,
2775
+ activePendingProgress,
2776
+ prompt,
2777
+ composerMenuOpen,
2778
+ isComposerModelPickerOpen,
2779
+ isComposerCollapsedMobile,
2780
+ composerPreviewAnnotations,
2781
+ composerReviewComments,
2782
+ composerThreadContexts,
2783
+ attachmentTargetKeyRef,
2784
+ composerDraftTargetKeyRef,
2785
+ composerEditorRef,
2786
+ isRevertingCheckpointRef,
2787
+ pendingThreadImportsRef,
2788
+ setComposerCursor,
2789
+ setComposerTrigger,
2790
+ importContextRecords,
2791
+ expandMobileComposer: expandMobileComposerStable,
2792
+ });
2793
const toggleTasksDrawer = () => {
2794
setIsTasksDrawerOpen((open) => !open);
2795
};
@@ -3755,54 +3229,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3229
}
3230
if (tasksDrawerThreadId !== activeThreadId) setTasksDrawerThreadId(activeThreadId);
3231
3758
- const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen });
3759
- if (
3760
- stashMenuClosesOn.prompt !== prompt ||
3761
- stashMenuClosesOn.composerMenuOpen !== composerMenuOpen
3762
- ) {
3763
- setStashMenuClosesOn({ prompt, composerMenuOpen });
3764
- if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
3765
- }
3766
-
3767
- useEffect(() => {
3768
- const handler = (event: globalThis.KeyboardEvent) => {
3769
- const command = resolveShortcutCommand(event, keybindings, {
3770
- context: {
3771
- terminalFocus: getTerminalFocusOwner() !== null,
3772
- terminalOpen,
3773
- modelPickerOpen: isComposerModelPickerOpen,
3774
- },
3775
- });
3776
- if (command !== "composer.stash") return;
3777
- // Always claim the shortcut so the browser save dialog never opens,
3778
- // even when the composer is in a state that can't stash.
3779
- event.preventDefault();
3780
- event.stopPropagation();
3781
- if (isCommandPaletteOpen() || isRevertingCheckpoint) {
3782
- return;
3783
- }
3784
- if (pendingUserInputs.length > 0) {
3785
- setIsStashMenuOpen((open) => !open);
3786
- return;
3787
- }
3788
- if (projectSelectionRequired || activePendingProgress !== null) {
3789
- return;
3790
- }
3791
- void stashCurrentPromptStable();
3792
- };
3793
- window.addEventListener("keydown", handler, true);
3794
- return () => window.removeEventListener("keydown", handler, true);
3795
- }, [
3796
- activePendingProgress,
3797
- isComposerModelPickerOpen,
3798
- keybindings,
3799
- pendingUserInputs.length,
3800
- projectSelectionRequired,
3801
- stashCurrentPromptStable,
3802
- isRevertingCheckpoint,
3803
- terminalOpen,
3804
- ]);
3805
-
3232
const insertComposerText = (
3233
text: string,
3234
position: "cursor" | "end",
apps/web/src/components/chat/useComposerStash.ts
new
+745
@@ -0,0 +1,745 @@
1
+import type { ChatComposerProps } from "./ChatComposer";
2
+import {
3
+ type ComposerContextRecord,
4
+ type EnvironmentId,
5
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6
+ type PreviewAnnotationPayload,
7
+ type ThreadContextRecord,
8
+} from "@t3tools/contracts";
9
+import {
10
+ type ComposerFileAttachment,
11
+ type PersistedComposerFileAttachment,
12
+ type PersistedComposerImageAttachment,
13
+ composerFileDedupKey,
14
+ composerFileMatchesReattachMarker,
15
+ composerFileNeedsReattach,
16
+ composerTargetKey,
17
+ hydrateImagesFromPersisted,
18
+ useComposerDraftStore,
19
+} from "../../composerDraftStore";
20
+import { type ComposerPromptEditorHandle } from "../ComposerPromptEditor";
21
+import {
22
+ MAX_STASH_ENTRIES,
23
+ type PromptStashEntry,
24
+ partitionStashAttachments,
25
+ usePromptStashStore,
26
+} from "../../promptStashStore";
27
+import { type PendingUserInput } from "../../session-logic";
28
+import { type ReviewCommentContext } from "../../reviewCommentContext";
29
+import { collapseExpandedComposerCursor } from "../../composer-logic";
30
+import { compressImageForStash } from "../../lib/imageCompression";
31
+import { formatInlineContextReference } from "~/lib/composerContextReferences";
32
+import { getTerminalFocusOwner } from "../../lib/terminalFocus";
33
+import { isCommandPaletteOpen } from "../../commandPaletteBus";
34
+import { pendingDraftWork } from "./pendingDraftWork";
35
+import {
36
+ previewAnnotationContextRecord,
37
+ reviewCommentContextRecord,
38
+ terminalContextRecord,
39
+} from "~/lib/composerContextRecords";
40
+import { randomUUID } from "~/lib/utils";
41
+import {
42
+ readAttachmentUpload,
43
+ releaseAttachmentUpload,
44
+ releasePersistedAttachmentUpload,
45
+ verifyStashedAttachmentUpload,
46
+} from "../../lib/attachmentUploadQueue";
47
+import { remainingComposerAttachmentSlots } from "./composerThreadImport";
48
+import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
49
+import { resizeSnapShotSource } from "../../lib/snapShotSource";
50
+import { resolveShortcutCommand } from "../../keybindings";
51
+import { toastManager } from "../ui/toast";
52
+import type { useComposerTriggerState } from "./useComposerTriggerState";
53
+import {
54
+ type Dispatch,
55
+ type RefObject,
56
+ type SetStateAction,
57
+ useEffect,
58
+ useRef,
59
+ useState,
60
+} from "react";
61
+import { useStableCallback } from "../../hooks/useStableCallback";
62
+
63
+/**
64
+ * The prompt stash: saving the draft aside, restoring or deleting an entry, the badge pulse,
65
+ * and the stash shortcut. Its state lives here so the composer body only wires it up.
66
+ */
67
+export function useComposerStash(input: {
68
+ readonly environmentId: EnvironmentId;
69
+ readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"];
70
+ readonly promptRef: ChatComposerProps["promptRef"];
71
+ readonly composerImagesRef: ChatComposerProps["composerImagesRef"];
72
+ readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
73
+ readonly composerTerminalContextsRef: ChatComposerProps["composerTerminalContextsRef"];
74
+ readonly keybindings: ChatComposerProps["keybindings"];
75
+ readonly terminalOpen: boolean;
76
+ readonly projectSelectionRequired: boolean;
77
+ readonly isRevertingCheckpoint: boolean;
78
+ readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
79
+ readonly activePendingProgress: ChatComposerProps["activePendingProgress"];
80
+ readonly prompt: string;
81
+ readonly composerMenuOpen: boolean;
82
+ readonly isComposerModelPickerOpen: boolean;
83
+ readonly isComposerCollapsedMobile: boolean;
84
+ readonly composerPreviewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
85
+ readonly composerReviewComments: ReadonlyArray<ReviewCommentContext>;
86
+ readonly composerThreadContexts: ReadonlyArray<ThreadContextRecord>;
87
+ readonly attachmentTargetKeyRef: RefObject<string>;
88
+ readonly composerDraftTargetKeyRef: RefObject<string>;
89
+ readonly composerEditorRef: RefObject<ComposerPromptEditorHandle | null>;
90
+ readonly isRevertingCheckpointRef: RefObject<boolean>;
91
+ readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
92
+ readonly setComposerCursor: Dispatch<SetStateAction<number>>;
93
+ readonly setComposerTrigger: ReturnType<typeof useComposerTriggerState>["setTrigger"];
94
+ readonly importContextRecords: (
95
+ records: ReadonlyArray<ComposerContextRecord>,
96
+ sourceEnvironmentId: EnvironmentId | null,
97
+ threadDraftTarget?: ChatComposerProps["composerDraftTarget"],
98
+ ) => ReadonlyMap<string, string>;
99
+ readonly expandMobileComposer: () => void;
100
+}) {
101
+ const {
102
+ environmentId,
103
+ composerDraftTarget,
104
+ promptRef,
105
+ composerImagesRef,
106
+ composerFilesRef,
107
+ composerTerminalContextsRef,
108
+ keybindings,
109
+ terminalOpen,
110
+ projectSelectionRequired,
111
+ isRevertingCheckpoint,
112
+ pendingUserInputs,
113
+ activePendingProgress,
114
+ prompt,
115
+ composerMenuOpen,
116
+ isComposerModelPickerOpen,
117
+ isComposerCollapsedMobile,
118
+ composerPreviewAnnotations,
119
+ composerReviewComments,
120
+ composerThreadContexts,
121
+ attachmentTargetKeyRef,
122
+ composerDraftTargetKeyRef,
123
+ composerEditorRef,
124
+ isRevertingCheckpointRef,
125
+ pendingThreadImportsRef,
126
+ setComposerCursor,
127
+ setComposerTrigger,
128
+ importContextRecords,
129
+ expandMobileComposer,
130
+ } = input;
131
+ const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
132
+ const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
133
+ const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
134
+ const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);
135
+ const removeComposerDraftPreviewAnnotation = useComposerDraftStore(
136
+ (store) => store.removePreviewAnnotation,
137
+ );
138
+ const removeComposerDraftReviewComment = useComposerDraftStore(
139
+ (store) => store.removeReviewComment,
140
+ );
141
+ const clearComposerDraftTerminalContexts = useComposerDraftStore(
142
+ (store) => store.clearTerminalContexts,
143
+ );
144
+ const clearComposerDraftPromptAndImages = useComposerDraftStore(
145
+ (store) => store.clearComposerPromptAndImages,
146
+ );
147
+ const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
148
+ const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
149
+ const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
150
+ key: 0,
151
+ active: false,
152
+ });
153
+ const stashPulseKeyRef = useRef(0);
154
+ const stashPulseTimeoutRef = useRef<number | null>(null);
155
+ const stashInFlightRef = useRef<Set<string>>(new Set());
156
+
157
+ const stashQueue = usePromptStashStore((state) => state.entries);
158
+ const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
159
+ const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
160
+ const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
161
+
162
+ useEffect(() => {
163
+ return () => {
164
+ if (stashPulseTimeoutRef.current !== null) {
165
+ window.clearTimeout(stashPulseTimeoutRef.current);
166
+ }
167
+ };
168
+ }, []);
169
+
170
+ const pulseStashBadge = () => {
171
+ stashPulseKeyRef.current += 1;
172
+ setStashPulse({ key: stashPulseKeyRef.current, active: true });
173
+ if (stashPulseTimeoutRef.current !== null) {
174
+ window.clearTimeout(stashPulseTimeoutRef.current);
175
+ }
176
+ stashPulseTimeoutRef.current = window.setTimeout(() => {
177
+ stashPulseTimeoutRef.current = null;
178
+ setStashPulse((current) => ({ ...current, active: false }));
179
+ }, 1200);
180
+ };
181
+
182
+ const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
183
+ const filesToVerify = menuEntry.files ?? [];
184
+ if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
185
+ toastManager.add({
186
+ type: "error",
187
+ title: "Stashed files belong to another environment",
188
+ description: "Restore this prompt in the environment that received its files.",
189
+ });
190
+ return;
191
+ }
192
+ setIsStashMenuOpen(false);
193
+
194
+ // An expired upload restores as a needs-reattach row instead of a reference
195
+ // the next send would fail to verify. Verify BEFORE taking: the take
196
+ // removes the entry from durable storage, and a tab closed during this
197
+ // await must still find it there after reload.
198
+ const verifications = await Promise.all(
199
+ filesToVerify.map((file) =>
200
+ verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }),
201
+ ),
202
+ );
203
+ const expiredAttachmentIds = new Set(
204
+ filesToVerify
205
+ .filter((_, index) => verifications[index]?.status === "missing")
206
+ .map((file) => file.attachmentId),
207
+ );
208
+
209
+ // A thread switch during the verify await would mix the new thread's
210
+ // prompt with this invocation's captured target. Nothing was taken yet,
211
+ // so abort and leave the entry restorable where the user now is.
212
+ if (
213
+ isRevertingCheckpointRef.current ||
214
+ composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
215
+ ) {
216
+ return;
217
+ }
218
+
219
+ const { entry, durable } = takeStashEntry(menuEntry.id);
220
+ if (!entry) return;
221
+ if (!durable) {
222
+ toastManager.add({
223
+ type: "warning",
224
+ title: "Restored prompt may reappear in the stash",
225
+ description:
226
+ "Browser storage rejected the update, so this entry could still be there after a reload.",
227
+ data: { hideCopyButton: true },
228
+ });
229
+ }
230
+
231
+ const rewrittenContextIds = entry.records
232
+ ? importContextRecords(entry.records, null, composerDraftTarget)
233
+ : new Map<string, string>();
234
+ const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => {
235
+ const contextId = rewrittenContextIds.get(reference.contextId);
236
+ return contextId
237
+ ? formatInlineContextReference({
238
+ ...reference,
239
+ contextId,
240
+ kind: reference.kind === "element" ? "preview-annotation" : reference.kind,
241
+ })
242
+ : reference.source;
243
+ });
244
+ const currentPrompt = promptRef.current;
245
+ const nextPrompt =
246
+ restoredPrompt.length === 0
247
+ ? currentPrompt
248
+ : currentPrompt.trim().length
249
+ ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}`
250
+ : restoredPrompt;
251
+ let promptChanged = nextPrompt !== currentPrompt;
252
+ if (promptChanged) {
253
+ promptRef.current = nextPrompt;
254
+ setComposerDraftPrompt(composerDraftTarget, nextPrompt);
255
+ setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
256
+ setComposerTrigger(null);
257
+ }
258
+
259
+ let unrestoredFileNames: string[] = [];
260
+ const expiredFileNames: string[] = [];
261
+ let restoredFileCount = 0;
262
+ const stashedFiles = entry.files ?? [];
263
+ if (stashedFiles.length > 0) {
264
+ const composerFilesNow = composerFilesRef.current;
265
+ const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
266
+ const retainedUploadIds = new Set(
267
+ composerFilesNow.flatMap((file) =>
268
+ file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
269
+ ),
270
+ );
271
+ const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey));
272
+ const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach);
273
+ const restoredMarkerIds = new Set<string>();
274
+ const duplicateFiles: PersistedComposerFileAttachment[] = [];
275
+ const markerReplacements: ComposerFileAttachment[] = [];
276
+ const appendedFiles: ComposerFileAttachment[] = [];
277
+ for (const file of stashedFiles) {
278
+ const expired = expiredAttachmentIds.has(file.attachmentId);
279
+ const key = composerFileDedupKey(file);
280
+ const restored: ComposerFileAttachment = {
281
+ type: "file",
282
+ id: file.id,
283
+ name: file.name,
284
+ mimeType: file.mimeType,
285
+ sizeBytes: file.sizeBytes,
286
+ file: null,
287
+ ...(file.source ? { source: file.source } : {}),
288
+ ...(expired
289
+ ? {}
290
+ : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }),
291
+ };
292
+ if (existingFileIds.has(file.id)) {
293
+ if (!expired && !retainedUploadIds.has(file.attachmentId)) {
294
+ duplicateFiles.push(file);
295
+ }
296
+ continue;
297
+ }
298
+ const reattachMarker = reattachMarkers.find(
299
+ (marker) =>
300
+ !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file),
301
+ );
302
+ if (reattachMarker) {
303
+ restoredMarkerIds.add(reattachMarker.id);
304
+ existingFileIds.add(file.id);
305
+ existingFileKeys.add(key);
306
+ if (expired) {
307
+ expiredFileNames.push(file.name);
308
+ } else {
309
+ retainedUploadIds.add(file.attachmentId);
310
+ markerReplacements.push(restored);
311
+ }
312
+ continue;
313
+ }
314
+ if (existingFileKeys.has(key)) {
315
+ if (!expired && !retainedUploadIds.has(file.attachmentId)) {
316
+ duplicateFiles.push(file);
317
+ }
318
+ continue;
319
+ }
320
+ existingFileIds.add(file.id);
321
+ existingFileKeys.add(key);
322
+ if (expired) {
323
+ expiredFileNames.push(file.name);
324
+ } else {
325
+ retainedUploadIds.add(file.attachmentId);
326
+ }
327
+ appendedFiles.push(restored);
328
+ }
329
+ const capacity = remainingComposerAttachmentSlots(
330
+ composerImagesRef.current.length + composerFilesNow.length,
331
+ pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
332
+ );
333
+ const filesToAppend = appendedFiles.slice(0, capacity);
334
+ const skippedFiles = appendedFiles.slice(capacity);
335
+ unrestoredFileNames = skippedFiles.map((file) => file.name);
336
+ // A non-durable take can resurrect the stash entry after a reload;
337
+ // deleting these uploads would leave it pointing at nothing.
338
+ if (durable) {
339
+ for (const file of duplicateFiles) {
340
+ releasePersistedAttachmentUpload({
341
+ id: file.id,
342
+ environmentId,
343
+ attachmentId: file.attachmentId,
344
+ });
345
+ }
346
+ for (const file of skippedFiles) {
347
+ if (file.uploadedAttachmentId) {
348
+ releasePersistedAttachmentUpload({
349
+ id: file.id,
350
+ environmentId,
351
+ attachmentId: file.uploadedAttachmentId,
352
+ });
353
+ }
354
+ }
355
+ }
356
+ const restoredFiles = [...markerReplacements, ...filesToAppend];
357
+ if (restoredFiles.length > 0) {
358
+ addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true });
359
+ const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt;
360
+ if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) {
361
+ promptRef.current = restoredFilePrompt;
362
+ setComposerCursor(
363
+ collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length),
364
+ );
365
+ setComposerTrigger(null);
366
+ promptChanged = true;
367
+ }
368
+ restoredFileCount = filesToAppend.length;
369
+ }
370
+ }
371
+
372
+ let unrestoredImageNames: string[] = [];
373
+ if (entry.attachments.length > 0) {
374
+ const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
375
+ // The draft store also dedupes by mimeType+sizeBytes+name, so filter
376
+ // on the same key here. Counting a duplicate against capacity would
377
+ // burn a slot the store then refuses to fill, pushing a genuinely
378
+ // unique image into the overflow list for nothing.
379
+ const existingDedupKeys = new Set(
380
+ composerImagesRef.current.map(
381
+ (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
382
+ ),
383
+ );
384
+ const capacity = remainingComposerAttachmentSlots(
385
+ composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
386
+ pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
387
+ );
388
+ const pending = entry.attachments.filter(
389
+ (attachment) =>
390
+ !existingIds.has(attachment.id) &&
391
+ !existingDedupKeys.has(
392
+ `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`,
393
+ ),
394
+ );
395
+ unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name);
396
+ const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity));
397
+ if (restoredImages.length > 0) {
398
+ addComposerDraftImages(composerDraftTarget, restoredImages);
399
+ }
400
+ }
401
+
402
+ const missingImageReasons: string[] = [];
403
+ if (entry.droppedImageNames.length > 0) {
404
+ missingImageReasons.push(
405
+ `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
406
+ );
407
+ }
408
+ if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
409
+ missingImageReasons.push(
410
+ `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
411
+ );
412
+ }
413
+ if (unrestoredImageNames.length > 0) {
414
+ missingImageReasons.push(
415
+ `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
416
+ );
417
+ }
418
+ if (unrestoredFileNames.length > 0) {
419
+ missingImageReasons.push(
420
+ `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
421
+ );
422
+ }
423
+ if (expiredFileNames.length > 0) {
424
+ missingImageReasons.push(
425
+ `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`,
426
+ );
427
+ }
428
+ if (missingImageReasons.length > 0) {
429
+ toastManager.add({
430
+ type: "warning",
431
+ title: "Some attachments were not restored",
432
+ description: missingImageReasons.join(" "),
433
+ });
434
+ }
435
+
436
+ if (promptChanged) {
437
+ window.requestAnimationFrame(() => {
438
+ composerEditorRef.current?.focusAtEnd();
439
+ });
440
+ }
441
+ };
442
+ const restoreStashEntryStable = useStableCallback(restoreStashEntry);
443
+
444
+ const deleteStashEntry = (entry: PromptStashEntry) => {
445
+ const { entry: removed, durable } = takeStashEntry(entry.id);
446
+ if (!stashQueue.some((candidate) => candidate.id !== entry.id)) {
447
+ setIsStashMenuOpen(false);
448
+ }
449
+ if (durable && removed) {
450
+ for (const file of removed.files ?? []) {
451
+ releasePersistedAttachmentUpload({
452
+ id: file.id,
453
+ environmentId: file.environmentId,
454
+ attachmentId: file.attachmentId,
455
+ });
456
+ }
457
+ }
458
+ if (!durable) {
459
+ toastManager.add({
460
+ type: "warning",
461
+ title: "Stash entry may come back",
462
+ description:
463
+ "Browser storage rejected the delete, so this prompt could reappear after a reload.",
464
+ data: { hideCopyButton: true },
465
+ });
466
+ }
467
+ };
468
+ const deleteStashEntryStable = useStableCallback(deleteStashEntry);
469
+
470
+ const stashCurrentPrompt = async () => {
471
+ // Stashing clears the draft. A pasted attachment still downloading would then land in the
472
+ // emptied composer instead of travelling with the entry it belongs to.
473
+ if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
474
+ toastManager.add({
475
+ type: "info",
476
+ title: "Still bringing attached context into this message.",
477
+ description: "Stash again once its chip resolves.",
478
+ });
479
+ return;
480
+ }
481
+ const prompt = promptRef.current.trim();
482
+ const images = [...composerImagesRef.current];
483
+ const files = [...composerFilesRef.current];
484
+ const stashedRecords: ComposerContextRecord[] = [
485
+ ...composerThreadContexts,
486
+ ...composerTerminalContextsRef.current.map(terminalContextRecord),
487
+ ...composerReviewComments.map(reviewCommentContextRecord),
488
+ ...composerPreviewAnnotations.map((annotation) =>
489
+ previewAnnotationContextRecord(annotation, {
490
+ screenshotContextId: images.some((image) => image.id === annotation.id)
491
+ ? annotation.id
492
+ : undefined,
493
+ }),
494
+ ),
495
+ ];
496
+ if (prompt.length === 0 && images.length === 0 && files.length === 0) {
497
+ const entries = usePromptStashStore.getState().entries;
498
+ const entry = entries.length === 1 ? entries[0] : undefined;
499
+ if (entry && !entry.pendingImageCount) {
500
+ await restoreStashEntry(entry);
501
+ } else {
502
+ setIsStashMenuOpen((open) => !open);
503
+ }
504
+ return;
505
+ }
506
+ const stashedFiles: PersistedComposerFileAttachment[] = [];
507
+ for (const file of files) {
508
+ if (composerFileNeedsReattach(file)) {
509
+ toastManager.add({
510
+ type: "error",
511
+ title: "Attach dropped files again or remove them before stashing",
512
+ });
513
+ return;
514
+ }
515
+ const upload = readAttachmentUpload(file.id);
516
+ if (upload?.status !== "ready" || upload.environmentId !== environmentId) {
517
+ toastManager.add({
518
+ type: "error",
519
+ title: "Wait for file uploads before stashing this prompt",
520
+ });
521
+ return;
522
+ }
523
+ stashedFiles.push({
524
+ id: file.id,
525
+ name: file.name,
526
+ mimeType: file.mimeType,
527
+ sizeBytes: file.sizeBytes,
528
+ attachmentId: upload.attachmentId,
529
+ environmentId,
530
+ ...(file.source ? { source: file.source } : {}),
531
+ });
532
+ }
533
+ // A repeat ⌘S on the *same* still-unencoded snapshot would stash it
534
+ // twice. Guard on the snapshot itself rather than a bare boolean: once
535
+ // the composer has been cleared the user can type something genuinely
536
+ // new (or switch threads) while encoding continues, and that deserves its
537
+ // own entry.
538
+ const attachmentKey = images
539
+ .map((image) => `image:${image.id}`)
540
+ .concat(files.map((file) => `file:${file.id}`))
541
+ .join(",");
542
+ const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n");
543
+ if (stashInFlightRef.current.has(snapshotKey)) return;
544
+ stashInFlightRef.current.add(snapshotKey);
545
+
546
+ const stashTarget = composerDraftTarget;
547
+ const entryId = randomUUID();
548
+ const stashAndEncode = async () => {
549
+ // Ordering matters in both directions: writing before clearing means a
550
+ // crash or closed tab mid-encode still leaves the prompt recoverable,
551
+ // while clearing before the async image work means edits typed during
552
+ // encoding are not wiped.
553
+ const { evicted, written, durable } = stashEntryToQueue({
554
+ id: entryId,
555
+ createdAt: new Date().toISOString(),
556
+ prompt,
557
+ attachments: [],
558
+ ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}),
559
+ droppedImageNames: [],
560
+ unreadableImageNames: [],
561
+ pendingImageCount: images.length,
562
+ ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}),
563
+ });
564
+
565
+ // If it was rejected (quota) the store has already rolled itself back,
566
+ // so leave the composer untouched rather than making it the second
567
+ // casualty of a reload.
568
+ if (!written) {
569
+ toastManager.add({
570
+ type: "error",
571
+ title: "Could not stash this prompt",
572
+ description:
573
+ "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",
574
+ data: { hideCopyButton: true },
575
+ });
576
+ return;
577
+ }
578
+ if (!durable) {
579
+ toastManager.add({
580
+ type: "warning",
581
+ title: "Stashed prompt will not survive a reload",
582
+ description:
583
+ "Browser storage is unavailable, so this stash is kept in memory only for this session.",
584
+ data: { hideCopyButton: true },
585
+ });
586
+ }
587
+
588
+ promptRef.current = "";
589
+ clearComposerDraftPromptAndImages(stashTarget);
590
+ clearComposerDraftTerminalContexts(stashTarget);
591
+ setComposerDraftThreadContexts(stashTarget, []);
592
+ for (const comment of composerReviewComments) {
593
+ removeComposerDraftReviewComment(stashTarget, comment.id);
594
+ }
595
+ for (const annotation of composerPreviewAnnotations) {
596
+ releaseAttachmentUpload(annotation.id);
597
+ removeComposerDraftPreviewAnnotation(stashTarget, annotation.id);
598
+ }
599
+ setComposerDraftPrompt(stashTarget, "");
600
+ for (const image of images) {
601
+ releaseAttachmentUpload(image.id);
602
+ }
603
+ setComposerCursor(0);
604
+ setComposerTrigger(null);
605
+ pulseStashBadge();
606
+
607
+ if (evicted) {
608
+ for (const file of evicted.files ?? []) {
609
+ releasePersistedAttachmentUpload({
610
+ id: file.id,
611
+ environmentId: file.environmentId,
612
+ attachmentId: file.attachmentId,
613
+ });
614
+ }
615
+ toastManager.add({
616
+ type: "warning",
617
+ title: "Oldest stashed prompt discarded",
618
+ description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,
619
+ data: { hideCopyButton: true },
620
+ });
621
+ }
622
+
623
+ // Images are re-encoded for the stash rather than stored verbatim: the
624
+ // composer allows up to 10MB per image, but localStorage gives the whole
625
+ // origin ~5MB.
626
+ const candidateAttachments: PersistedComposerImageAttachment[] = [];
627
+ const oversizedImageNames: string[] = [];
628
+ const unreadableImageNames: string[] = [];
629
+ for (const image of images) {
630
+ const result = await compressImageForStash(image.file);
631
+ if (!result.ok) {
632
+ (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push(
633
+ image.name,
634
+ );
635
+ continue;
636
+ }
637
+ candidateAttachments.push({
638
+ id: image.id,
639
+ name: image.name,
640
+ mimeType: result.image.mimeType,
641
+ sizeBytes: result.image.sizeBytes,
642
+ dataUrl: result.image.dataUrl,
643
+ ...(image.source
644
+ ? { source: resizeSnapShotSource(image.source, result.image.imageSize) }
645
+ : {}),
646
+ });
647
+ }
648
+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);
649
+
650
+ const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
651
+ attachments: kept,
652
+ droppedImageNames: [...oversizedImageNames, ...droppedNames],
653
+ unreadableImageNames,
654
+ });
655
+ if (attached) {
656
+ if (!imagesDurable && durable && images.length > 0) {
657
+ toastManager.add({
658
+ type: "warning",
659
+ title: "Stashed images were not saved",
660
+ description:
661
+ "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.",
662
+ data: { hideCopyButton: true },
663
+ });
664
+ }
665
+ } else if (kept.length > 0) {
666
+ toastManager.add({
667
+ type: "warning",
668
+ title: "Stashed images did not attach",
669
+ description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`,
670
+ data: { hideCopyButton: true },
671
+ });
672
+ }
673
+ };
674
+ await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey));
675
+ };
676
+ const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
677
+
678
+ const toggleStashMenu = () => {
679
+ if (isComposerCollapsedMobile) {
680
+ expandMobileComposer();
681
+ setIsStashMenuOpen(true);
682
+ return;
683
+ }
684
+ setIsStashMenuOpen((open) => !open);
685
+ };
686
+ const toggleStashMenuStable = useStableCallback(toggleStashMenu);
687
+
688
+ const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen });
689
+ if (
690
+ stashMenuClosesOn.prompt !== prompt ||
691
+ stashMenuClosesOn.composerMenuOpen !== composerMenuOpen
692
+ ) {
693
+ setStashMenuClosesOn({ prompt, composerMenuOpen });
694
+ if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
695
+ }
696
+
697
+ useEffect(() => {
698
+ const handler = (event: globalThis.KeyboardEvent) => {
699
+ const command = resolveShortcutCommand(event, keybindings, {
700
+ context: {
701
+ terminalFocus: getTerminalFocusOwner() !== null,
702
+ terminalOpen,
703
+ modelPickerOpen: isComposerModelPickerOpen,
704
+ },
705
+ });
706
+ if (command !== "composer.stash") return;
707
+ // Always claim the shortcut so the browser save dialog never opens,
708
+ // even when the composer is in a state that can't stash.
709
+ event.preventDefault();
710
+ event.stopPropagation();
711
+ if (isCommandPaletteOpen() || isRevertingCheckpoint) {
712
+ return;
713
+ }
714
+ if (pendingUserInputs.length > 0) {
715
+ setIsStashMenuOpen((open) => !open);
716
+ return;
717
+ }
718
+ if (projectSelectionRequired || activePendingProgress !== null) {
719
+ return;
720
+ }
721
+ void stashCurrentPromptStable();
722
+ };
723
+ window.addEventListener("keydown", handler, true);
724
+ return () => window.removeEventListener("keydown", handler, true);
725
+ }, [
726
+ activePendingProgress,
727
+ isComposerModelPickerOpen,
728
+ keybindings,
729
+ pendingUserInputs.length,
730
+ projectSelectionRequired,
731
+ stashCurrentPromptStable,
732
+ isRevertingCheckpoint,
733
+ terminalOpen,
734
+ ]);
735
+
736
+ return {
737
+ stashQueue,
738
+ isStashMenuOpen,
739
+ setIsStashMenuOpen,
740
+ stashPulse,
741
+ restoreStashEntryStable,
742
+ deleteStashEntryStable,
743
+ toggleStashMenuStable,
744
+ };
745
+}