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

promptStashStore.ts

232 lines8.3 KB

1import { ComposerContextRecord, ForwardCompatibleArray } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { create } from "zustand";
4​
5import {
6 PersistedComposerFileAttachment,
7 PersistedComposerImageAttachment,
8} from "./composerDraftStore";
9import { createMemoryStorage, type StateStorage } from "./lib/storage";
10​
11export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v2";
12const LEGACY_PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v1";
13const PROMPT_STASH_STORAGE_VERSION = 2;
14​
15export const MAX_STASH_ENTRIES = 20;
16/**
17 * Budget for an entry's serialized attachment payload. localStorage is a
18 * ~5MB origin-wide quota shared with the composer draft store, so oversized
19 * images are dropped (tracked in `droppedImageNames`) rather than persisted.
20 */
21export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000;
22​
23const StashEntrySchema = Schema.Struct({
24 id: Schema.String,
25 createdAt: Schema.String,
26 prompt: Schema.String,
27 attachments: Schema.Array(PersistedComposerImageAttachment),
28 files: Schema.optionalKey(Schema.Array(PersistedComposerFileAttachment)),
29 droppedImageNames: Schema.Array(Schema.String),
30 unreadableImageNames: Schema.optionalKey(Schema.Array(Schema.String)),
31 pendingImageCount: Schema.optionalKey(Schema.Number),
32 records: Schema.optionalKey(ForwardCompatibleArray(ComposerContextRecord)),
33});
34export type PromptStashEntry = typeof StashEntrySchema.Type;
35​
36const PersistedPromptStashState = Schema.Struct({
37 entries: Schema.Array(StashEntrySchema),
38});
39type PersistedPromptStashState = typeof PersistedPromptStashState.Type;
40​
41const decodePersistedPromptStashState = Schema.decodeUnknownSync(PersistedPromptStashState);
42​
43/**
44 * `pendingImageCount` only has meaning within the session that wrote it: the
45 * encode loop that would clear it does not survive a reload. Any entry that
46 * comes back from storage still pending was orphaned by a closed tab or a
47 * crash mid-encode, so the count is settled here — otherwise the entry would
48 * be stuck showing "saving…" and refuse to restore forever.
49 */
50function clearOrphanedPendingImages(
51 entries: ReadonlyArray<PromptStashEntry>,
52): ReadonlyArray<PromptStashEntry> {
53 return entries.map((entry) => {
54 if (!entry.pendingImageCount) return entry;
55 const lostCount = entry.pendingImageCount;
56 return {
57 ...entry,
58 pendingImageCount: 0,
59 unreadableImageNames: [
60 ...(entry.unreadableImageNames ?? []),
61 ...Array.from(
62 { length: lostCount },
63 (_, index) => `image ${index + 1} (not saved before reload)`,
64 ),
65 ],
66 };
67 });
69​
70export function partitionStashAttachments(
71 attachments: ReadonlyArray<PersistedComposerImageAttachment>,
72): {
73 kept: PersistedComposerImageAttachment[];
74 droppedNames: string[];
75} {
76 const kept: PersistedComposerImageAttachment[] = [];
77 const droppedNames: string[] = [];
78 let usedChars = 0;
79 for (const attachment of attachments) {
80 if (usedChars + attachment.dataUrl.length > MAX_STASH_ENTRY_ATTACHMENT_CHARS) {
81 droppedNames.push(attachment.name);
82 continue;
83 }
84 usedChars += attachment.dataUrl.length;
85 kept.push(attachment);
86 }
87 return { kept, droppedNames };
89​
90/**
91 * Reading the `localStorage` property itself can throw `SecurityError` when
92 * storage is blocked by policy or the page is a sandboxed iframe — so the
93 * access has to be guarded, not just the get/set calls on it.
94 */
95function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
96 try {
97 if (typeof localStorage !== "undefined") {
98 return { storage: localStorage, durable: true };
99 }
100 } catch {}
101 return { storage: createMemoryStorage(), durable: false };
103​
104const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage();
105​
106/**
107 * Persists the queue, immediately rather than debounced. Stashing is a
108 * deliberate, infrequent keystroke — not a per-character autosave — so there
109 * is nothing to coalesce, and the caller clears the composer on the strength
110 * of this write landing, which a debounce timer cannot honestly report.
111 */
112function persistEntries(entries: ReadonlyArray<PromptStashEntry>): {
113 written: boolean;
114 durable: boolean;
115} {
116 try {
117 baseStashStorage.setItem(
118 PROMPT_STASH_STORAGE_KEY,
119 JSON.stringify({
120 version: PROMPT_STASH_STORAGE_VERSION,
121 state: { entries },
122 }),
123 );
124 return { written: true, durable: storageIsDurable };
125 } catch (error) {
126 console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error);
127 return { written: false, durable: false };
128 }
130​
131function readPersistedEntries(): ReadonlyArray<PromptStashEntry> | null {
132 try {
133 const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);
134 if (typeof raw !== "string" || raw.length === 0) return null;
135 const parsed: unknown = JSON.parse(raw);
136 const state = (parsed as { state?: unknown } | null)?.state;
137 if (!state) return null;
138 return clearOrphanedPendingImages(decodePersistedPromptStashState(state).entries);
139 } catch {
140 return null;
141 }
143​
144interface PromptStashStoreState {
145 entries: ReadonlyArray<PromptStashEntry>;
146 stashEntry: (entry: PromptStashEntry) => {
147 evicted: PromptStashEntry | null;
148 /** False when the write failed outright (e.g. quota); nothing was kept. */
149 written: boolean;
150 /**
151 * False when the write will not survive a reload: either it failed, or it
152 * landed only in the in-memory fallback because localStorage is blocked.
153 */
154 durable: boolean;
155 };
156 /**
157 * `durable` is false when the removal could not be persisted, meaning a
158 * reload would resurrect the entry.
159 */
160 takeEntry: (entryId: string) => { entry: PromptStashEntry | null; durable: boolean };
161 /**
162 * Returns attached=false when the entry is gone (restored or deleted while
163 * encoding was still running) so the caller can tell the user their images
164 * did not make it.
165 */
166 finalizeEntryImages: (
167 entryId: string,
168 images: {
169 attachments: ReadonlyArray<PersistedComposerImageAttachment>;
170 droppedImageNames: ReadonlyArray<string>;
171 unreadableImageNames: ReadonlyArray<string>;
172 },
173 ) => { attached: boolean; durable: boolean };
175​
176export const usePromptStashStore = create<PromptStashStoreState>()((set, get) => ({
177 entries: [],
178 stashEntry: (entry) => {
179 const nextEntries = [entry, ...get().entries];
180 const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null;
181 const { written, durable } = persistEntries(nextEntries);
182 // A rejected write must not leave the entry visible either: the caller
183 // keeps the composer intact on failure, so a stashed copy would
184 // duplicate the prompt. Eviction likewise only sticks on success.
185 if (!written) {
186 return { evicted: null, written: false, durable: false };
187 }
188 set(() => ({ entries: nextEntries }));
189 return { evicted, written: true, durable };
190 },
191 takeEntry: (entryId) => {
192 const entries = get().entries;
193 const entry = entries.find((candidate) => candidate.id === entryId) ?? null;
194 if (!entry) return { entry: null, durable: true };
195 const nextEntries = entries.filter((candidate) => candidate.id !== entryId);
196 const { durable } = persistEntries(nextEntries);
197 set(() => ({ entries: nextEntries }));
198 return { entry, durable };
199 },
200 finalizeEntryImages: (entryId, images) => {
201 const entries = get().entries;
202 const index = entries.findIndex((candidate) => candidate.id === entryId);
203 const existing = index === -1 ? undefined : entries[index];
204 if (!existing) return { attached: false, durable: true };
205 const nextEntries = [...entries];
206 nextEntries[index] = {
207 ...existing,
208 attachments: images.attachments,
209 droppedImageNames: images.droppedImageNames,
210 unreadableImageNames: images.unreadableImageNames,
211 pendingImageCount: 0,
212 };
213 const { durable } = persistEntries(nextEntries);
214 set(() => ({ entries: nextEntries }));
215 return { attached: true, durable };
216 },
217}));
218​
220 try {
221 baseStashStorage.removeItem(LEGACY_PROMPT_STASH_STORAGE_KEY);
222 } catch {}
223 const persisted = readPersistedEntries();
224 if (persisted) {
225 usePromptStashStore.setState({ entries: persisted });
226 }
228​
229export function writePromptStashStorageForTest(raw: string): void {
230 baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw);
231 usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] });