From ad62f1b3fe46ddd4ff490399e334c9a1031d6d29 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:18:38 +0100 Subject: [PATCH 1/7] test(web): reproduce stale prompt stashes across tabs Co-authored-by: GPT 6.2 Sol --- apps/web/src/promptStashStore.test.ts | 75 ++++++++++++++++++- .../stashed-prompt-appears-in-open-tab.e2e.ts | 44 +++++++++++ 2 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 scripts/scenarios/stashed-prompt-appears-in-open-tab.e2e.ts diff --git a/apps/web/src/promptStashStore.test.ts b/apps/web/src/promptStashStore.test.ts index 1e40dfc884bfd..c932684c5d055 100644 --- a/apps/web/src/promptStashStore.test.ts +++ b/apps/web/src/promptStashStore.test.ts @@ -49,6 +49,15 @@ function resetPromptStashStore() { removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY); } +function notifyStorage( + target: EventTarget, + storageArea: ReturnType, + key: string | null = PROMPT_STASH_STORAGE_KEY, + newValue?: string, +) { + target.dispatchEvent(Object.assign(new Event("storage"), { key, storageArea, newValue })); +} + describe("partitionStashAttachments", () => { it("keeps attachments within the budget and reports dropped names in order", () => { const small = { @@ -247,7 +256,9 @@ describe("promptStashStore", () => { it("keeps an entry another tab stashed after this tab loaded", async () => { const sharedStorage = createMemoryStorage(); vi.stubGlobal("localStorage", sharedStorage); - vi.stubGlobal("window", new EventTarget()); + const reader = new EventTarget(); + const writer = new EventTarget(); + vi.stubGlobal("window", reader); vi.resetModules(); try { const thisTab = await import("./promptStashStore"); @@ -255,7 +266,13 @@ describe("promptStashStore", () => { PROMPT_STASH_STORAGE_KEY, JSON.stringify({ version: 2, state: { entries: [makeEntry({ id: "other-tab" })] } }), ); - window.dispatchEvent(Object.assign(new Event("storage"), { key: PROMPT_STASH_STORAGE_KEY })); + notifyStorage(reader, sharedStorage, "another-key"); + notifyStorage(reader, createMemoryStorage()); + expect(thisTab.usePromptStashStore.getState().entries).toEqual([]); + notifyStorage(reader, sharedStorage, PROMPT_STASH_STORAGE_KEY, '{"state":{"entries":[]}}'); + expect(thisTab.usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([ + "other-tab", + ]); thisTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "this-tab" })); @@ -269,14 +286,30 @@ describe("promptStashStore", () => { ...makeEntry({ id: "encoding-image" }), pendingImageCount: 1, }); + vi.stubGlobal("window", writer); vi.resetModules(); const secondTab = await import("./promptStashStore"); + secondTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "while-encoding" })); + notifyStorage(reader, sharedStorage); + expect(thisTab.usePromptStashStore.getState().entries).toMatchObject([ + { id: "while-encoding" }, + { id: "encoding-image", pendingImageCount: 1 }, + { id: "this-tab" }, + { id: "other-tab" }, + ]); + const finalized = makeEntry({ id: "encoding-image", attachmentChars: 12 }).attachments; thisTab.usePromptStashStore.getState().finalizeEntryImages("encoding-image", { attachments: finalized, droppedImageNames: [], unreadableImageNames: [], }); + notifyStorage(writer, sharedStorage); + expect( + secondTab.usePromptStashStore + .getState() + .entries.find((entry) => entry.id === "encoding-image")?.attachments, + ).toEqual(finalized); secondTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "second-tab-new" })); const afterFinalization = JSON.parse( sharedStorage.getItem(PROMPT_STASH_STORAGE_KEY) as string, @@ -292,21 +325,51 @@ describe("promptStashStore", () => { } }); + it.each([PROMPT_STASH_STORAGE_KEY, null])( + "empties the stash when another tab removes its storage (event key %s)", + async (key) => { + const storage = createMemoryStorage(); + vi.stubGlobal("localStorage", storage); + const reader = new EventTarget(); + vi.stubGlobal("window", reader); + vi.resetModules(); + try { + const { usePromptStashStore: store } = await import("./promptStashStore"); + store.getState().stashEntry(makeEntry({ id: "stored" })); + + storage.setItem(PROMPT_STASH_STORAGE_KEY, "{"); + notifyStorage(reader, storage); + expect(store.getState().entries.map((entry) => entry.id)).toEqual(["stored"]); + + storage.removeItem(PROMPT_STASH_STORAGE_KEY); + notifyStorage(reader, storage, key); + expect(store.getState().entries).toEqual([]); + } finally { + vi.unstubAllGlobals(); + vi.resetModules(); + } + }, + ); + it.each(["restore", "take"] as const)( "keeps a failed finalize after another tab stashes, then handles %s", async (action) => { const storage = createMemoryStorage(); - vi.stubGlobal("localStorage", { + const sharedStorage = { ...storage, setItem: (key: string, value: string) => { if (value.includes("rejected-image")) throw new Error("QuotaExceededError"); storage.setItem(key, value); }, - }); + }; + vi.stubGlobal("localStorage", sharedStorage); + const reader = new EventTarget(); + vi.stubGlobal("window", reader); vi.resetModules(); try { const { usePromptStashStore: store } = await import("./promptStashStore"); store.getState().stashEntry({ ...makeEntry({ id: "too-big" }), pendingImageCount: 1 }); + vi.stubGlobal("window", new EventTarget()); vi.resetModules(); const { usePromptStashStore: otherTab } = await import("./promptStashStore"); const { attachments } = makeEntry({ id: "rejected-image", attachmentChars: 4 }); @@ -316,9 +379,13 @@ describe("promptStashStore", () => { durable: false, }); otherTab.getState().stashEntry(makeEntry({ id: "unrelated" })); + notifyStorage(reader, sharedStorage); + expect(store.getState().entries).toMatchObject([{ id: "unrelated" }, { attachments }]); if (action === "take") { otherTab.getState().takeEntry("too-big"); + notifyStorage(reader, sharedStorage); + expect(store.getState().entries.map((entry) => entry.id)).toEqual(["unrelated"]); expect(store.getState().finalizeEntryImages("too-big", images)).toEqual({ attached: false, durable: true, diff --git a/scripts/scenarios/stashed-prompt-appears-in-open-tab.e2e.ts b/scripts/scenarios/stashed-prompt-appears-in-open-tab.e2e.ts new file mode 100644 index 0000000000000..21f5e961876d3 --- /dev/null +++ b/scripts/scenarios/stashed-prompt-appears-in-open-tab.e2e.ts @@ -0,0 +1,44 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A prompt stashed in another tab appears in the open stash menu", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const reader = await t3.thread({ project, title: "Reading", messages: ["first"] }); + const writer = await t3.thread({ project, title: "Writing", messages: ["second"] }); + await t3.open(reader); + + await screen.getByTestId("composer-editor").tap(); + await browser.keyboard.press("Control+s"); + await screen.getByRole("list", "Stashed prompts").waitFor(); + + // A second signed-in document shares storage while keeping its own app state. + await browser.evaluate((threadId) => { + const frame = document.createElement("iframe"); + frame.id = "second-client"; + frame.src = location.pathname.replace(/[^/]+$/, threadId); + frame.style.cssText = + "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647"; + document.body.append(frame); + return null; + }, writer.threadId); + + const other = browser.frameLocator("#second-client"); + const editor = other.getByTestId("composer-editor"); + const prompt = "Draft from the other tab"; + await editor.fill(prompt); + await browser.keyboard.press("Control+s"); + await other.getByRole("button", "Stashed prompts: 1. Open stash.").waitFor(); + await browser.evaluate(() => { + document.querySelector("#second-client")?.remove(); + return null; + }); + + await app.screenshot("stash-after-other-tab-saves"); + await expect(screen.getByRole("button", `Restore stashed prompt: ${prompt}`)).toBeVisible(); + }, +); From 51682406d7aad3a36de038fe33accc6ce16da468 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:19:31 +0100 Subject: [PATCH 2/7] fix(web): refresh the prompt stash across tabs Co-authored-by: GPT 6.2 Sol --- apps/web/src/promptStashStore.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/web/src/promptStashStore.ts b/apps/web/src/promptStashStore.ts index 0afb52eb01838..d50f70696f5d5 100644 --- a/apps/web/src/promptStashStore.ts +++ b/apps/web/src/promptStashStore.ts @@ -110,6 +110,7 @@ function persistEntries(entries: ReadonlyArray): { function readStoredEntries(): ReadonlyArray | null { try { const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY); + if (raw === null) return []; if (typeof raw !== "string" || raw.length === 0) return null; const parsed: unknown = JSON.parse(raw); const state = (parsed as { state?: unknown } | null)?.state; @@ -125,7 +126,7 @@ function readPersistedEntries(): ReadonlyArray | null { } /** - * Starts each write from storage so other tabs' stashes, takes and finalized images survive. + * Reconciles the local queue with storage before writes and after changes in other tabs. * Local encoding and failed finalize writes retain ownership while the stored entry exists. */ function latestEntries(memory: ReadonlyArray): ReadonlyArray { @@ -225,6 +226,18 @@ export const usePromptStashStore = create()((set, get) => } } +if (storageIsDurable && typeof window !== "undefined") { + window.addEventListener("storage", (event) => { + if (event.storageArea !== baseStashStorage) return; + if (event.key !== PROMPT_STASH_STORAGE_KEY && event.key !== null) return; + + // A queued event can describe an older write than the value now in storage. + const { entries } = usePromptStashStore.getState(); + const latest = latestEntries(entries); + if (latest !== entries) usePromptStashStore.setState({ entries: latest }); + }); +} + export function writePromptStashStorageForTest(raw: string): void { baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw); usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] }); From 2c5d0c475b9b2b5bfcdd3e79c9338dab5369205b Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:34:28 +0100 Subject: [PATCH 3/7] fix(web): keep cross-tab stash images pending until saved Co-authored-by: GPT 6.2 Sol --- apps/web/src/promptStashStore.test.ts | 44 +++++++++++++++ apps/web/src/promptStashStore.ts | 77 +++++++++++++++------------ 2 files changed, 86 insertions(+), 35 deletions(-) diff --git a/apps/web/src/promptStashStore.test.ts b/apps/web/src/promptStashStore.test.ts index c932684c5d055..f6abbf870d07c 100644 --- a/apps/web/src/promptStashStore.test.ts +++ b/apps/web/src/promptStashStore.test.ts @@ -325,6 +325,50 @@ describe("promptStashStore", () => { } }); + it("keeps images pending in an open tab until the other tab finishes saving them", async () => { + const storage = createMemoryStorage(); + const readerWindow = new EventTarget(); + vi.stubGlobal("localStorage", storage); + vi.stubGlobal("window", readerWindow); + vi.resetModules(); + try { + const { usePromptStashStore: reader } = await import("./promptStashStore"); + vi.stubGlobal("window", new EventTarget()); + vi.resetModules(); + const { usePromptStashStore: writer } = await import("./promptStashStore"); + const entry = makeEntry({ id: "encoding-in-other-tab" }); + writer.getState().stashEntry({ ...entry, pendingImageCount: 1 }); + notifyStorage(readerWindow, storage); + + expect(reader.getState().entries).toEqual([{ ...entry, pendingImageCount: 1 }]); + + vi.stubGlobal("window", new EventTarget()); + vi.resetModules(); + const { usePromptStashStore: reloaded } = await import("./promptStashStore"); + expect(reloaded.getState().entries[0]).toMatchObject({ + pendingImageCount: 0, + unreadableImageNames: ["image 1 (not saved before reload)"], + }); + reloaded.getState().stashEntry(makeEntry({ id: "unrelated" })); + notifyStorage(readerWindow, storage); + expect(reader.getState().entries[1]).toEqual({ ...entry, pendingImageCount: 1 }); + + const { attachments } = makeEntry({ id: entry.id, attachmentChars: 12 }); + const images = { attachments, droppedImageNames: [], unreadableImageNames: [] }; + expect(writer.getState().finalizeEntryImages(entry.id, images)).toEqual({ + attached: true, + durable: true, + }); + notifyStorage(readerWindow, storage); + const finalizedEntry = { ...entry, ...images, pendingImageCount: 0 }; + expect(reader.getState().entries[1]).toEqual(finalizedEntry); + expect(reader.getState().takeEntry(entry.id).entry).toEqual(finalizedEntry); + } finally { + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + it.each([PROMPT_STASH_STORAGE_KEY, null])( "empties the stash when another tab removes its storage (event key %s)", async (key) => { diff --git a/apps/web/src/promptStashStore.ts b/apps/web/src/promptStashStore.ts index d50f70696f5d5..d73d3b3305a0d 100644 --- a/apps/web/src/promptStashStore.ts +++ b/apps/web/src/promptStashStore.ts @@ -85,6 +85,8 @@ function resolveBaseStorage(): { storage: StateStorage; durable: boolean } { const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage(); const unpersistedFinalizedEntryIds = new Set(); +const recoveredEntryIds = new Set(); +let memoryEntries: ReadonlyArray = []; // Clear the composer only after a durable write; debounce cannot confirm durability. function persistEntries(entries: ReadonlyArray): { @@ -121,34 +123,43 @@ function readStoredEntries(): ReadonlyArray | null { } } -function readPersistedEntries(): ReadonlyArray | null { - return readStoredEntries()?.map(clearOrphanedPendingImages) ?? null; +function recoverEntry(entry: PromptStashEntry): PromptStashEntry { + return recoveredEntryIds.has(entry.id) ? clearOrphanedPendingImages(entry) : entry; +} + +function hydrateEntries() { + const entries = readStoredEntries() ?? []; + recoveredEntryIds.clear(); + for (const entry of entries) { + if (entry.pendingImageCount) recoveredEntryIds.add(entry.id); + } + publishEntries(entries); +} + +function publishEntries(entries: ReadonlyArray) { + // Recovery is local to the loading tab because another tab may still be encoding. + memoryEntries = entries; + usePromptStashStore.setState({ + entries: recoveredEntryIds.size === 0 ? entries : entries.map(recoverEntry), + }); } /** * Reconciles the local queue with storage before writes and after changes in other tabs. - * Local encoding and failed finalize writes retain ownership while the stored entry exists. + * Failed finalize writes retain their local images while the stored entry exists. */ -function latestEntries(memory: ReadonlyArray): ReadonlyArray { +function latestEntries(): ReadonlyArray { const stored = readStoredEntries(); - if (!stored) return memory; + if (!stored) return memoryEntries; + if (unpersistedFinalizedEntryIds.size === 0) return stored; const storedIds = new Set(stored.map((entry) => entry.id)); for (const id of unpersistedFinalizedEntryIds) { if (!storedIds.has(id)) unpersistedFinalizedEntryIds.delete(id); } - const memoryById = new Map(memory.map((entry) => [entry.id, entry])); - return stored.map((entry) => { - const local = memoryById.get(entry.id); - if ( - local && - (local.pendingImageCount || - entry.pendingImageCount || - unpersistedFinalizedEntryIds.has(entry.id)) - ) { - return local; - } - return clearOrphanedPendingImages(entry); - }); + const memoryById = new Map(memoryEntries.map((entry) => [entry.id, entry])); + return stored.map((entry) => + unpersistedFinalizedEntryIds.has(entry.id) ? (memoryById.get(entry.id) ?? entry) : entry, + ); } interface PromptStashStoreState { @@ -173,31 +184,31 @@ interface PromptStashStoreState { ) => { attached: boolean; durable: boolean }; } -export const usePromptStashStore = create()((set, get) => ({ +export const usePromptStashStore = create()(() => ({ entries: [], stashEntry: (entry) => { - const nextEntries = [entry, ...latestEntries(get().entries)]; + const nextEntries = [entry, ...latestEntries()]; const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null; const { written, durable } = persistEntries(nextEntries); // Failed writes must not duplicate the intact composer; eviction also commits only on success. if (!written) { return { evicted: null, written: false, durable: false }; } - set(() => ({ entries: nextEntries })); - return { evicted, written: true, durable }; + publishEntries(nextEntries); + return { evicted: evicted && recoverEntry(evicted), written: true, durable }; }, takeEntry: (entryId) => { - const entries = latestEntries(get().entries); + const entries = latestEntries(); const entry = entries.find((candidate) => candidate.id === entryId) ?? null; if (!entry) return { entry: null, durable: true }; const nextEntries = entries.filter((candidate) => candidate.id !== entryId); const { durable } = persistEntries(nextEntries); unpersistedFinalizedEntryIds.delete(entryId); - set(() => ({ entries: nextEntries })); - return { entry, durable }; + publishEntries(nextEntries); + return { entry: recoverEntry(entry), durable }; }, finalizeEntryImages: (entryId, images) => { - const entries = latestEntries(get().entries); + const entries = latestEntries(); const index = entries.findIndex((candidate) => candidate.id === entryId); const existing = index === -1 ? undefined : entries[index]; if (!existing) return { attached: false, durable: true }; @@ -211,7 +222,7 @@ export const usePromptStashStore = create()((set, get) => }; const { written, durable } = persistEntries(nextEntries); if (!written) unpersistedFinalizedEntryIds.add(entryId); - set(() => ({ entries: nextEntries })); + publishEntries(nextEntries); return { attached: true, durable }; }, })); @@ -220,10 +231,7 @@ export const usePromptStashStore = create()((set, get) => try { baseStashStorage.removeItem(LEGACY_PROMPT_STASH_STORAGE_KEY); } catch {} - const persisted = readPersistedEntries(); - if (persisted) { - usePromptStashStore.setState({ entries: persisted }); - } + hydrateEntries(); } if (storageIsDurable && typeof window !== "undefined") { @@ -232,13 +240,12 @@ if (storageIsDurable && typeof window !== "undefined") { if (event.key !== PROMPT_STASH_STORAGE_KEY && event.key !== null) return; // A queued event can describe an older write than the value now in storage. - const { entries } = usePromptStashStore.getState(); - const latest = latestEntries(entries); - if (latest !== entries) usePromptStashStore.setState({ entries: latest }); + const latest = latestEntries(); + if (latest !== memoryEntries) publishEntries(latest); }); } export function writePromptStashStorageForTest(raw: string): void { baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw); - usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] }); + hydrateEntries(); } From 50cf294c31cb5a761d561508d29206901c497567 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:45:52 +0100 Subject: [PATCH 4/7] fix(web): wait for stashed images before restoring prompts Co-authored-by: GPT 6.2 Sol --- .../src/components/chat/ComposerStashMenu.tsx | 9 +- .../src/components/chat/useComposerStash.ts | 2 +- apps/web/src/promptStashStore.test.ts | 4 +- apps/web/src/promptStashStore.ts | 18 ++-- ...ashed-image-finishes-before-restore.e2e.ts | 85 +++++++++++++++++++ 5 files changed, 107 insertions(+), 11 deletions(-) create mode 100644 scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index c55d843510080..c1bd41f5346b2 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -129,7 +129,7 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { if (!highlightedEntry) return; event.preventDefault(); event.stopPropagation(); - onRestore(highlightedEntry); + if (!highlightedEntry.pendingImageCount) onRestore(highlightedEntry); return; } if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) { @@ -216,13 +216,16 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index b574b8a78eb91..e64d265d9b7c5 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -478,7 +478,7 @@ export function useComposerStash(input: { const restoreStashEntryStable = useStableCallback(restoreStashEntry); const deleteStashEntry = (entry: PromptStashEntry) => { - const { entry: removed, durable } = takeStashEntry(entry.id); + const { entry: removed, durable } = takeStashEntry(entry.id, "delete"); if (!stashQueue.some((candidate) => candidate.id !== entry.id)) { setIsStashMenuOpen(false); } diff --git a/apps/web/src/promptStashStore.test.ts b/apps/web/src/promptStashStore.test.ts index f6abbf870d07c..7a6fc5729381a 100644 --- a/apps/web/src/promptStashStore.test.ts +++ b/apps/web/src/promptStashStore.test.ts @@ -216,7 +216,7 @@ describe("promptStashStore", () => { it("finalizeEntryImages reports false when the entry was already taken", () => { const store = usePromptStashStore.getState(); store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 }); - store.takeEntry("racing"); + store.takeEntry("racing", "delete"); const { attached } = store.finalizeEntryImages("racing", { attachments: [], @@ -240,6 +240,7 @@ describe("promptStashStore", () => { const entry = usePromptStashStore.getState().entries[0]; expect(entry?.pendingImageCount).toBe(0); expect(entry?.unreadableImageNames).toHaveLength(2); + expect(usePromptStashStore.getState().takeEntry("orphan").entry).toEqual(entry); }); it("ignores an unreadable v1 payload seeded under the current key", () => { @@ -338,6 +339,7 @@ describe("promptStashStore", () => { const { usePromptStashStore: writer } = await import("./promptStashStore"); const entry = makeEntry({ id: "encoding-in-other-tab" }); writer.getState().stashEntry({ ...entry, pendingImageCount: 1 }); + expect(reader.getState().takeEntry(entry.id).entry).toBeNull(); notifyStorage(readerWindow, storage); expect(reader.getState().entries).toEqual([{ ...entry, pendingImageCount: 1 }]); diff --git a/apps/web/src/promptStashStore.ts b/apps/web/src/promptStashStore.ts index d73d3b3305a0d..8b6bbd12438c4 100644 --- a/apps/web/src/promptStashStore.ts +++ b/apps/web/src/promptStashStore.ts @@ -171,8 +171,11 @@ interface PromptStashStoreState { /** False for failed writes or in-memory fallback; the entry will not survive reload. */ durable: boolean; }; - /** durable=false means removal was not persisted and reload would restore the entry. */ - takeEntry: (entryId: string) => { entry: PromptStashEntry | null; durable: boolean }; + /** Restore waits for images. durable=false means the entry could reappear after reload. */ + takeEntry: ( + entryId: string, + action?: "restore" | "delete", + ) => { entry: PromptStashEntry | null; durable: boolean }; /** attached=false means the entry disappeared while encoding, so images could not be saved. */ finalizeEntryImages: ( entryId: string, @@ -197,15 +200,18 @@ export const usePromptStashStore = create()(() => ({ publishEntries(nextEntries); return { evicted: evicted && recoverEntry(evicted), written: true, durable }; }, - takeEntry: (entryId) => { + takeEntry: (entryId, action = "restore") => { const entries = latestEntries(); - const entry = entries.find((candidate) => candidate.id === entryId) ?? null; - if (!entry) return { entry: null, durable: true }; + const stored = entries.find((candidate) => candidate.id === entryId); + const entry = stored && recoverEntry(stored); + if (!entry || (action === "restore" && entry.pendingImageCount)) { + return { entry: null, durable: true }; + } const nextEntries = entries.filter((candidate) => candidate.id !== entryId); const { durable } = persistEntries(nextEntries); unpersistedFinalizedEntryIds.delete(entryId); publishEntries(nextEntries); - return { entry: recoverEntry(entry), durable }; + return { entry, durable }; }, finalizeEntryImages: (entryId, images) => { const entries = latestEntries(); diff --git a/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts b/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts new file mode 100644 index 0000000000000..67f8fd241a4ac --- /dev/null +++ b/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts @@ -0,0 +1,85 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "An open stash menu waits for the other tab to finish saving an image before restoring", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const reader = await t3.thread({ project, title: "Reading", messages: ["first"] }); + const writer = await t3.thread({ project, title: "Writing", messages: ["second"] }); + await t3.open(reader); + + const editor = screen.getByTestId("composer-editor"); + await editor.tap(); + await browser.keyboard.press("ControlOrMeta+s"); + const menu = screen.getByRole("list", "Stashed prompts"); + await menu.waitFor(); + + await browser.evaluate((threadId) => { + const frame = document.createElement("iframe"); + frame.id = "stash-writer"; + frame.src = location.pathname.replace(/[^/]+$/, threadId); + frame.style.cssText = + "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647"; + document.body.append(frame); + return null; + }, writer.threadId); + + const other = browser.frameLocator("#stash-writer"); + const prompt = "Keep this screenshot"; + await other.getByTestId("composer-editor").fill(prompt); + await browser.evaluate(async () => { + const frame = document.querySelector("#stash-writer")!; + const canvas = new OffscreenCanvas(10, 10); + canvas.getContext("2d")!.fillRect(0, 0, 10, 10); + const file = new File([await canvas.convertToBlob()], "stash.png", { type: "image/png" }); + const clipboardData = new DataTransfer(); + clipboardData.items.add(file); + frame + .contentDocument!.querySelector('[data-testid="composer-editor"]')! + .dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + return null; + }); + await other.getByRole("button", "Remove stash.png").waitFor(); + + await browser.evaluate(() => { + const writer = + document.querySelector("#stash-writer")!.contentDocument!.defaultView!; + const read = writer.FileReader.prototype.readAsDataURL; + writer.FileReader.prototype.readAsDataURL = function (blob) { + writer.FileReader.prototype.readAsDataURL = read; + writer.addEventListener("finish-stash-image", () => read.call(this, blob), { once: true }); + }; + return null; + }); + await browser.keyboard.press("ControlOrMeta+s"); + + await browser.evaluate(() => { + document.querySelector("#stash-writer")!.hidden = true; + document.querySelector('[data-testid="composer-editor"]')!.focus(); + return null; + }); + const restore = menu.getByRole("button", `Restore stashed prompt: ${prompt}`); + await expect(menu.getByText("saving 1 image…")).toBeVisible(); + await app.screenshot("stash-image-still-saving"); + await browser.keyboard.press("Enter"); + await expect(restore).toBeDisabled(); + await expect(editor).toHaveText(""); + + await browser.evaluate(() => { + document + .querySelector("#stash-writer")! + .contentWindow!.dispatchEvent(new Event("finish-stash-image")); + return null; + }); + await expect(restore).toBeEnabled(); + await restore.tap(); + await expect(editor).toHaveText(prompt); + await expect(screen.getByRole("button", "Remove stash.png")).toBeVisible(); + }, +); From 3df154a6f1c75b553467dbf97804e6652a6f1223 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:46:31 +0100 Subject: [PATCH 5/7] test(web): account for the image chip in the stash label Co-authored-by: GPT 6.2 Sol --- .../scenarios/stashed-image-finishes-before-restore.e2e.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts b/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts index 67f8fd241a4ac..7d6e5f61caf35 100644 --- a/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts +++ b/scripts/scenarios/stashed-image-finishes-before-restore.e2e.ts @@ -64,12 +64,12 @@ test( document.querySelector('[data-testid="composer-editor"]')!.focus(); return null; }); - const restore = menu.getByRole("button", `Restore stashed prompt: ${prompt}`); + const restore = menu.getByRole("button", `Restore stashed prompt: ${prompt}`, { exact: false }); await expect(menu.getByText("saving 1 image…")).toBeVisible(); await app.screenshot("stash-image-still-saving"); await browser.keyboard.press("Enter"); - await expect(restore).toBeDisabled(); await expect(editor).toHaveText(""); + await expect(restore).toBeDisabled(); await browser.evaluate(() => { document @@ -79,7 +79,7 @@ test( }); await expect(restore).toBeEnabled(); await restore.tap(); - await expect(editor).toHaveText(prompt); + await expect(editor).toContainText(prompt); await expect(screen.getByRole("button", "Remove stash.png")).toBeVisible(); }, ); From 8c139c10e1566c09e3b2da4311d1e27da89ad1e2 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:48:18 +0100 Subject: [PATCH 6/7] chore: credit the models that worked on this change Co-authored-by: Claude Opus 5.5 From 557ec718d9f2a1f89bfa552f2bca13fdb518faa5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 20:01:53 +0000 Subject: [PATCH 7/7] fix(web): release stashed images when the encoding tab closes Co-Authored-By: Claude Opus 5.5 --- apps/web/src/promptStashStore.test.ts | 30 +++++++++++++++++++++++++++ apps/web/src/promptStashStore.ts | 14 +++++++++++++ 2 files changed, 44 insertions(+) diff --git a/apps/web/src/promptStashStore.test.ts b/apps/web/src/promptStashStore.test.ts index 7a6fc5729381a..e9e0e57a76a1d 100644 --- a/apps/web/src/promptStashStore.test.ts +++ b/apps/web/src/promptStashStore.test.ts @@ -371,6 +371,36 @@ describe("promptStashStore", () => { } }); + it("lets open tabs restore an entry whose encoding tab closed mid-encode", async () => { + const storage = createMemoryStorage(); + const readerWindow = new EventTarget(); + const writerWindow = new EventTarget(); + vi.stubGlobal("localStorage", storage); + vi.stubGlobal("window", readerWindow); + vi.resetModules(); + try { + const { usePromptStashStore: reader } = await import("./promptStashStore"); + vi.stubGlobal("window", writerWindow); + vi.resetModules(); + const { usePromptStashStore: writer } = await import("./promptStashStore"); + const entry = makeEntry({ id: "closed-mid-encode" }); + writer.getState().stashEntry({ ...entry, pendingImageCount: 1 }); + writer.getState().stashEntry(makeEntry({ id: "settled" })); + + writerWindow.dispatchEvent(new Event("pagehide")); + notifyStorage(readerWindow, storage); + + expect(reader.getState().takeEntry(entry.id).entry).toMatchObject({ + pendingImageCount: 0, + unreadableImageNames: ["image 1 (not saved before reload)"], + }); + expect(reader.getState().entries.map((candidate) => candidate.id)).toEqual(["settled"]); + } finally { + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + it.each([PROMPT_STASH_STORAGE_KEY, null])( "empties the stash when another tab removes its storage (event key %s)", async (key) => { diff --git a/apps/web/src/promptStashStore.ts b/apps/web/src/promptStashStore.ts index 8b6bbd12438c4..99d8527ec8732 100644 --- a/apps/web/src/promptStashStore.ts +++ b/apps/web/src/promptStashStore.ts @@ -86,6 +86,7 @@ const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStor const unpersistedFinalizedEntryIds = new Set(); const recoveredEntryIds = new Set(); +const encodingEntryIds = new Set(); let memoryEntries: ReadonlyArray = []; // Clear the composer only after a durable write; debounce cannot confirm durability. @@ -197,6 +198,7 @@ export const usePromptStashStore = create()(() => ({ if (!written) { return { evicted: null, written: false, durable: false }; } + if (entry.pendingImageCount) encodingEntryIds.add(entry.id); publishEntries(nextEntries); return { evicted: evicted && recoverEntry(evicted), written: true, durable }; }, @@ -210,10 +212,12 @@ export const usePromptStashStore = create()(() => ({ const nextEntries = entries.filter((candidate) => candidate.id !== entryId); const { durable } = persistEntries(nextEntries); unpersistedFinalizedEntryIds.delete(entryId); + encodingEntryIds.delete(entryId); publishEntries(nextEntries); return { entry, durable }; }, finalizeEntryImages: (entryId, images) => { + encodingEntryIds.delete(entryId); const entries = latestEntries(); const index = entries.findIndex((candidate) => candidate.id === entryId); const existing = index === -1 ? undefined : entries[index]; @@ -249,6 +253,16 @@ if (storageIsDurable && typeof window !== "undefined") { const latest = latestEntries(); if (latest !== memoryEntries) publishEntries(latest); }); + // Other open tabs wait on this tab's encoding; tell them it will not finish. + window.addEventListener("pagehide", () => { + if (encodingEntryIds.size === 0) return; + const entries = latestEntries(); + persistEntries( + entries.map((entry) => + encodingEntryIds.has(entry.id) ? clearOrphanedPendingImages(entry) : entry, + ), + ); + }); } export function writePromptStashStorageForTest(raw: string): void {