@@ -163,31 +163,20 @@ function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
163163const { 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
242209interface 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-
356312export 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 */
363319export function writePromptStashStorageForTest ( raw : string ) : void {
364320 baseStashStorage . setItem ( PROMPT_STASH_STORAGE_KEY , raw ) ;
365- syncQueuesFromStorage ( ) ;
321+ usePromptStashStore . setState ( { queuesByScopeKey : readPersistedQueues ( ) ?? { } } ) ;
366322}
0 commit comments