Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
2import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
3import {
4 collectAssistantCitations,
5 serializeAssistantCitation,
6} from "@t3tools/shared/assistantCitations";
7
8import { removeLocalStorageItem } from "./hooks/useLocalStorage";
9
10import {
11 MAX_STASH_ENTRIES,
12 PROMPT_STASH_STORAGE_KEY,
13 MAX_STASH_ENTRY_ATTACHMENT_CHARS,
14 partitionStashAttachments,
15 usePromptStashStore,
16 writePromptStashStorageForTest,
17 type PromptStashEntry,
18} from "./promptStashStore";
19
20function makeEntry(input: {
21 id: string;
22 prompt?: string;
23 attachmentChars?: number;
24}): PromptStashEntry {
25 return {
26 id: input.id,
27 createdAt: "2026-07-24T12:00:00.000Z",
28 prompt: input.prompt ?? `prompt ${input.id}`,
29 attachments:
30 input.attachmentChars !== undefined
31 ? [
32 {
33 id: `${input.id}-img`,
34 name: "shot.png",
35 mimeType: "image/png",
36 sizeBytes: input.attachmentChars,
37 dataUrl: "x".repeat(input.attachmentChars),
38 },
39 ]
40 : [],
41 droppedImageNames: [],
42 };
43}
44
45function resetPromptStashStore() {
46 usePromptStashStore.setState({ entries: [] });
47 writePromptStashStorageForTest("");
48 removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
49}
50
51describe("partitionStashAttachments", () => {
52 it("keeps attachments within the budget and reports dropped names in order", () => {
53 const small = {
54 id: "a",
55 name: "small.png",
56 mimeType: "image/png",
57 sizeBytes: 10,
58 dataUrl: "x".repeat(10),
59 };
60 const huge = {
61 id: "b",
62 name: "huge.png",
63 mimeType: "image/png",
64 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
65 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
66 };
67 const alsoSmall = {
68 id: "c",
69 name: "also-small.png",
70 mimeType: "image/png",
71 sizeBytes: 10,
72 dataUrl: "x".repeat(10),
73 };
74 const { kept, droppedNames } = partitionStashAttachments([small, huge, alsoSmall]);
75 expect(kept.map((attachment) => attachment.id)).toEqual(["a", "c"]);
76 expect(droppedNames).toEqual(["huge.png"]);
77 });
78
79 it("admits a single attachment that exactly fits the budget", () => {
80 const exact = {
81 id: "a",
82 name: "exact.png",
83 mimeType: "image/png",
84 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
85 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
86 };
87 const { kept, droppedNames } = partitionStashAttachments([exact]);
88 expect(kept).toHaveLength(1);
89 expect(droppedNames).toEqual([]);
90 });
91});
92
93describe("promptStashStore", () => {
94 beforeEach(() => {
95 resetPromptStashStore();
96 });
97
98 afterEach(() => {
99 resetPromptStashStore();
100 });
101
102 it("prepends entries so the newest stash is first", () => {
103 const store = usePromptStashStore.getState();
104 store.stashEntry(makeEntry({ id: "first" }));
105 store.stashEntry(makeEntry({ id: "second" }));
106 const entries = usePromptStashStore.getState().entries;
107 expect(entries.map((entry) => entry.id)).toEqual(["second", "first"]);
108 });
109
110 it("restores citations and bound comments from a persisted stash", () => {
111 const citation = {
112 version: 1 as const,
113 environmentId: EnvironmentId.make("remote-source"),
114 threadId: ThreadId.make("source-thread"),
115 messageId: MessageId.make("source-message"),
116 text: "A quote to revisit later.",
117 comment: "Revisit this tomorrow.\nCheck whether the example still applies.",
118 start: 0,
119 end: 24,
120 prefix: "",
121 suffix: " Next.",
122 };
123 const prompt = `Revisit ${serializeAssistantCitation(citation)}`;
124 writePromptStashStorageForTest(
125 JSON.stringify({
126 version: 2,
127 state: { entries: [makeEntry({ id: "citation-stash", prompt })] },
128 }),
129 );
130 const restored = usePromptStashStore.getState().takeEntry("citation-stash").entry;
131 expect(restored?.prompt).toBe(prompt);
132 expect(
133 collectAssistantCitations(restored?.prompt ?? "").map((entry) => entry.citation),
134 ).toEqual([citation]);
135 expect(usePromptStashStore.getState().takeEntry("citation-stash").entry).toBeNull();
136 });
137
138 it("evicts the oldest entry past the cap and returns it", () => {
139 const store = usePromptStashStore.getState();
140 for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) {
141 expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull();
142 }
143 const { evicted } = store.stashEntry(makeEntry({ id: "overflow" }));
144 expect(evicted?.id).toBe("entry-0");
145 const entries = usePromptStashStore.getState().entries;
146 expect(entries).toHaveLength(MAX_STASH_ENTRIES);
147 expect(entries[0]?.id).toBe("overflow");
148 });
149
150 it("distinguishes a memory-only write (written, not durable) from a failed one", () => {
151 const store = usePromptStashStore.getState();
152 const result = store.stashEntry(makeEntry({ id: "memory-only" }));
153 expect(result.written).toBe(true);
154 expect(result.durable).toBe(false);
155 expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([
156 "memory-only",
157 ]);
158 });
159
160 it("takeEntry removes and returns the entry; second take returns null", () => {
161 const store = usePromptStashStore.getState();
162 store.stashEntry(makeEntry({ id: "keep" }));
163 store.stashEntry(makeEntry({ id: "take" }));
164 expect(store.takeEntry("take").entry?.id).toBe("take");
165 expect(store.takeEntry("take").entry).toBeNull();
166 const entries = usePromptStashStore.getState().entries;
167 expect(entries.map((entry) => entry.id)).toEqual(["keep"]);
168 });
169
170 it("finalizeEntryImages attaches images and clears the pending count", () => {
171 const store = usePromptStashStore.getState();
172 store.stashEntry({ ...makeEntry({ id: "pending" }), pendingImageCount: 2 });
173
174 const { attached } = store.finalizeEntryImages("pending", {
175 attachments: [
176 {
177 id: "img-1",
178 name: "a.webp",
179 mimeType: "image/webp",
180 sizeBytes: 10,
181 dataUrl: "data:image/webp;base64,AAAA",
182 },
183 ],
184 droppedImageNames: ["big.png"],
185 unreadableImageNames: [],
186 });
187
188 expect(attached).toBe(true);
189 const entry = usePromptStashStore.getState().entries[0];
190 expect(entry?.attachments).toHaveLength(1);
191 expect(entry?.droppedImageNames).toEqual(["big.png"]);
192 expect(entry?.pendingImageCount).toBe(0);
193 });
194
195 it("takeEntry returns images and drop metadata finalized after a menu snapshot", () => {
196 const store = usePromptStashStore.getState();
197 store.stashEntry({ ...makeEntry({ id: "pending-restore" }), pendingImageCount: 1 });
198 const menuSnapshot = usePromptStashStore.getState().entries[0];
199 expect(menuSnapshot?.attachments).toEqual([]);
200
201 store.finalizeEntryImages("pending-restore", {
202 attachments: [
203 {
204 id: "img-finalized",
205 name: "finalized.webp",
206 mimeType: "image/webp",
207 sizeBytes: 12,
208 dataUrl: "data:image/webp;base64,BBBB",
209 },
210 ],
211 droppedImageNames: ["too-large.png"],
212 unreadableImageNames: ["unreadable.png"],
213 });
214
215 const { entry: taken } = store.takeEntry("pending-restore");
216 expect(taken).not.toBe(menuSnapshot);
217 expect(taken).toMatchObject({
218 attachments: [
219 {
220 id: "img-finalized",
221 name: "finalized.webp",
222 },
223 ],
224 droppedImageNames: ["too-large.png"],
225 unreadableImageNames: ["unreadable.png"],
226 pendingImageCount: 0,
227 });
228 });
229
230 it("preserves uploaded file references without storing file contents", () => {
231 const store = usePromptStashStore.getState();
232 const file = {
233 id: "file-1",
234 name: "report.pdf",
235 mimeType: "application/pdf",
236 sizeBytes: 42,
237 attachmentId: "pending-report-pdf",
238 environmentId: EnvironmentId.make("environment-1"),
239 };
240
241 store.stashEntry({ ...makeEntry({ id: "with-file" }), files: [file] });
242 store.finalizeEntryImages("with-file", {
243 attachments: [],
244 droppedImageNames: [],
245 unreadableImageNames: [],
246 });
247
248 expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
249 });
250
251 it("finalizeEntryImages reports false when the entry was already taken", () => {
252 const store = usePromptStashStore.getState();
253 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
254 store.takeEntry("racing");
255
256 const { attached } = store.finalizeEntryImages("racing", {
257 attachments: [],
258 droppedImageNames: [],
259 unreadableImageNames: [],
260 });
261
262 expect(attached).toBe(false);
263 });
264
265 it("settles a pending count left behind by a crashed or closed session", () => {
266 writePromptStashStorageForTest(
267 JSON.stringify({
268 version: 2,
269 state: {
270 entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
271 },
272 }),
273 );
274
275 const entry = usePromptStashStore.getState().entries[0];
276 expect(entry?.pendingImageCount).toBe(0);
277 expect(entry?.unreadableImageNames).toHaveLength(2);
278 });
279
280 it("ignores an unreadable v1 payload seeded under the current key", () => {
281 writePromptStashStorageForTest(
282 JSON.stringify({
283 version: 1,
284 state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
285 }),
286 );
287 expect(usePromptStashStore.getState().entries).toEqual([]);
288 });
289});
290
291describe("prompt stash context records", () => {
292 it("keeps the records behind a stashed prompt's chips", () => {
293 const store = usePromptStashStore.getState();
294 const records = [
295 {
296 version: 1 as const,
297 contextId: "ctx-1" as never,
298 kind: "terminal" as const,
299 label: "Terminal 1 line 4",
300 terminalId: "default",
301 terminalLabel: "Terminal 1",
302 lineStart: 4,
303 lineEnd: 4,
304 text: "boom",
305 },
306 ];
307 store.stashEntry({
308 id: "entry-records",
309 createdAt: "2026-01-01T00:00:00.000Z",
310 prompt: "see [Terminal 1 line 4](t3-context://v1/terminal/ctx-1)",
311 attachments: [],
312 droppedImageNames: [],
313 records,
314 });
315 const taken = usePromptStashStore.getState().takeEntry("entry-records");
316 expect(taken.entry?.records).toEqual(records);
317 });
318});