Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

promptStashStore.ts

322 lines12.4 KB

1import { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { create } from "zustand";
4​
5import { PersistedComposerImageAttachment } from "./composerDraftStore";
6import { createMemoryStorage, type StateStorage } from "./lib/storage";
7​
8export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1";
9const PROMPT_STASH_STORAGE_VERSION = 1;
10​
11/**
12 * Queue bucket for prompts stashed while no provider instance is selected.
13 *
14 * Provider-scoped keys are prefixed (see `promptStashScopeKey`), so this
15 * sentinel can never collide with a provider literally named `__none__`.
16 */
17export const PROMPT_STASH_UNSCOPED_KEY = "__none__";
18/** Namespace applied to provider-derived keys to keep them collision-proof. */
19const PROVIDER_SCOPE_PREFIX = "provider:";
20​
21export const MAX_STASH_ENTRIES_PER_QUEUE = 20;
22/**
23 * Budget for an entry's serialized attachment payload. localStorage is a
24 * ~5MB origin-wide quota shared with the composer draft store, so oversized
25 * images are dropped (tracked in `droppedImageNames`) rather than persisted.
26 *
27 * Sized to hold two images at the per-image compression budget
28 * (`MAX_STASH_IMAGE_DATA_URL_CHARS`) so a typical before/after screenshot
29 * pair survives intact.
30 */
31export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000;
32​
33const StashEntrySchema = Schema.Struct({
34 id: Schema.String,
35 createdAt: Schema.String,
36 prompt: Schema.String,
37 attachments: Schema.Array(PersistedComposerImageAttachment),
38 providerInstanceId: Schema.NullOr(ProviderInstanceId),
39 modelSelection: Schema.NullOr(ModelSelection),
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 queuesByScopeKey: Schema.Record(Schema.String, 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 queues: Record<string, ReadonlyArray<PromptStashEntry>>,
78): Record<string, ReadonlyArray<PromptStashEntry>> {
79 const next: Record<string, ReadonlyArray<PromptStashEntry>> = {};
80 for (const [scopeKey, queue] of Object.entries(queues)) {
81 next[scopeKey] = queue.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 return next;
99​
100/** Maps the composer's active provider instance to a stash queue bucket. */
101export function promptStashScopeKey(instanceId: ProviderInstanceId | null | undefined): string {
102 return instanceId ? `${PROVIDER_SCOPE_PREFIX}${instanceId}` : PROMPT_STASH_UNSCOPED_KEY;
104​
105/**
106 * Reads a queue without inheriting from `Object.prototype`. Scope keys derive
107 * from user-authored provider slugs, so a key like `__proto__` must not
108 * resolve to the prototype chain.
109 */
110function readQueue(
111 queues: Record<string, ReadonlyArray<PromptStashEntry>>,
112 scopeKey: string,
113): ReadonlyArray<PromptStashEntry> {
114 return Object.hasOwn(queues, scopeKey) ? (queues[scopeKey] ?? []) : [];
116​
117/**
118 * Splits candidate attachments into a persistable set within the entry
119 * budget plus the names of any that had to be dropped. Attachments are
120 * admitted in order so the earliest-added images win.
121 */
122export function partitionStashAttachments(
123 attachments: ReadonlyArray<PersistedComposerImageAttachment>,
124): {
125 kept: PersistedComposerImageAttachment[];
126 droppedNames: string[];
127} {
128 const kept: PersistedComposerImageAttachment[] = [];
129 const droppedNames: string[] = [];
130 let usedChars = 0;
131 for (const attachment of attachments) {
132 if (usedChars + attachment.dataUrl.length > MAX_STASH_ENTRY_ATTACHMENT_CHARS) {
133 droppedNames.push(attachment.name);
134 continue;
135 }
136 usedChars += attachment.dataUrl.length;
137 kept.push(attachment);
138 }
139 return { kept, droppedNames };
141​
142/**
143 * Reading the `localStorage` property itself can throw `SecurityError` when
144 * storage is blocked by policy or the page is a sandboxed iframe — so the
145 * access has to be guarded, not just the get/set calls on it. Otherwise
146 * importing this module would crash the app at load.
147 *
148 * `durable` is false for the in-memory fallback: writes there "succeed" but
149 * vanish on reload, and callers clear the composer on the strength of a
150 * successful stash, so they must be told the difference.
151 */
152function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
153 try {
154 if (typeof localStorage !== "undefined") {
155 return { storage: localStorage, durable: true };
156 }
157 } catch {
158 // Fall through to the in-memory store.
159 }
160 return { storage: createMemoryStorage(), durable: false };
162​
163const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage();
164​
165/**
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.
170 *
171 * Returns whether the write will survive a reload: false on a quota rejection
172 * or when only the in-memory fallback is available.
173 */
174function 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} {
180 try {
181 baseStashStorage.setItem(
182 PROMPT_STASH_STORAGE_KEY,
183 JSON.stringify({
184 version: PROMPT_STASH_STORAGE_VERSION,
185 state: { queuesByScopeKey: queues },
186 }),
187 );
188 return { written: true, durable: storageIsDurable };
189 } catch (error) {
190 console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error);
191 return { written: false, durable: false };
192 }
194​
195/** Reads the persisted queues, settling stale pending counts. */
196function 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 }
208​
209interface PromptStashStoreState {
210 queuesByScopeKey: Record<string, ReadonlyArray<PromptStashEntry>>;
211 /**
212 * Prepends an entry to its scope's queue, evicting the oldest entry past
213 * the per-queue cap. Returns the evicted entry (for messaging) if any.
214 */
215 stashEntry: (entry: PromptStashEntry) => {
216 evicted: PromptStashEntry | null;
217 /** False when the write did not reach durable storage; nothing was kept. */
218 durable: boolean;
219 };
220 /**
221 * Removes and returns an entry from a scope's queue (restore + delete).
222 * `durable` is false when the removal could not be persisted, meaning a
223 * reload would resurrect the entry.
224 */
225 takeEntry: (
226 scopeKey: string,
227 entryId: string,
228 ) => { entry: PromptStashEntry | null; durable: boolean };
229 /**
230 * Attaches the encoded images to an entry written earlier by `stashEntry`,
231 * clearing its pending count. Returns attached=false when the entry is gone
232 * (restored or deleted while encoding was still running) so the caller can
233 * tell the user their images did not make it.
234 */
235 finalizeEntryImages: (
236 scopeKey: string,
237 entryId: string,
238 images: {
239 attachments: ReadonlyArray<PersistedComposerImageAttachment>;
240 droppedImageNames: ReadonlyArray<string>;
241 unreadableImageNames: ReadonlyArray<string>;
242 },
243 ) => { attached: boolean; durable: boolean };
245​
246export const usePromptStashStore = create<PromptStashStoreState>()((set, get) => ({
247 queuesByScopeKey: {},
248 stashEntry: (entry) => {
249 const scopeKey = promptStashScopeKey(entry.providerInstanceId);
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 };
264 },
265 takeEntry: (scopeKey, entryId) => {
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);
278 set(() => ({ queuesByScopeKey: next }));
279 return { entry, durable };
280 },
281 finalizeEntryImages: (scopeKey, entryId, images) => {
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);
298 set(() => ({ queuesByScopeKey: next }));
299 return { attached: true, durable };
300 },
301}));
302​
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.
306 const persisted = readPersistedQueues();
307 if (persisted) {
308 usePromptStashStore.setState({ queuesByScopeKey: persisted });
309 }
311​
312export const EMPTY_PROMPT_STASH_QUEUE: ReadonlyArray<PromptStashEntry> = [];
313​
314/**
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.
318 */
319export function writePromptStashStorageForTest(raw: string): void {
320 baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw);
321 usePromptStashStore.setState({ queuesByScopeKey: readPersistedQueues() ?? {} });