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