Skip to content

Commit 69fcddd

Browse files
t3dotggclaude
andcommitted
refactor(web): drop cross-tab handling from the prompt stash
No other persisted store in the app (composer drafts included) does cross-tab merging or storage-event syncing — they are all last-write-wins — and the machinery added for it here caused more bugs across review rounds than the two-tabs-stashing-simultaneously edge case it guarded against. Remove it and match the sibling stores: mutate in-memory state, persist it, hydrate once at startup. Kept, because they fix real single-tab bugs: synchronous immediate writes (the composer clears on the strength of the write landing, which a debounce timer cannot honestly report), durability reporting including the non-durable in-memory fallback, rollback of a rejected stash write, and settling stale pendingImageCount on hydration. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent f0abec9 commit 69fcddd

2 files changed

Lines changed: 89 additions & 181 deletions

File tree

‎apps/web/src/promptStashStore.test.ts‎

Lines changed: 12 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import {
1717

1818
const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent");
1919
const CODEX_INSTANCE = ProviderInstanceId.make("codex");
20-
const OLDER_TIMESTAMP = "2026-07-24T11:00:00.000Z";
2120

2221
function makeEntry(input: {
2322
id: string;
@@ -229,68 +228,21 @@ describe("promptStashStore", () => {
229228
expect(attached).toBe(false);
230229
});
231230

232-
/** Writes a queue straight to storage, as another tab would. */
233-
function seedStorage(scopeKey: string, entries: ReadonlyArray<PromptStashEntry>) {
234-
writePromptStashStorageForTest(
235-
JSON.stringify({ version: 1, state: { queuesByScopeKey: { [scopeKey]: entries } } }),
236-
);
237-
}
238-
239-
it("keeps another tab's entries when stashing", () => {
231+
it("settles a pending count left behind by a crashed or closed session", () => {
240232
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
241-
seedStorage(scopeKey, [{ ...makeEntry({ id: "from-other-tab" }), createdAt: OLDER_TIMESTAMP }]);
242-
243-
usePromptStashStore.getState().stashEntry(makeEntry({ id: "from-this-tab" }));
244-
245-
const ids = (usePromptStashStore.getState().queuesByScopeKey[scopeKey] ?? []).map(
246-
(entry) => entry.id,
247-
);
248-
expect(ids).toEqual(["from-this-tab", "from-other-tab"]);
249-
});
250-
251-
// The previous id-union merge could not tell "another tab created this"
252-
// from "this tab deleted it", so deletes came back. Reading disk as the
253-
// source of truth removes the ambiguity.
254-
it("does not resurrect an entry another tab deleted", () => {
255-
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
256-
const store = usePromptStashStore.getState();
257-
store.stashEntry(makeEntry({ id: "doomed" }));
258-
// The other tab deletes it and writes the emptied queue.
259-
seedStorage(scopeKey, []);
260-
261-
store.stashEntry(makeEntry({ id: "fresh" }));
262-
263-
const ids = (usePromptStashStore.getState().queuesByScopeKey[scopeKey] ?? []).map(
264-
(entry) => entry.id,
265-
);
266-
expect(ids).toEqual(["fresh"]);
267-
expect(ids).not.toContain("doomed");
268-
});
269-
270-
it("does not clobber another tab's finalized images when taking an entry", () => {
271-
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
272-
const store = usePromptStashStore.getState();
273-
store.stashEntry(makeEntry({ id: "mine" }));
274-
// Another tab adds an entry after this one's in-memory state was built.
275-
seedStorage(scopeKey, [
276-
{ ...makeEntry({ id: "mine" }), createdAt: OLDER_TIMESTAMP },
277-
{ ...makeEntry({ id: "theirs" }), createdAt: OLDER_TIMESTAMP },
278-
]);
279-
280-
store.takeEntry(scopeKey, "mine");
281-
282-
const ids = (usePromptStashStore.getState().queuesByScopeKey[scopeKey] ?? []).map(
283-
(entry) => entry.id,
233+
writePromptStashStorageForTest(
234+
JSON.stringify({
235+
version: 1,
236+
state: {
237+
queuesByScopeKey: {
238+
[scopeKey]: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
239+
},
240+
},
241+
}),
284242
);
285-
expect(ids).toEqual(["theirs"]);
286-
});
287-
288-
it("settles a pending count left behind by a closed tab", () => {
289-
const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
290-
seedStorage(scopeKey, [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }]);
291243

292-
// Any read of persisted state must settle the stale count, or the entry
293-
// would stay stuck showing "saving…" and refuse to restore.
244+
// Hydration must settle the stale count, or the entry would stay stuck
245+
// showing "saving…" with images that no longer exist anywhere.
294246
const entry = usePromptStashStore.getState().queuesByScopeKey[scopeKey]?.[0];
295247
expect(entry?.pendingImageCount).toBe(0);
296248
expect(entry?.unreadableImageNames).toHaveLength(2);

‎apps/web/src/promptStashStore.ts‎

Lines changed: 77 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -163,31 +163,20 @@ function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
163163
const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage();
164164

165165
/**
166-
* Reads the queues currently on disk, settling any stale pending counts.
166+
* Persists the queues, immediately rather than debounced. Stashing is a
167+
* deliberate, infrequent keystroke — not a per-character autosave — so there
168+
* is nothing to coalesce, and the caller clears the composer on the strength
169+
* of this write landing, which a debounce timer cannot honestly report.
167170
*
168-
* Disk — not this tab's memory — is the source of truth for every mutation.
169-
* A union of the two could never distinguish "another tab added this entry"
170-
* from "this tab deleted it", which would resurrect deletions; reading the
171-
* live state and mutating *that* sidesteps the question entirely.
171+
* Returns whether the write will survive a reload: false on a quota rejection
172+
* or when only the in-memory fallback is available.
172173
*/
173-
function readPersistedQueues(): Record<string, ReadonlyArray<PromptStashEntry>> | null {
174-
try {
175-
// Read the backing store directly: the debounced wrapper's getItem is
176-
// typed as possibly-async, and this has to resolve synchronously inside a
177-
// store mutation.
178-
const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);
179-
if (typeof raw !== "string" || raw.length === 0) return null;
180-
const parsed: unknown = JSON.parse(raw);
181-
const state = (parsed as { state?: unknown } | null)?.state;
182-
if (!state) return null;
183-
return clearOrphanedPendingImages(decodePersistedPromptStashState(state).queuesByScopeKey);
184-
} catch {
185-
return null;
186-
}
187-
}
188-
189-
/** Serializes queues in the exact envelope zustand's persist middleware uses. */
190-
function writePersistedQueues(queues: Record<string, ReadonlyArray<PromptStashEntry>>): boolean {
174+
function persistQueues(queues: Record<string, ReadonlyArray<PromptStashEntry>>): {
175+
/** The write succeeded (possibly only into the in-memory fallback). */
176+
written: boolean;
177+
/** The write will survive a reload. */
178+
durable: boolean;
179+
} {
191180
try {
192181
baseStashStorage.setItem(
193182
PROMPT_STASH_STORAGE_KEY,
@@ -196,47 +185,25 @@ function writePersistedQueues(queues: Record<string, ReadonlyArray<PromptStashEn
196185
state: { queuesByScopeKey: queues },
197186
}),
198187
);
199-
return true;
188+
return { written: true, durable: storageIsDurable };
200189
} catch (error) {
201190
console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error);
202-
return false;
191+
return { written: false, durable: false };
203192
}
204193
}
205194

206-
/**
207-
* Applies `mutate` to the queues currently on disk and writes the result back
208-
* synchronously, so concurrent tabs cannot clobber each other: each mutation
209-
* starts from whatever the other tab last wrote.
210-
*
211-
* Writes are immediate rather than debounced. Stashing is a deliberate,
212-
* infrequent keystroke — not a per-character autosave — so there is nothing to
213-
* coalesce, and a debounce window is exactly where cross-tab races live.
214-
*
215-
* Returns the mutation's own result plus whether the write reached disk.
216-
*/
217-
function commitQueues<T>(
218-
localQueues: Record<string, ReadonlyArray<PromptStashEntry>>,
219-
mutate: (queues: Record<string, ReadonlyArray<PromptStashEntry>>) => {
220-
next: Record<string, ReadonlyArray<PromptStashEntry>>;
221-
result: T;
222-
},
223-
): {
224-
next: Record<string, ReadonlyArray<PromptStashEntry>>;
225-
result: T;
226-
/** The write itself succeeded (possibly only in memory). */
227-
written: boolean;
228-
/** The write will survive a reload. */
229-
durable: boolean;
230-
} {
231-
// Fall back to this tab's state only when there is nothing readable on disk
232-
// (first write of the session, blocked storage, corrupt payload).
233-
const base = readPersistedQueues() ?? localQueues;
234-
const { next, result } = mutate(base);
235-
// The write still happens against the in-memory fallback so the stash works
236-
// within the session; `durable` reports only whether it will survive a
237-
// reload, which is what callers gate composer-clearing on.
238-
const written = writePersistedQueues(next);
239-
return { next, result, written, durable: written && storageIsDurable };
195+
/** Reads the persisted queues, settling stale pending counts. */
196+
function readPersistedQueues(): Record<string, ReadonlyArray<PromptStashEntry>> | null {
197+
try {
198+
const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);
199+
if (typeof raw !== "string" || raw.length === 0) return null;
200+
const parsed: unknown = JSON.parse(raw);
201+
const state = (parsed as { state?: unknown } | null)?.state;
202+
if (!state) return null;
203+
return clearOrphanedPendingImages(decodePersistedPromptStashState(state).queuesByScopeKey);
204+
} catch {
205+
return null;
206+
}
240207
}
241208

242209
interface PromptStashStoreState {
@@ -280,87 +247,76 @@ export const usePromptStashStore = create<PromptStashStoreState>()((set, get) =>
280247
queuesByScopeKey: {},
281248
stashEntry: (entry) => {
282249
const scopeKey = promptStashScopeKey(entry.providerInstanceId);
283-
const { next, result, written, durable } = commitQueues(get().queuesByScopeKey, (queues) => {
284-
const nextQueue = [entry, ...readQueue(queues, scopeKey)];
285-
const evicted =
286-
nextQueue.length > MAX_STASH_ENTRIES_PER_QUEUE ? (nextQueue.pop() ?? null) : null;
287-
return { next: { ...queues, [scopeKey]: nextQueue }, result: evicted };
288-
});
289-
// A rejected write must not leave the entry visible in this tab: the
290-
// caller keeps the composer intact on failure, so showing a stashed
291-
// copy too would duplicate the prompt.
292-
set(() => ({ queuesByScopeKey: written ? next : (readPersistedQueues() ?? {}) }));
293-
return { evicted: written ? result : null, durable };
250+
const queues = get().queuesByScopeKey;
251+
const nextQueue = [entry, ...readQueue(queues, scopeKey)];
252+
const evicted =
253+
nextQueue.length > MAX_STASH_ENTRIES_PER_QUEUE ? (nextQueue.pop() ?? null) : null;
254+
const next = { ...queues, [scopeKey]: nextQueue };
255+
const { written, durable } = persistQueues(next);
256+
// A rejected write must not leave the entry visible either: the caller
257+
// keeps the composer intact on failure, so a stashed copy would
258+
// duplicate the prompt. Eviction likewise only sticks on success.
259+
if (!written) {
260+
return { evicted: null, durable: false };
261+
}
262+
set(() => ({ queuesByScopeKey: next }));
263+
return { evicted, durable };
294264
},
295265
takeEntry: (scopeKey, entryId) => {
296-
const { next, result, durable } = commitQueues(get().queuesByScopeKey, (queues) => {
297-
const queue = readQueue(queues, scopeKey);
298-
const entry = queue.find((candidate) => candidate.id === entryId) ?? null;
299-
if (!entry) return { next: queues, result: null };
300-
const nextQueue = queue.filter((candidate) => candidate.id !== entryId);
301-
const nextQueues = { ...queues };
302-
if (nextQueue.length === 0) {
303-
delete nextQueues[scopeKey];
304-
} else {
305-
nextQueues[scopeKey] = nextQueue;
306-
}
307-
return { next: nextQueues, result: entry };
308-
});
266+
const queues = get().queuesByScopeKey;
267+
const queue = readQueue(queues, scopeKey);
268+
const entry = queue.find((candidate) => candidate.id === entryId) ?? null;
269+
if (!entry) return { entry: null, durable: true };
270+
const nextQueue = queue.filter((candidate) => candidate.id !== entryId);
271+
const next = { ...queues };
272+
if (nextQueue.length === 0) {
273+
delete next[scopeKey];
274+
} else {
275+
next[scopeKey] = nextQueue;
276+
}
277+
const { durable } = persistQueues(next);
309278
set(() => ({ queuesByScopeKey: next }));
310-
return { entry: result, durable };
279+
return { entry, durable };
311280
},
312281
finalizeEntryImages: (scopeKey, entryId, images) => {
313-
const { next, result, durable } = commitQueues(get().queuesByScopeKey, (queues) => {
314-
const queue = readQueue(queues, scopeKey);
315-
const index = queue.findIndex((candidate) => candidate.id === entryId);
316-
const existing = index === -1 ? undefined : queue[index];
317-
// Restored or deleted mid-encode: nothing to attach to.
318-
if (!existing) return { next: queues, result: false };
319-
const nextQueue = [...queue];
320-
nextQueue[index] = {
321-
...existing,
322-
attachments: images.attachments,
323-
droppedImageNames: images.droppedImageNames,
324-
unreadableImageNames: images.unreadableImageNames,
325-
pendingImageCount: 0,
326-
};
327-
return { next: { ...queues, [scopeKey]: nextQueue }, result: true };
328-
});
282+
const queues = get().queuesByScopeKey;
283+
const queue = readQueue(queues, scopeKey);
284+
const index = queue.findIndex((candidate) => candidate.id === entryId);
285+
const existing = index === -1 ? undefined : queue[index];
286+
// Restored or deleted mid-encode: nothing to attach to.
287+
if (!existing) return { attached: false, durable: true };
288+
const nextQueue = [...queue];
289+
nextQueue[index] = {
290+
...existing,
291+
attachments: images.attachments,
292+
droppedImageNames: images.droppedImageNames,
293+
unreadableImageNames: images.unreadableImageNames,
294+
pendingImageCount: 0,
295+
};
296+
const next = { ...queues, [scopeKey]: nextQueue };
297+
const { durable } = persistQueues(next);
329298
set(() => ({ queuesByScopeKey: next }));
330-
return { attached: result, durable };
299+
return { attached: true, durable };
331300
},
332301
}));
333302

334-
/**
335-
* Refreshes the in-memory queues from disk. Mutations already read-modify-write
336-
* synchronously, so this only matters for picking up another tab's changes.
337-
*/
338-
function syncQueuesFromStorage(): void {
303+
// Hydrate once at startup. Like the app's other persisted stores, tabs are
304+
// last-write-wins: no cross-tab merging or storage-event syncing.
305+
{
339306
const persisted = readPersistedQueues();
340307
if (persisted) {
341308
usePromptStashStore.setState({ queuesByScopeKey: persisted });
342309
}
343310
}
344311

345-
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
346-
// Hydrate once at startup, then follow other tabs. `storage` fires only in
347-
// *other* tabs, which is exactly the case this tab cannot observe itself.
348-
syncQueuesFromStorage();
349-
window.addEventListener("storage", (event) => {
350-
if (event.key === null || event.key === PROMPT_STASH_STORAGE_KEY) {
351-
syncQueuesFromStorage();
352-
}
353-
});
354-
}
355-
356312
export const EMPTY_PROMPT_STASH_QUEUE: ReadonlyArray<PromptStashEntry> = [];
357313

358314
/**
359-
* Test seam: writes the raw persisted payload through the same storage the
360-
* store reads, so cross-tab behavior can be exercised without a real
361-
* `localStorage` global. Pass an empty string to clear.
315+
* Test seam: seeds the persisted payload through the same storage the store
316+
* reads and rehydrates, without needing a real `localStorage` global.
317+
* Pass an empty string to clear.
362318
*/
363319
export function writePromptStashStorageForTest(raw: string): void {
364320
baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw);
365-
syncQueuesFromStorage();
321+
usePromptStashStore.setState({ queuesByScopeKey: readPersistedQueues() ?? {} });
366322
}

0 commit comments

Comments
 (0)