Open History to see the last commit
1import * as Schema from "effect/Schema";
2import { create } from "zustand";
3
4import {
5 PersistedComposerFileAttachment,
6 PersistedComposerImageAttachment,
7} from "./composerDraftStore";
8import { createMemoryStorage, type StateStorage } from "./lib/storage";
9
10export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v2";
11/**
12 * v1 bucketed entries into per-provider-instance queues and stored a model
13 * selection with each prompt. The stash is provider-agnostic now, so the old
14 * payload is deleted at startup rather than migrated — left behind it would
15 * silently hold megabytes of the origin's ~5MB localStorage quota forever.
16 */
17const LEGACY_PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1";
18const PROMPT_STASH_STORAGE_VERSION = 2;
19
20export const MAX_STASH_ENTRIES = 20;
21/**
22 * Budget for an entry's serialized attachment payload. localStorage is a
23 * ~5MB origin-wide quota shared with the composer draft store, so oversized
24 * images are dropped (tracked in `droppedImageNames`) rather than persisted.
25 *
26 * Sized to hold two images at the per-image compression budget
27 * (`MAX_STASH_IMAGE_DATA_URL_CHARS`) so a typical before/after screenshot
28 * pair survives intact.
29 */
30export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000;
31
32/**
33 * Stashed files keep signed-upload references instead of storing their bytes.
34 * Image payloads remain subject to the localStorage budget.
35 */
36const StashEntrySchema = Schema.Struct({
37 id: Schema.String,
38 createdAt: Schema.String,
39 prompt: Schema.String,
40 attachments: Schema.Array(PersistedComposerImageAttachment),
41 files: Schema.optionalKey(Schema.Array(PersistedComposerFileAttachment)),
42 /** Names of images that exceeded the attachment budget and were not saved. */
43 droppedImageNames: Schema.Array(Schema.String),
44 /**
45 * Names of images that could not be decoded or re-encoded at all — a
46 * distinct failure from exceeding the size budget, so the menu can explain
47 * which actually happened. Optional: entries written before this field
48 * existed decode without it.
49 */
50 unreadableImageNames: Schema.optionalKey(Schema.Array(Schema.String)),
51 /**
52 * Images still being encoded when the entry was written. The entry is
53 * persisted before its images so a crash mid-encode cannot lose the prompt;
54 * this field lets the UI show "N images still saving" until
55 * `finalizeEntryImages` lands, and flags entries orphaned by a reload.
56 */
57 pendingImageCount: Schema.optionalKey(Schema.Number),
58});
59export type PromptStashEntry = typeof StashEntrySchema.Type;
60
61const PersistedPromptStashState = Schema.Struct({
62 entries: Schema.Array(StashEntrySchema),
63});
64type PersistedPromptStashState = typeof PersistedPromptStashState.Type;
65
66const decodePersistedPromptStashState = Schema.decodeUnknownSync(PersistedPromptStashState);
67
68/**
69 * `pendingImageCount` only has meaning within the session that wrote it: the
70 * encode loop that would clear it does not survive a reload. Any entry that
71 * comes back from storage still pending was orphaned by a closed tab or a
72 * crash mid-encode, so the count is settled here — otherwise the entry would
73 * be stuck showing "saving…" and refuse to restore forever.
74 *
75 * The images are genuinely gone (they were never written), so they are
76 * recorded as unreadable to keep the prompt itself restorable.
77 */
78function clearOrphanedPendingImages(
79 entries: ReadonlyArray<PromptStashEntry>,
80): ReadonlyArray<PromptStashEntry> {
81 return entries.map((entry) => {
82 if (!entry.pendingImageCount) return entry;
83 const lostCount = entry.pendingImageCount;
84 return {
85 ...entry,
86 pendingImageCount: 0,
87 unreadableImageNames: [
88 ...(entry.unreadableImageNames ?? []),
89 ...Array.from(
90 { length: lostCount },
91 (_, index) => `image ${index + 1} (not saved before reload)`,
92 ),
93 ],
94 };
95 });
96}
97
98/**
99 * Splits candidate attachments into a persistable set within the entry
100 * budget plus the names of any that had to be dropped. Attachments are
101 * admitted in order so the earliest-added images win.
102 */
103export function partitionStashAttachments(
104 attachments: ReadonlyArray<PersistedComposerImageAttachment>,
105): {
106 kept: PersistedComposerImageAttachment[];
107 droppedNames: string[];
108} {
109 const kept: PersistedComposerImageAttachment[] = [];
110 const droppedNames: string[] = [];
111 let usedChars = 0;
112 for (const attachment of attachments) {
113 if (usedChars + attachment.dataUrl.length > MAX_STASH_ENTRY_ATTACHMENT_CHARS) {
114 droppedNames.push(attachment.name);
115 continue;
116 }
117 usedChars += attachment.dataUrl.length;
118 kept.push(attachment);
119 }
120 return { kept, droppedNames };
121}
122
123/**
124 * Reading the `localStorage` property itself can throw `SecurityError` when
125 * storage is blocked by policy or the page is a sandboxed iframe — so the
126 * access has to be guarded, not just the get/set calls on it. Otherwise
127 * importing this module would crash the app at load.
128 *
129 * `durable` is false for the in-memory fallback: writes there "succeed" but
130 * vanish on reload, and callers clear the composer on the strength of a
131 * successful stash, so they must be told the difference.
132 */
133function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
134 try {
135 if (typeof localStorage !== "undefined") {
136 return { storage: localStorage, durable: true };
137 }
138 } catch {
139 // Fall through to the in-memory store.
140 }
141 return { storage: createMemoryStorage(), durable: false };
142}
143
144const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage();
145
146/**
147 * Persists the queue, immediately rather than debounced. Stashing is a
148 * deliberate, infrequent keystroke — not a per-character autosave — so there
149 * is nothing to coalesce, and the caller clears the composer on the strength
150 * of this write landing, which a debounce timer cannot honestly report.
151 *
152 * Returns whether the write will survive a reload: false on a quota rejection
153 * or when only the in-memory fallback is available.
154 */
155function persistEntries(entries: ReadonlyArray<PromptStashEntry>): {
156 /** The write succeeded (possibly only into the in-memory fallback). */
157 written: boolean;
158 /** The write will survive a reload. */
159 durable: boolean;
160} {
161 try {
162 baseStashStorage.setItem(
163 PROMPT_STASH_STORAGE_KEY,
164 JSON.stringify({
165 version: PROMPT_STASH_STORAGE_VERSION,
166 state: { entries },
167 }),
168 );
169 return { written: true, durable: storageIsDurable };
170 } catch (error) {
171 console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error);
172 return { written: false, durable: false };
173 }
174}
175
176/** Reads the persisted queue, settling stale pending counts. */
177function readPersistedEntries(): ReadonlyArray<PromptStashEntry> | null {
178 try {
179 const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);
180 if (typeof raw !== "string" || raw.length === 0) return null;
181 const parsed: unknown = JSON.parse(raw);
182 const state = (parsed as { state?: unknown } | null)?.state;
183 if (!state) return null;
184 return clearOrphanedPendingImages(decodePersistedPromptStashState(state).entries);
185 } catch {
186 return null;
187 }
188}
189
190interface PromptStashStoreState {
191 entries: ReadonlyArray<PromptStashEntry>;
192 /**
193 * Prepends an entry to the queue, evicting the oldest entry past the cap.
194 * Returns the evicted entry (for messaging) if any.
195 */
196 stashEntry: (entry: PromptStashEntry) => {
197 evicted: PromptStashEntry | null;
198 /** False when the write failed outright (e.g. quota); nothing was kept. */
199 written: boolean;
200 /**
201 * False when the write will not survive a reload: either it failed, or it
202 * landed only in the in-memory fallback because localStorage is blocked.
203 */
204 durable: boolean;
205 };
206 /**
207 * Removes and returns an entry from the queue (restore + delete).
208 * `durable` is false when the removal could not be persisted, meaning a
209 * reload would resurrect the entry.
210 */
211 takeEntry: (entryId: string) => { entry: PromptStashEntry | null; durable: boolean };
212 /**
213 * Attaches the encoded images to an entry written earlier by `stashEntry`,
214 * clearing its pending count. Returns attached=false when the entry is gone
215 * (restored or deleted while encoding was still running) so the caller can
216 * tell the user their images did not make it.
217 */
218 finalizeEntryImages: (
219 entryId: string,
220 images: {
221 attachments: ReadonlyArray<PersistedComposerImageAttachment>;
222 droppedImageNames: ReadonlyArray<string>;
223 unreadableImageNames: ReadonlyArray<string>;
224 },
225 ) => { attached: boolean; durable: boolean };
226}
227
228export const usePromptStashStore = create<PromptStashStoreState>()((set, get) => ({
229 entries: [],
230 stashEntry: (entry) => {
231 const nextEntries = [entry, ...get().entries];
232 const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null;
233 const { written, durable } = persistEntries(nextEntries);
234 // A rejected write must not leave the entry visible either: the caller
235 // keeps the composer intact on failure, so a stashed copy would
236 // duplicate the prompt. Eviction likewise only sticks on success.
237 if (!written) {
238 return { evicted: null, written: false, durable: false };
239 }
240 set(() => ({ entries: nextEntries }));
241 return { evicted, written: true, durable };
242 },
243 takeEntry: (entryId) => {
244 const entries = get().entries;
245 const entry = entries.find((candidate) => candidate.id === entryId) ?? null;
246 if (!entry) return { entry: null, durable: true };
247 const nextEntries = entries.filter((candidate) => candidate.id !== entryId);
248 const { durable } = persistEntries(nextEntries);
249 set(() => ({ entries: nextEntries }));
250 return { entry, durable };
251 },
252 finalizeEntryImages: (entryId, images) => {
253 const entries = get().entries;
254 const index = entries.findIndex((candidate) => candidate.id === entryId);
255 const existing = index === -1 ? undefined : entries[index];
256 // Restored or deleted mid-encode: nothing to attach to.
257 if (!existing) return { attached: false, durable: true };
258 const nextEntries = [...entries];
259 nextEntries[index] = {
260 ...existing,
261 attachments: images.attachments,
262 droppedImageNames: images.droppedImageNames,
263 unreadableImageNames: images.unreadableImageNames,
264 pendingImageCount: 0,
265 };
266 const { durable } = persistEntries(nextEntries);
267 set(() => ({ entries: nextEntries }));
268 return { attached: true, durable };
269 },
270}));
271
272// Hydrate once at startup. Like the app's other persisted stores, tabs are
273// last-write-wins: no cross-tab merging or storage-event syncing.
274{
275 try {
276 baseStashStorage.removeItem(LEGACY_PROMPT_STASH_STORAGE_KEY);
277 } catch {
278 // Purging the v1 payload is best-effort; a storage policy that rejects
279 // the delete must not take down module init.
280 }
281 const persisted = readPersistedEntries();
282 if (persisted) {
283 usePromptStashStore.setState({ entries: persisted });
284 }
285}
286
287/**
288 * Test seam: seeds the persisted payload through the same storage the store
289 * reads and rehydrates, without needing a real `localStorage` global.
290 * Pass an empty string to clear.
291 */
292export function writePromptStashStorageForTest(raw: string): void {
293 baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw);
294 usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] });
295}