feat(web): prompt stash — cmd+S saves the composer to a per-provider queue #4453
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 8 commits into
main fromrefs/pull/4453/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/chat/ChatComposer.tsx line 2077OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2057,21 @@2057+ playStashGhost(2058+ prompt.length > 0 ? prompt : `${images.length} image${images.length === 1 ? "" : "s"}`,2059+ );2060+2061+ toastManager.add({2062+ type: "success",2063+ title: `Stashed to ${stashProviderLabel}`,2064+ description:2065+ allDroppedNames.length > 02066+ ? `Saved without ${allDroppedNames.join(", ")} (too large to stash).`2067+ : evicted2068+ ? "Oldest stashed prompt was discarded to make room."2069+ : "Press ⌘S in an empty composer to bring it back.",2070+ actionProps: {2071+ children: "Undo",2072+ onClick: () => {2073+ restoreStashEntry(entry);2074+ },2075+ },2076+ data: { hideCopyButton: true },2077+ });apps/web/src/components/chat/ChatComposer.tsx line 2005Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +1931,21 @@1931+ setIsStashMenuOpen(false);1932+1933+ const currentPrompt = promptRef.current;1934+ const nextPrompt = currentPrompt.trim().length1935+ ? `${currentPrompt.replace(/\s+$/, "")}\n\n${entry.prompt}`1936+ : entry.prompt;1937+ promptRef.current = nextPrompt;1938+ setComposerDraftPrompt(composerDraftTarget, nextPrompt);1939+ const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);1940+ setComposerCursor(nextCursor);1941+ setComposerTrigger(null);1942+1943+ if (entry.attachments.length > 0) {1944+ const existingIds = new Set(composerImagesRef.current.map((image) => image.id));1945+ const capacity = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - composerImagesRef.current.length;1946+ const restoredImages = hydrateImagesFromPersisted(1947+ entry.attachments.filter((attachment) => !existingIds.has(attachment.id)),1948+ ).slice(0, Math.max(0, capacity));1949+ if (restoredImages.length > 0) {1950+ addComposerDraftImages(composerDraftTarget, restoredImages);1951+ }apps/web/src/components/chat/ChatComposer.tsx line 2047OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2027,21 @@2027+ id: image.id,2028+ name: image.name,2029+ mimeType: image.mimeType,2030+ sizeBytes: image.sizeBytes,2031+ dataUrl: await readFileAsDataUrl(image.file),2032+ });2033+ } catch {2034+ unreadableImageNames.push(image.name);2035+ }2036+ }2037+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2038+ const allDroppedNames = [...droppedNames, ...unreadableImageNames];2039+2040+ const entry: PromptStashEntry = {2041+ id: randomUUID(),2042+ createdAt: new Date().toISOString(),2043+ prompt,2044+ attachments: kept,2045+ providerInstanceId: stashScopeInstanceId,2046+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2047+ droppedImageNames: allDroppedNames,apps/web/src/components/chat/ChatComposer.tsx line 2053OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2033,21 @@2033+ } catch {2034+ unreadableImageNames.push(image.name);2035+ }2036+ }2037+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2038+ const allDroppedNames = [...droppedNames, ...unreadableImageNames];2039+2040+ const entry: PromptStashEntry = {2041+ id: randomUUID(),2042+ createdAt: new Date().toISOString(),2043+ prompt,2044+ attachments: kept,2045+ providerInstanceId: stashScopeInstanceId,2046+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2047+ droppedImageNames: allDroppedNames,2048+ };2049+ const evicted = stashEntryToQueue(entry);2050+ flushPromptStashStorage();2051+2052+ promptRef.current = "";2053+ clearComposerDraftContent(composerDraftTarget);
- apps/web/src/promptStashStore.ts line 128OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +108,21 @@108+ });109+}110+111+interface PromptStashStoreState {112+ queuesByScopeKey: Record<string, ReadonlyArray<PromptStashEntry>>;113+ /**114+ * Prepends an entry to its scope's queue, evicting the oldest entry past115+ * the per-queue cap. Returns the evicted entry (for messaging) if any.116+ */117+ stashEntry: (entry: PromptStashEntry) => PromptStashEntry | null;118+ /** Removes and returns an entry from a scope's queue (restore + delete). */119+ takeEntry: (scopeKey: string, entryId: string) => PromptStashEntry | null;120+}121+122+export const usePromptStashStore = create<PromptStashStoreState>()(123+ persist(124+ (set, get) => ({125+ queuesByScopeKey: {},126+ stashEntry: (entry) => {127+ const scopeKey = promptStashScopeKey(entry.providerInstanceId);128+ const queue = get().queuesByScopeKey[scopeKey] ?? [];apps/web/src/promptStashStore.ts line 101Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +24,21 @@24+const StashEntrySchema = Schema.Struct({25+ id: Schema.String,26+ createdAt: Schema.String,27+ prompt: Schema.String,28+ attachments: Schema.Array(PersistedComposerImageAttachment),29+ providerInstanceId: Schema.NullOr(ProviderInstanceId),30+ modelSelection: Schema.NullOr(ModelSelection),31+ /** Names of images that exceeded the attachment budget and were not saved. */32+ droppedImageNames: Schema.Array(Schema.String),33+});34+export type PromptStashEntry = typeof StashEntrySchema.Type;35+36+const PersistedPromptStashState = Schema.Struct({37+ queuesByScopeKey: Schema.Record(Schema.String, Schema.Array(StashEntrySchema)),38+});39+type PersistedPromptStashState = typeof PersistedPromptStashState.Type;40+41+const decodePersistedPromptStashState = Schema.decodeUnknownSync(PersistedPromptStashState);42+43+/** Maps the composer's active provider instance to a stash queue bucket. */44+export function promptStashScopeKey(instanceId: ProviderInstanceId | null | undefined): string {apps/web/src/components/chat/ComposerStashMenu.tsx lines 72 to 83Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +53,21 @@53+ onClose();54+ return;55+ }56+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {57+ if (entries.length === 0) return;58+ event.preventDefault();59+ event.stopPropagation();60+ const currentIndex = entries.findIndex((entry) => entry.id === highlightedId);61+ const offset = event.key === "ArrowDown" ? 1 : -1;62+ const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;63+ const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;64+ setHighlightedId(entries[nextIndex]?.id ?? null);65+ return;66+ }67+ if (event.key === "Enter") {68+ if (!highlightedEntry) return;69+ event.preventDefault();70+ event.stopPropagation();71+ onRestore(highlightedEntry);72+ return;73+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/promptStashStore.ts lines 128 to 133OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +113,21 @@113+ base.setItem(name, value);114+ } catch (error) {115+ console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error);116+ }117+ },118+ removeItem: (name) => {119+ try {120+ base.removeItem(name);121+ } catch (error) {122+ console.error("[PROMPT-STASH] Could not remove stash entry.", error);123+ }124+ },125+ };126+}127+128+const promptStashDebouncedStorage = createDebouncedStorage(129+ createQuotaSafeStorage(130+ typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),131+ ),132+ PROMPT_STASH_PERSIST_DEBOUNCE_MS,133+);apps/web/src/lib/stashImageCompression.ts lines 218 to 245Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +181,21 @@181+ }182+183+ let bitmap: ImageBitmap;184+ try {185+ bitmap = await createImageBitmap(file);186+ } catch {187+ return null;188+ }189+190+ try {191+ for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {192+ const encoded = await encodeWithinBudget(bitmap, MAX_DIMENSION * dimensionScale, budgetChars);193+ if (encoded && encoded.dataUrl.length <= budgetChars) {194+ return {195+ dataUrl: encoded.dataUrl,196+ mimeType: encoded.mimeType,197+ sizeBytes: dataUrlByteLength(encoded.dataUrl),198+ recompressed: true,199+ };200+ }201+ }
- apps/web/src/components/chat/ChatComposer.tsx line 2108OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2088,21 @@2088+ } catch {2089+ unreadableImageNames.push(image.name);2090+ }2091+ }2092+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2093+2094+ const entry: PromptStashEntry = {2095+ id: randomUUID(),2096+ createdAt: new Date().toISOString(),2097+ prompt,2098+ attachments: kept,2099+ providerInstanceId: stashScopeInstanceId,2100+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2101+ // Kept separate so the menu can say *why* an image is missing rather2102+ // than blaming everything on the size budget.2103+ droppedImageNames: droppedNames,2104+ unreadableImageNames,2105+ };2106+ stashEntryToQueue(entry);2107+ flushPromptStashStorage();2108+ stashInFlightRef.current = false;apps/web/src/components/chat/ChatComposer.tsx line 2104OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2084,21 @@2084+ mimeType: compressed.mimeType,2085+ sizeBytes: compressed.sizeBytes,2086+ dataUrl: compressed.dataUrl,2087+ });2088+ } catch {2089+ unreadableImageNames.push(image.name);2090+ }2091+ }2092+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2093+2094+ const entry: PromptStashEntry = {2095+ id: randomUUID(),2096+ createdAt: new Date().toISOString(),2097+ prompt,2098+ attachments: kept,2099+ providerInstanceId: stashScopeInstanceId,2100+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2101+ // Kept separate so the menu can say *why* an image is missing rather2102+ // than blaming everything on the size budget.2103+ droppedImageNames: droppedNames,2104+ unreadableImageNames,apps/web/src/components/chat/ChatComposer.tsx line 2108OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2088,21 @@2088+ } catch {2089+ unreadableImageNames.push(image.name);2090+ }2091+ }2092+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2093+2094+ const entry: PromptStashEntry = {2095+ id: randomUUID(),2096+ createdAt: new Date().toISOString(),2097+ prompt,2098+ attachments: kept,2099+ providerInstanceId: stashScopeInstanceId,2100+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2101+ // Kept separate so the menu can say *why* an image is missing rather2102+ // than blaming everything on the size budget.2103+ droppedImageNames: droppedNames,2104+ unreadableImageNames,2105+ };2106+ stashEntryToQueue(entry);2107+ flushPromptStashStorage();2108+ stashInFlightRef.current = false;apps/web/src/components/chat/ChatComposer.tsx line 2107OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2087,21 @@2087+ });2088+ } catch {2089+ unreadableImageNames.push(image.name);2090+ }2091+ }2092+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2093+2094+ const entry: PromptStashEntry = {2095+ id: randomUUID(),2096+ createdAt: new Date().toISOString(),2097+ prompt,2098+ attachments: kept,2099+ providerInstanceId: stashScopeInstanceId,2100+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2101+ // Kept separate so the menu can say *why* an image is missing rather2102+ // than blaming everything on the size budget.2103+ droppedImageNames: droppedNames,2104+ unreadableImageNames,2105+ };2106+ stashEntryToQueue(entry);2107+ flushPromptStashStorage();
- apps/web/src/lib/stashImageCompression.ts line 208Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +188,21 @@188+ ok: true,189+ image: {190+ dataUrl: originalDataUrl,191+ mimeType: file.type,192+ sizeBytes: file.size,193+ recompressed: false,194+ },195+ };196+ }197+ if (!canRecompress()) {198+ return { ok: false, reason: "too-large" };199+ }200+201+ let bitmap: ImageBitmap;202+ try {203+ bitmap = await createImageBitmap(file);204+ } catch {205+ return { ok: false, reason: "unreadable" };206+ }207+208+ try {
- apps/web/src/components/chat/ChatComposer.tsx line 1913Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1861,3 +1891,20 @@18611891 return false;18621892 };186318931894+ // ------------------------------------------------------------------1895+ // Prompt stash (⌘S)1896+ // ------------------------------------------------------------------1897+ const stashScopeInstanceId = noProviderAvailable ? null : selectedInstanceId;1898+ const stashScope = promptStashScopeKey(stashScopeInstanceId);1899+ const stashQueue = usePromptStashStore(1900+ (state) => state.queuesByScopeKey[stashScope] ?? EMPTY_PROMPT_STASH_QUEUE,1901+ );1902+ const stashOtherScopesCount = usePromptStashStore((state) =>1903+ Object.entries(state.queuesByScopeKey).reduce(1904+ (total, [key, queue]) => (key === stashScope ? total : total + queue.length),1905+ 0,1906+ ),1907+ );1908+ const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);1909+ const takeStashEntry = usePromptStashStore((state) => state.takeEntry);1910+ const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);apps/web/src/components/chat/ChatComposer.tsx line 2147Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2060,21 @@2060+ // mid-encode still leaves the prompt recoverable, while clearing before2061+ // the async image work means edits typed during encoding are not wiped.2062+ // Images are appended to the stored entry as they finish encoding.2063+ const evicted = stashEntryToQueue({2064+ id: entryId,2065+ createdAt: new Date().toISOString(),2066+ prompt,2067+ attachments: [],2068+ providerInstanceId: stashScopeInstanceId,2069+ modelSelection: noProviderAvailable ? null : selectedModelSelection,2070+ droppedImageNames: [],2071+ unreadableImageNames: [],2072+ pendingImageCount: images.length,2073+ });2074+ flushPromptStashStorage();2075+2076+ // Only the prompt and images are cleared — terminal/element contexts,2077+ // preview annotations, and review comments are not stashable, so2078+ // destroying them here would be unrecoverable.2079+ promptRef.current = "";2080+ clearComposerDraftPromptAndImages(stashTarget);apps/web/src/components/chat/ChatComposer.tsx line 2130OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2110,21 @@2110+ }2111+ candidateAttachments.push({2112+ id: image.id,2113+ name: image.name,2114+ mimeType: result.image.mimeType,2115+ sizeBytes: result.image.sizeBytes,2116+ dataUrl: result.image.dataUrl,2117+ });2118+ }2119+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2120+2121+ finalizeStashEntryImages(scopeKey, entryId, {2122+ attachments: kept,2123+ droppedImageNames: [...oversizedImageNames, ...droppedNames],2124+ unreadableImageNames,2125+ });2126+ flushPromptStashStorage();2127+ } finally {2128+ // Must clear on every path: a throw that left this set would wedge ⌘S2129+ // until the composer remounts.2130+ stashInFlightRef.current = false;apps/web/src/promptStashStore.ts line 241OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +221,21 @@221+ },222+ finalizeEntryImages: (scopeKey, entryId, images) => {223+ set((state) => {224+ const queue = readQueue(state.queuesByScopeKey, scopeKey);225+ const index = queue.findIndex((candidate) => candidate.id === entryId);226+ // Restored or deleted mid-encode: nothing to attach to.227+ if (index === -1) return state;228+ const existing = queue[index];229+ if (!existing) return state;230+ const nextEntry: PromptStashEntry = {231+ ...existing,232+ attachments: images.attachments,233+ droppedImageNames: images.droppedImageNames,234+ unreadableImageNames: images.unreadableImageNames,235+ pendingImageCount: 0,236+ };237+ const nextQueue = [...queue];238+ nextQueue[index] = nextEntry;239+ return { queuesByScopeKey: { ...state.queuesByScopeKey, [scopeKey]: nextQueue } };240+ });241+ },
- apps/web/src/components/chat/ComposerStashMenu.tsx line 79OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +59,21 @@59+ return;60+ }61+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {62+ if (entries.length === 0) return;63+ event.preventDefault();64+ event.stopPropagation();65+ const currentIndex = entries.findIndex((entry) => entry.id === highlightedId);66+ const offset = event.key === "ArrowDown" ? 1 : -1;67+ const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;68+ const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;69+ setHighlightedId(entries[nextIndex]?.id ?? null);70+ return;71+ }72+ if (event.key === "Enter") {73+ // A focused control inside the row (the delete button) owns its own74+ // activation; swallowing Enter here would restore instead of delete.75+ if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {76+ return;77+ }78+ // Still encoding: restoring now would strand the pending images.79+ if (highlightedEntry?.pendingImageCount) {apps/web/src/promptStashStore.ts line 117OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +97,21 @@97+ const droppedNames: string[] = [];98+ let usedChars = 0;99+ for (const attachment of attachments) {100+ if (usedChars + attachment.dataUrl.length > MAX_STASH_ENTRY_ATTACHMENT_CHARS) {101+ droppedNames.push(attachment.name);102+ continue;103+ }104+ usedChars += attachment.dataUrl.length;105+ kept.push(attachment);106+ }107+ return { kept, droppedNames };108+}109+110+/**111+ * Tracks whether the most recent write actually reached disk. Callers clear112+ * the composer on the strength of a stash write, so "the write silently113+ * failed" has to be observable rather than only logged.114+ */115+let lastWriteFailed = false;116+117+/**
- apps/web/src/components/chat/ComposerStashMenu.tsx line 83OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ event.preventDefault();64+ event.stopPropagation();65+ const currentIndex = entries.findIndex((entry) => entry.id === highlightedId);66+ const offset = event.key === "ArrowDown" ? 1 : -1;67+ const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;68+ const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;69+ setHighlightedId(entries[nextIndex]?.id ?? null);70+ return;71+ }72+ if (event.key === "Enter") {73+ // A focused control inside the row (the delete button) owns its own74+ // activation; swallowing Enter here would restore instead of delete.75+ if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {76+ return;77+ }78+ // Still encoding: restoring now would strand the pending images.79+ if (highlightedEntry?.pendingImageCount) {80+ event.preventDefault();81+ event.stopPropagation();82+ return;83+ }apps/web/src/lib/stashImageCompression.ts line 232Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +205,21 @@205+ return { ok: false, reason: "unreadable" };206+ }207+208+ try {209+ // Each pass shrinks relative to the *previous target*, capped by210+ // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for211+ // images already smaller than that ceiling — the fallback passes would212+ // all resolve to the source size and never actually reduce resolution.213+ const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));214+ for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {215+ const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));216+ let encoded: { dataUrl: string; mimeType: string } | null;217+ try {218+ encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars);219+ } catch {220+ // Canvas allocation, drawing, or the codec itself can throw (OOM on a221+ // huge bitmap, a hostile decoder). Never let that escape: the caller222+ // finalizes the stash entry after this returns, and an exception here223+ // would strand the entry as permanently "still saving".224+ return { ok: false, reason: "unreadable" };225+ }apps/web/src/components/chat/ChatComposer.tsx line 2148OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2128,21 @@2128+ image.name,2129+ );2130+ continue;2131+ }2132+ candidateAttachments.push({2133+ id: image.id,2134+ name: image.name,2135+ mimeType: result.image.mimeType,2136+ sizeBytes: result.image.sizeBytes,2137+ dataUrl: result.image.dataUrl,2138+ });2139+ }2140+ const { kept, droppedNames } = partitionStashAttachments(candidateAttachments);2141+2142+ const finalized = finalizeStashEntryImages(scopeKey, entryId, {2143+ attachments: kept,2144+ droppedImageNames: [...oversizedImageNames, ...droppedNames],2145+ unreadableImageNames,2146+ });2147+ if (finalized) {2148+ flushPromptStashStorage();apps/web/src/components/chat/ChatComposer.tsx line 2059OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2039,21 @@2039+ );2040+2041+ const stashCurrentPrompt = useCallback(async () => {2042+ // Terminal-context placeholders reference live sessions the stash can't2043+ // round-trip, so they are stripped from the stashed prompt.2044+ const prompt = promptRef.current.split(INLINE_TERMINAL_CONTEXT_PLACEHOLDER).join("").trim();2045+ const images = [...composerImagesRef.current];2046+ if (prompt.length === 0 && images.length === 0) {2047+ setIsStashMenuOpen((open) => !open);2048+ return;2049+ }2050+ // A repeat ⌘S while encoding is still running would stash the same2051+ // snapshot twice. The composer is already cleared by then, so the second2052+ // press has nothing new to save.2053+ if (stashInFlightRef.current) return;2054+ stashInFlightRef.current = true;2055+2056+ const stashTarget = composerDraftTarget;2057+ const entryId = randomUUID();2058+ const scopeKey = promptStashScopeKey(stashScopeInstanceId);2059+ // Captured before the write so a rejected persist can be rolled back
- apps/web/src/promptStashStore.ts line 238OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +218,21 @@218+ // store mutation.219+ const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);220+ if (typeof raw !== "string" || raw.length === 0) return null;221+ const parsed: unknown = JSON.parse(raw);222+ const state = (parsed as { state?: unknown } | null)?.state;223+ if (!state) return null;224+ return decodePersistedPromptStashState(state).queuesByScopeKey;225+ } catch {226+ return null;227+ }228+}229+230+/**231+ * Union of the on-disk queues and this tab's, keyed by entry id. Entries are232+ * immutable once finalized, so a plain id-union is sufficient: whichever copy233+ * has images attached wins, and ordering stays newest-first by `createdAt`.234+ */235+function mergeQueuesWithStorage(236+ local: Record<string, ReadonlyArray<PromptStashEntry>>,237+): Record<string, ReadonlyArray<PromptStashEntry>> {238+ const persisted = readPersistedQueues();apps/web/src/promptStashStore.ts line 306OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +286,21 @@286+ */287+ finalizeEntryImages: (288+ scopeKey: string,289+ entryId: string,290+ images: {291+ attachments: ReadonlyArray<PersistedComposerImageAttachment>;292+ droppedImageNames: ReadonlyArray<string>;293+ unreadableImageNames: ReadonlyArray<string>;294+ },295+ ) => boolean;296+}297+298+export const usePromptStashStore = create<PromptStashStoreState>()(299+ persist(300+ (set, get) => ({301+ queuesByScopeKey: {},302+ stashEntry: (entry) => {303+ const scopeKey = promptStashScopeKey(entry.providerInstanceId);304+ // Re-read from storage first: another tab may have stashed since this305+ // one hydrated, and persisting our whole map would erase its entries.306+ const mergedQueues = mergeQueuesWithStorage(get().queuesByScopeKey);
- apps/web/src/components/chat/ChatComposer.tsx line 2105Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1863,0 +2069,21 @@2069+ );2070+2071+ const stashCurrentPrompt = useCallback(async () => {2072+ // Terminal-context placeholders reference live sessions the stash can't2073+ // round-trip, so they are stripped from the stashed prompt.2074+ const prompt = promptRef.current.split(INLINE_TERMINAL_CONTEXT_PLACEHOLDER).join("").trim();2075+ const images = [...composerImagesRef.current];2076+ if (prompt.length === 0 && images.length === 0) {2077+ setIsStashMenuOpen((open) => !open);2078+ return;2079+ }2080+ // A repeat ⌘S on the *same* still-unencoded snapshot would stash it2081+ // twice. Guard on the snapshot itself rather than a bare boolean: once2082+ // the composer has been cleared the user can type something genuinely2083+ // new (or switch threads) while encoding continues, and that deserves its2084+ // own entry.2085+ const snapshotKey = `${String(composerDraftTarget)}


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
fe442759-7c74-402d-873e-bd8a017da3a4You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share