Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
2import { EnvironmentId } from "@t3tools/contracts";
3
4import { removeLocalStorageItem } from "./hooks/useLocalStorage";
5
6import {
7 MAX_STASH_ENTRIES,
8 PROMPT_STASH_STORAGE_KEY,
9 MAX_STASH_ENTRY_ATTACHMENT_CHARS,
10 partitionStashAttachments,
11 usePromptStashStore,
12 writePromptStashStorageForTest,
13 type PromptStashEntry,
14} from "./promptStashStore";
15
16function makeEntry(input: {
17 id: string;
18 prompt?: string;
19 attachmentChars?: number;
20}): PromptStashEntry {
21 return {
22 id: input.id,
23 createdAt: "2026-07-24T12:00:00.000Z",
24 prompt: input.prompt ?? `prompt ${input.id}`,
25 attachments:
26 input.attachmentChars !== undefined
27 ? [
28 {
29 id: `${input.id}-img`,
30 name: "shot.png",
31 mimeType: "image/png",
32 sizeBytes: input.attachmentChars,
33 dataUrl: "x".repeat(input.attachmentChars),
34 },
35 ]
36 : [],
37 droppedImageNames: [],
38 };
39}
40
41function resetPromptStashStore() {
42 usePromptStashStore.setState({ entries: [] });
43 writePromptStashStorageForTest("");
44 removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
45}
46
47describe("partitionStashAttachments", () => {
48 it("keeps attachments within the budget and reports dropped names in order", () => {
49 const small = {
50 id: "a",
51 name: "small.png",
52 mimeType: "image/png",
53 sizeBytes: 10,
54 dataUrl: "x".repeat(10),
55 };
56 const huge = {
57 id: "b",
58 name: "huge.png",
59 mimeType: "image/png",
60 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
61 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
62 };
63 const alsoSmall = {
64 id: "c",
65 name: "also-small.png",
66 mimeType: "image/png",
67 sizeBytes: 10,
68 dataUrl: "x".repeat(10),
69 };
70 const { kept, droppedNames } = partitionStashAttachments([small, huge, alsoSmall]);
71 expect(kept.map((attachment) => attachment.id)).toEqual(["a", "c"]);
72 expect(droppedNames).toEqual(["huge.png"]);
73 });
74
75 it("admits a single attachment that exactly fits the budget", () => {
76 const exact = {
77 id: "a",
78 name: "exact.png",
79 mimeType: "image/png",
80 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
81 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
82 };
83 const { kept, droppedNames } = partitionStashAttachments([exact]);
84 expect(kept).toHaveLength(1);
85 expect(droppedNames).toEqual([]);
86 });
87});
88
89describe("promptStashStore", () => {
90 beforeEach(() => {
91 resetPromptStashStore();
92 });
93
94 afterEach(() => {
95 resetPromptStashStore();
96 });
97
98 it("prepends entries so the newest stash is first", () => {
99 const store = usePromptStashStore.getState();
100 store.stashEntry(makeEntry({ id: "first" }));
101 store.stashEntry(makeEntry({ id: "second" }));
102 const entries = usePromptStashStore.getState().entries;
103 expect(entries.map((entry) => entry.id)).toEqual(["second", "first"]);
104 });
105
106 it("evicts the oldest entry past the cap and returns it", () => {
107 const store = usePromptStashStore.getState();
108 for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) {
109 expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull();
110 }
111 const { evicted } = store.stashEntry(makeEntry({ id: "overflow" }));
112 expect(evicted?.id).toBe("entry-0");
113 const entries = usePromptStashStore.getState().entries;
114 expect(entries).toHaveLength(MAX_STASH_ENTRIES);
115 expect(entries[0]?.id).toBe("overflow");
116 });
117
118 // This test environment has no `localStorage`, so the store runs on its
119 // in-memory fallback — the exact "kept for this session, gone on reload"
120 // case the composer must distinguish from an outright write failure.
121 it("distinguishes a memory-only write (written, not durable) from a failed one", () => {
122 const store = usePromptStashStore.getState();
123 const result = store.stashEntry(makeEntry({ id: "memory-only" }));
124 expect(result.written).toBe(true);
125 expect(result.durable).toBe(false);
126 expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([
127 "memory-only",
128 ]);
129 });
130
131 it("takeEntry removes and returns the entry; second take returns null", () => {
132 const store = usePromptStashStore.getState();
133 store.stashEntry(makeEntry({ id: "keep" }));
134 store.stashEntry(makeEntry({ id: "take" }));
135 expect(store.takeEntry("take").entry?.id).toBe("take");
136 expect(store.takeEntry("take").entry).toBeNull();
137 const entries = usePromptStashStore.getState().entries;
138 expect(entries.map((entry) => entry.id)).toEqual(["keep"]);
139 });
140
141 it("finalizeEntryImages attaches images and clears the pending count", () => {
142 const store = usePromptStashStore.getState();
143 store.stashEntry({ ...makeEntry({ id: "pending" }), pendingImageCount: 2 });
144
145 const { attached } = store.finalizeEntryImages("pending", {
146 attachments: [
147 {
148 id: "img-1",
149 name: "a.webp",
150 mimeType: "image/webp",
151 sizeBytes: 10,
152 dataUrl: "data:image/webp;base64,AAAA",
153 },
154 ],
155 droppedImageNames: ["big.png"],
156 unreadableImageNames: [],
157 });
158
159 expect(attached).toBe(true);
160 const entry = usePromptStashStore.getState().entries[0];
161 expect(entry?.attachments).toHaveLength(1);
162 expect(entry?.droppedImageNames).toEqual(["big.png"]);
163 expect(entry?.pendingImageCount).toBe(0);
164 });
165
166 it("takeEntry returns images and drop metadata finalized after a menu snapshot", () => {
167 const store = usePromptStashStore.getState();
168 store.stashEntry({ ...makeEntry({ id: "pending-restore" }), pendingImageCount: 1 });
169 const menuSnapshot = usePromptStashStore.getState().entries[0];
170 expect(menuSnapshot?.attachments).toEqual([]);
171
172 store.finalizeEntryImages("pending-restore", {
173 attachments: [
174 {
175 id: "img-finalized",
176 name: "finalized.webp",
177 mimeType: "image/webp",
178 sizeBytes: 12,
179 dataUrl: "data:image/webp;base64,BBBB",
180 },
181 ],
182 droppedImageNames: ["too-large.png"],
183 unreadableImageNames: ["unreadable.png"],
184 });
185
186 const { entry: taken } = store.takeEntry("pending-restore");
187 expect(taken).not.toBe(menuSnapshot);
188 expect(taken).toMatchObject({
189 attachments: [
190 {
191 id: "img-finalized",
192 name: "finalized.webp",
193 },
194 ],
195 droppedImageNames: ["too-large.png"],
196 unreadableImageNames: ["unreadable.png"],
197 pendingImageCount: 0,
198 });
199 });
200
201 it("preserves uploaded file references without storing file contents", () => {
202 const store = usePromptStashStore.getState();
203 const file = {
204 id: "file-1",
205 name: "report.pdf",
206 mimeType: "application/pdf",
207 sizeBytes: 42,
208 attachmentId: "pending-report-pdf",
209 environmentId: EnvironmentId.make("environment-1"),
210 };
211
212 store.stashEntry({ ...makeEntry({ id: "with-file" }), files: [file] });
213 store.finalizeEntryImages("with-file", {
214 attachments: [],
215 droppedImageNames: [],
216 unreadableImageNames: [],
217 });
218
219 expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
220 });
221
222 it("finalizeEntryImages reports false when the entry was already taken", () => {
223 const store = usePromptStashStore.getState();
224 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
225 // Restored (or deleted) while its images were still encoding.
226 store.takeEntry("racing");
227
228 const { attached } = store.finalizeEntryImages("racing", {
229 attachments: [],
230 droppedImageNames: [],
231 unreadableImageNames: [],
232 });
233
234 expect(attached).toBe(false);
235 });
236
237 it("settles a pending count left behind by a crashed or closed session", () => {
238 writePromptStashStorageForTest(
239 JSON.stringify({
240 version: 2,
241 state: {
242 entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
243 },
244 }),
245 );
246
247 // Hydration must settle the stale count, or the entry would stay stuck
248 // showing "saving…" with images that no longer exist anywhere.
249 const entry = usePromptStashStore.getState().entries[0];
250 expect(entry?.pendingImageCount).toBe(0);
251 expect(entry?.unreadableImageNames).toHaveLength(2);
252 });
253
254 it("ignores an unreadable v1 payload seeded under the current key", () => {
255 // The v1 shape (per-provider queues) does not decode as v2; hydration
256 // must fall back to an empty stash rather than throw.
257 writePromptStashStorageForTest(
258 JSON.stringify({
259 version: 1,
260 state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
261 }),
262 );
263 expect(usePromptStashStore.getState().entries).toEqual([]);
264 });
265});