Open History to see the last commit
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
15// A sanity bound; storage quota is the real limit and reports its own failure.
16export const MAX_STASH_ENTRIES = 100;
17// Share localStorage's ~5MB quota with drafts; record oversized attachments in droppedImageNames.
18export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000;
19
20const StashEntrySchema = Schema.Struct({
21 id: Schema.String,
22 createdAt: Schema.String,
23 prompt: Schema.String,
24 attachments: Schema.Array(PersistedComposerImageAttachment),
25 files: Schema.optionalKey(Schema.Array(PersistedComposerFileAttachment)),
26 droppedImageNames: Schema.Array(Schema.String),
27 unreadableImageNames: Schema.optionalKey(Schema.Array(Schema.String)),
28 pendingImageCount: Schema.optionalKey(Schema.Number),
29 records: Schema.optionalKey(ForwardCompatibleArray(ComposerContextRecord)),
30});
31export type PromptStashEntry = typeof StashEntrySchema.Type;
32
33const PersistedPromptStashState = Schema.Struct({
34 entries: Schema.Array(StashEntrySchema),
35});
36type PersistedPromptStashState = typeof PersistedPromptStashState.Type;
37
38const decodePersistedPromptStashState = Schema.decodeUnknownSync(PersistedPromptStashState);
39
40// Encoders cannot survive reload; clear orphaned counts so entries remain restorable.
41function clearOrphanedPendingImages(entry: PromptStashEntry): PromptStashEntry {
42 if (!entry.pendingImageCount) return entry;
43 return {
44 ...entry,
45 pendingImageCount: 0,
46 unreadableImageNames: [
47 ...(entry.unreadableImageNames ?? []),
48 ...Array.from(
49 { length: entry.pendingImageCount },
50 (_, index) => `image ${index + 1} (not saved before reload)`,
51 ),
52 ],
53 };
54}
55
56export function partitionStashAttachments(
57 attachments: ReadonlyArray<PersistedComposerImageAttachment>,
58): {
59 kept: PersistedComposerImageAttachment[];
60 droppedNames: string[];
61} {
62 const kept: PersistedComposerImageAttachment[] = [];
63 const droppedNames: string[] = [];
64 let usedChars = 0;
65 for (const attachment of attachments) {
66 if (usedChars + attachment.dataUrl.length > MAX_STASH_ENTRY_ATTACHMENT_CHARS) {
67 droppedNames.push(attachment.name);
68 continue;
69 }
70 usedChars += attachment.dataUrl.length;
71 kept.push(attachment);
72 }
73 return { kept, droppedNames };
74}
75
76// Accessing localStorage itself can throw SecurityError before get/set.
77function resolveBaseStorage(): { storage: StateStorage; durable: boolean } {
78 try {
79 if (typeof localStorage !== "undefined") {
80 return { storage: localStorage, durable: true };
81 }
82 } catch {}
83 return { storage: createMemoryStorage(), durable: false };
84}
85
86const { storage: baseStashStorage, durable: storageIsDurable } = resolveBaseStorage();
87
88const unpersistedFinalizedEntryIds = new Set<string>();
89
90// Clear the composer only after a durable write; debounce cannot confirm durability.
91function persistEntries(entries: ReadonlyArray<PromptStashEntry>): {
92 written: boolean;
93 durable: boolean;
94} {
95 try {
96 baseStashStorage.setItem(
97 PROMPT_STASH_STORAGE_KEY,
98 JSON.stringify({
99 version: PROMPT_STASH_STORAGE_VERSION,
100 state: { entries },
101 }),
102 );
103 unpersistedFinalizedEntryIds.clear();
104 return { written: true, durable: storageIsDurable };
105 } catch (error) {
106 console.error("[PROMPT-STASH] Could not persist stash (storage quota?).", error);
107 return { written: false, durable: false };
108 }
109}
110
111function readStoredEntries(): ReadonlyArray<PromptStashEntry> | null {
112 try {
113 const raw = baseStashStorage.getItem(PROMPT_STASH_STORAGE_KEY);
114 if (typeof raw !== "string" || raw.length === 0) return null;
115 const parsed: unknown = JSON.parse(raw);
116 const state = (parsed as { state?: unknown } | null)?.state;
117 if (!state) return null;
118 return decodePersistedPromptStashState(state).entries;
119 } catch {
120 return null;
121 }
122}
123
124function readPersistedEntries(): ReadonlyArray<PromptStashEntry> | null {
125 return readStoredEntries()?.map(clearOrphanedPendingImages) ?? null;
126}
127
128/**
129 * Starts each write from storage so other tabs' stashes, takes and finalized images survive.
130 * Local encoding and failed finalize writes retain ownership while the stored entry exists.
131 */
132function latestEntries(memory: ReadonlyArray<PromptStashEntry>): ReadonlyArray<PromptStashEntry> {
133 const stored = readStoredEntries();
134 if (!stored) return memory;
135 const storedIds = new Set(stored.map((entry) => entry.id));
136 for (const id of unpersistedFinalizedEntryIds) {
137 if (!storedIds.has(id)) unpersistedFinalizedEntryIds.delete(id);
138 }
139 const memoryById = new Map(memory.map((entry) => [entry.id, entry]));
140 return stored.map((entry) => {
141 const local = memoryById.get(entry.id);
142 if (
143 local &&
144 (local.pendingImageCount ||
145 entry.pendingImageCount ||
146 unpersistedFinalizedEntryIds.has(entry.id))
147 ) {
148 return local;
149 }
150 return clearOrphanedPendingImages(entry);
151 });
152}
153
154interface PromptStashStoreState {
155 entries: ReadonlyArray<PromptStashEntry>;
156 stashEntry: (entry: PromptStashEntry) => {
157 /** True when the stash already holds MAX_STASH_ENTRIES; nothing was written. */
158 full: boolean;
159 /** False when the write failed outright (e.g. quota or a full stash); nothing was kept. */
160 written: boolean;
161 /** False for failed writes or in-memory fallback; the entry will not survive reload. */
162 durable: boolean;
163 };
164 /** durable=false means removal was not persisted and reload would restore the entry. */
165 takeEntry: (entryId: string) => { entry: PromptStashEntry | null; durable: boolean };
166 /** attached=false means the entry disappeared while encoding, so images could not be saved. */
167 finalizeEntryImages: (
168 entryId: string,
169 images: {
170 attachments: ReadonlyArray<PersistedComposerImageAttachment>;
171 droppedImageNames: ReadonlyArray<string>;
172 unreadableImageNames: ReadonlyArray<string>;
173 },
174 ) => { attached: boolean; durable: boolean };
175}
176
177export const usePromptStashStore = create<PromptStashStoreState>()((set, get) => ({
178 entries: [],
179 stashEntry: (entry) => {
180 const currentEntries = latestEntries(get().entries);
181 // Never discard a stashed prompt to make room; the user decides what to remove.
182 if (currentEntries.length >= MAX_STASH_ENTRIES) {
183 return { full: true, written: false, durable: false };
184 }
185 const nextEntries = [entry, ...currentEntries];
186 const { written, durable } = persistEntries(nextEntries);
187 // Failed writes must not duplicate the intact composer.
188 if (!written) {
189 return { full: false, written: false, durable: false };
190 }
191 set(() => ({ entries: nextEntries }));
192 return { full: false, written: true, durable };
193 },
194 takeEntry: (entryId) => {
195 const entries = latestEntries(get().entries);
196 const entry = entries.find((candidate) => candidate.id === entryId) ?? null;
197 if (!entry) return { entry: null, durable: true };
198 const nextEntries = entries.filter((candidate) => candidate.id !== entryId);
199 const { durable } = persistEntries(nextEntries);
200 unpersistedFinalizedEntryIds.delete(entryId);
201 set(() => ({ entries: nextEntries }));
202 return { entry, durable };
203 },
204 finalizeEntryImages: (entryId, images) => {
205 const entries = latestEntries(get().entries);
206 const index = entries.findIndex((candidate) => candidate.id === entryId);
207 const existing = index === -1 ? undefined : entries[index];
208 if (!existing) return { attached: false, durable: true };
209 const nextEntries = [...entries];
210 nextEntries[index] = {
211 ...existing,
212 attachments: images.attachments,
213 droppedImageNames: images.droppedImageNames,
214 unreadableImageNames: images.unreadableImageNames,
215 pendingImageCount: 0,
216 };
217 const { written, durable } = persistEntries(nextEntries);
218 if (!written) unpersistedFinalizedEntryIds.add(entryId);
219 set(() => ({ entries: nextEntries }));
220 return { attached: true, durable };
221 },
222}));
223
224{
225 try {
226 baseStashStorage.removeItem(LEGACY_PROMPT_STASH_STORAGE_KEY);
227 } catch {}
228 const persisted = readPersistedEntries();
229 if (persisted) {
230 usePromptStashStore.setState({ entries: persisted });
231 }
232}
233
234export function writePromptStashStorageForTest(raw: string): void {
235 baseStashStorage.setItem(PROMPT_STASH_STORAGE_KEY, raw);
236 usePromptStashStore.setState({ entries: readPersistedEntries() ?? [] });
237}