Open History to see the last commit
1import { ProviderInstanceId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
3
4import { removeLocalStorageItem } from "./hooks/useLocalStorage";
5
6import {
7 MAX_STASH_ENTRIES_PER_QUEUE,
8 PROMPT_STASH_STORAGE_KEY,
9 MAX_STASH_ENTRY_ATTACHMENT_CHARS,
10 PROMPT_STASH_UNSCOPED_KEY,
11 partitionStashAttachments,
12 promptStashScopeKey,
13 usePromptStashStore,
14 writePromptStashStorageForTest,
15 type PromptStashEntry,
16} from "./promptStashStore";
17
18const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent");
19const CODEX_INSTANCE = ProviderInstanceId.make("codex");
20
21function makeEntry(input: {
22 id: string;
23 providerInstanceId?: ProviderInstanceId | null;
24 prompt?: string;
25 attachmentChars?: number;
26}): PromptStashEntry {
27 return {
28 id: input.id,
29 createdAt: "2026-07-24T12:00:00.000Z",
30 prompt: input.prompt ?? `prompt ${input.id}`,
31 attachments:
32 input.attachmentChars !== undefined
33 ? [
34 {
35 id: `${input.id}-img`,
36 name: "shot.png",
37 mimeType: "image/png",
38 sizeBytes: input.attachmentChars,
39 dataUrl: "x".repeat(input.attachmentChars),
40 },
41 ]
42 : [],
43 providerInstanceId:
44 input.providerInstanceId === undefined ? CLAUDE_AGENT_INSTANCE : input.providerInstanceId,
45 modelSelection: null,
46 droppedImageNames: [],
47 };
48}
49
50function resetPromptStashStore() {
51 usePromptStashStore.setState({ queuesByScopeKey: {} });
52 writePromptStashStorageForTest("");
53 removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
54}
55
56describe("promptStashScopeKey", () => {
57 it("maps a provider instance to its own bucket and null to the unscoped bucket", () => {
58 expect(promptStashScopeKey(CLAUDE_AGENT_INSTANCE)).toBe("provider:claudeAgent");
59 expect(promptStashScopeKey(null)).toBe(PROMPT_STASH_UNSCOPED_KEY);
60 expect(promptStashScopeKey(undefined)).toBe(PROMPT_STASH_UNSCOPED_KEY);
61 });
62
63 // Provider slugs must match /^[a-zA-Z][a-zA-Z0-9_-]*$/, so no real instance
64 // id can equal the unscoped sentinel. The namespace prefix makes that
65 // structural rather than incidental.
66 it("namespaces provider keys so they can never equal the unscoped sentinel", () => {
67 expect(promptStashScopeKey(CLAUDE_AGENT_INSTANCE)).not.toBe(PROMPT_STASH_UNSCOPED_KEY);
68 expect(promptStashScopeKey(CODEX_INSTANCE).startsWith("provider:")).toBe(true);
69 });
70});
71
72describe("partitionStashAttachments", () => {
73 it("keeps attachments within the budget and reports dropped names in order", () => {
74 const small = {
75 id: "a",
76 name: "small.png",
77 mimeType: "image/png",
78 sizeBytes: 10,
79 dataUrl: "x".repeat(10),
80 };
81 const huge = {
82 id: "b",
83 name: "huge.png",
84 mimeType: "image/png",
85 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
86 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
87 };
88 const alsoSmall = {
89 id: "c",
90 name: "also-small.png",
91 mimeType: "image/png",
92 sizeBytes: 10,
93 dataUrl: "x".repeat(10),
94 };
95 const { kept, droppedNames } = partitionStashAttachments([small, huge, alsoSmall]);
96 expect(kept.map((attachment) => attachment.id)).toEqual(["a", "c"]);
97 expect(droppedNames).toEqual(["huge.png"]);
98 });
99
100 it("admits a single attachment that exactly fits the budget", () => {
101 const exact = {
102 id: "a",
103 name: "exact.png",
104 mimeType: "image/png",
105 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
106 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
107 };
108 const { kept, droppedNames } = partitionStashAttachments([exact]);
109 expect(kept).toHaveLength(1);
110 expect(droppedNames).toEqual([]);
111 });
112});
113
114describe("promptStashStore", () => {
115 beforeEach(() => {
116 resetPromptStashStore();
117 });
118
119 afterEach(() => {
120 resetPromptStashStore();
121 });
122
123 it("prepends entries so the newest stash is first", () => {
124 const store = usePromptStashStore.getState();
125 store.stashEntry(makeEntry({ id: "first" }));
126 store.stashEntry(makeEntry({ id: "second" }));
127 const queue =
128 usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)] ??
129 [];
130 expect(queue.map((entry) => entry.id)).toEqual(["second", "first"]);
131 });
132
133 it("scopes queues by provider instance, including the unscoped bucket", () => {
134 const store = usePromptStashStore.getState();
135 store.stashEntry(makeEntry({ id: "claude" }));
136 store.stashEntry(makeEntry({ id: "codex", providerInstanceId: CODEX_INSTANCE }));
137 store.stashEntry(makeEntry({ id: "none", providerInstanceId: null }));
138 const queues = usePromptStashStore.getState().queuesByScopeKey;
139 expect(queues[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)]?.map((entry) => entry.id)).toEqual([
140 "claude",
141 ]);
142 expect(queues[promptStashScopeKey(CODEX_INSTANCE)]?.map((entry) => entry.id)).toEqual([
143 "codex",
144 ]);
145 expect(queues[PROMPT_STASH_UNSCOPED_KEY]?.map((entry) => entry.id)).toEqual(["none"]);
146 });
147
148 it("evicts the oldest entry past the per-queue cap and returns it", () => {
149 const store = usePromptStashStore.getState();
150 for (let index = 0; index < MAX_STASH_ENTRIES_PER_QUEUE; index += 1) {
151 expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull();
152 }
153 const { evicted } = store.stashEntry(makeEntry({ id: "overflow" }));
154 expect(evicted?.id).toBe("entry-0");
155 const queue =
156 usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)] ??
157 [];
158 expect(queue).toHaveLength(MAX_STASH_ENTRIES_PER_QUEUE);
159 expect(queue[0]?.id).toBe("overflow");
160 });
161
162 it("takeEntry removes and returns the entry; second take returns null", () => {
163 const store = usePromptStashStore.getState();
164 store.stashEntry(makeEntry({ id: "keep" }));
165 store.stashEntry(makeEntry({ id: "take" }));
166 expect(store.takeEntry(promptStashScopeKey(CLAUDE_AGENT_INSTANCE), "take").entry?.id).toBe(
167 "take",
168 );
169 expect(store.takeEntry(promptStashScopeKey(CLAUDE_AGENT_INSTANCE), "take").entry).toBeNull();
170 const queue =
171 usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)] ??
172 [];
173 expect(queue.map((entry) => entry.id)).toEqual(["keep"]);
174 });
175
176 // Queue keys are persisted as plain strings, so a hand-edited or corrupted
177 // localStorage payload can carry a literal `__proto__` key that survives
178 // JSON.parse as an own property. An unguarded lookup would resolve to
179 // Object.prototype and throw "not iterable" on spread.
180 it("tolerates a __proto__ scope key rehydrated from storage", () => {
181 usePromptStashStore.setState({
182 queuesByScopeKey: JSON.parse('{"__proto__":[]}') as Record<string, PromptStashEntry[]>,
183 });
184 const store = usePromptStashStore.getState();
185 expect(() => store.takeEntry("__proto__", "missing")).not.toThrow();
186 expect(store.takeEntry("__proto__", "missing").entry).toBeNull();
187 });
188
189 it("finalizeEntryImages attaches images and clears the pending count", () => {
190 const store = usePromptStashStore.getState();
191 const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
192 store.stashEntry({ ...makeEntry({ id: "pending" }), pendingImageCount: 2 });
193
194 const { attached } = store.finalizeEntryImages(scopeKey, "pending", {
195 attachments: [
196 {
197 id: "img-1",
198 name: "a.webp",
199 mimeType: "image/webp",
200 sizeBytes: 10,
201 dataUrl: "data:image/webp;base64,AAAA",
202 },
203 ],
204 droppedImageNames: ["big.png"],
205 unreadableImageNames: [],
206 });
207
208 expect(attached).toBe(true);
209 const entry = usePromptStashStore.getState().queuesByScopeKey[scopeKey]?.[0];
210 expect(entry?.attachments).toHaveLength(1);
211 expect(entry?.droppedImageNames).toEqual(["big.png"]);
212 expect(entry?.pendingImageCount).toBe(0);
213 });
214
215 it("finalizeEntryImages reports false when the entry was already taken", () => {
216 const store = usePromptStashStore.getState();
217 const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
218 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
219 // Restored (or deleted) while its images were still encoding.
220 store.takeEntry(scopeKey, "racing");
221
222 const { attached } = store.finalizeEntryImages(scopeKey, "racing", {
223 attachments: [],
224 droppedImageNames: [],
225 unreadableImageNames: [],
226 });
227
228 expect(attached).toBe(false);
229 });
230
231 it("settles a pending count left behind by a crashed or closed session", () => {
232 const scopeKey = promptStashScopeKey(CLAUDE_AGENT_INSTANCE);
233 writePromptStashStorageForTest(
234 JSON.stringify({
235 version: 1,
236 state: {
237 queuesByScopeKey: {
238 [scopeKey]: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
239 },
240 },
241 }),
242 );
243
244 // Hydration must settle the stale count, or the entry would stay stuck
245 // showing "saving…" with images that no longer exist anywhere.
246 const entry = usePromptStashStore.getState().queuesByScopeKey[scopeKey]?.[0];
247 expect(entry?.pendingImageCount).toBe(0);
248 expect(entry?.unreadableImageNames).toHaveLength(2);
249 });
250
251 it("drops the scope key entirely when its queue empties", () => {
252 const store = usePromptStashStore.getState();
253 store.stashEntry(makeEntry({ id: "only" }));
254 store.takeEntry(promptStashScopeKey(CLAUDE_AGENT_INSTANCE), "only");
255 expect(
256 usePromptStashStore.getState().queuesByScopeKey[promptStashScopeKey(CLAUDE_AGENT_INSTANCE)],
257 ).toBeUndefined();
258 });
259});