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