Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } 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";
9import { createMemoryStorage } from "./lib/storage";
10
11import {
12 MAX_STASH_ENTRIES,
13 PROMPT_STASH_STORAGE_KEY,
14 MAX_STASH_ENTRY_ATTACHMENT_CHARS,
15 partitionStashAttachments,
16 usePromptStashStore,
17 writePromptStashStorageForTest,
18 type PromptStashEntry,
19} from "./promptStashStore";
20
21function makeEntry(input: {
22 id: string;
23 prompt?: string;
24 attachmentChars?: number;
25}): PromptStashEntry {
26 return {
27 id: input.id,
28 createdAt: "2026-07-24T12:00:00.000Z",
29 prompt: input.prompt ?? `prompt ${input.id}`,
30 attachments:
31 input.attachmentChars !== undefined
32 ? [
33 {
34 id: `${input.id}-img`,
35 name: "shot.png",
36 mimeType: "image/png",
37 sizeBytes: input.attachmentChars,
38 dataUrl: "x".repeat(input.attachmentChars),
39 },
40 ]
41 : [],
42 droppedImageNames: [],
43 };
44}
45
46function resetPromptStashStore() {
47 usePromptStashStore.setState({ entries: [] });
48 writePromptStashStorageForTest("");
49 removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
50}
51
52describe("partitionStashAttachments", () => {
53 it("keeps attachments within the budget and reports dropped names in order", () => {
54 const small = {
55 id: "a",
56 name: "small.png",
57 mimeType: "image/png",
58 sizeBytes: 10,
59 dataUrl: "x".repeat(10),
60 };
61 const huge = {
62 id: "b",
63 name: "huge.png",
64 mimeType: "image/png",
65 sizeBytes: MAX_STASH_ENTRY_ATTACHMENT_CHARS,
66 dataUrl: "x".repeat(MAX_STASH_ENTRY_ATTACHMENT_CHARS),
67 };
68 const alsoSmall = {
69 id: "c",
70 name: "also-small.png",
71 mimeType: "image/png",
72 sizeBytes: 10,
73 dataUrl: "x".repeat(10),
74 };
75 const { kept, droppedNames } = partitionStashAttachments([small, huge, alsoSmall]);
76 expect(kept.map((attachment) => attachment.id)).toEqual(["a", "c"]);
77 expect(droppedNames).toEqual(["huge.png"]);
78 });
79});
80
81describe("promptStashStore", () => {
82 beforeEach(() => {
83 resetPromptStashStore();
84 });
85
86 afterEach(() => {
87 resetPromptStashStore();
88 });
89
90 it("restores citations and bound comments from a persisted stash", () => {
91 const citation = {
92 version: 1 as const,
93 environmentId: EnvironmentId.make("remote-source"),
94 threadId: ThreadId.make("source-thread"),
95 messageId: MessageId.make("source-message"),
96 text: "A quote to revisit later.",
97 comment: "Revisit this tomorrow.\nCheck whether the example still applies.",
98 start: 0,
99 end: 24,
100 prefix: "",
101 suffix: " Next.",
102 };
103 const prompt = `Revisit ${serializeAssistantCitation(citation)}`;
104 writePromptStashStorageForTest(
105 JSON.stringify({
106 version: 2,
107 state: { entries: [makeEntry({ id: "citation-stash", prompt })] },
108 }),
109 );
110 const restored = usePromptStashStore.getState().takeEntry("citation-stash").entry;
111 expect(restored?.prompt).toBe(prompt);
112 expect(
113 collectAssistantCitations(restored?.prompt ?? "").map((entry) => entry.citation),
114 ).toEqual([citation]);
115 expect(usePromptStashStore.getState().takeEntry("citation-stash").entry).toBeNull();
116 });
117
118 it("refuses a new entry when full instead of discarding the oldest", () => {
119 const store = usePromptStashStore.getState();
120 for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) {
121 expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).written).toBe(true);
122 }
123 const result = store.stashEntry(makeEntry({ id: "overflow" }));
124 expect(result).toEqual({ full: true, written: false, durable: false });
125 const entries = usePromptStashStore.getState().entries;
126 expect(entries).toHaveLength(MAX_STASH_ENTRIES);
127 expect(entries.map((entry) => entry.id)).not.toContain("overflow");
128 expect(entries.map((entry) => entry.id)).toContain("entry-0");
129 });
130
131 // regression: #4787 stashed prompts were lost when switching providers
132 it("distinguishes a memory-only write (written, not durable) from a failed one", () => {
133 const store = usePromptStashStore.getState();
134 const result = store.stashEntry(makeEntry({ id: "memory-only" }));
135 expect(result.written).toBe(true);
136 expect(result.durable).toBe(false);
137 expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([
138 "memory-only",
139 ]);
140 });
141
142 it("takeEntry returns images and drop metadata finalized after a menu snapshot", () => {
143 const store = usePromptStashStore.getState();
144 store.stashEntry({ ...makeEntry({ id: "pending-restore" }), pendingImageCount: 1 });
145 const menuSnapshot = usePromptStashStore.getState().entries[0];
146 expect(menuSnapshot?.attachments).toEqual([]);
147 store.stashEntry(makeEntry({ id: "stashed-while-encoding" }));
148 expect(
149 usePromptStashStore.getState().entries.find((entry) => entry.id === "pending-restore")
150 ?.pendingImageCount,
151 ).toBe(1);
152
153 store.finalizeEntryImages("pending-restore", {
154 attachments: [
155 {
156 id: "img-finalized",
157 name: "finalized.webp",
158 mimeType: "image/webp",
159 sizeBytes: 12,
160 dataUrl: "data:image/webp;base64,BBBB",
161 },
162 ],
163 droppedImageNames: ["too-large.png"],
164 unreadableImageNames: ["unreadable.png"],
165 });
166
167 const { entry: taken } = store.takeEntry("pending-restore");
168 expect(taken).not.toBe(menuSnapshot);
169 expect(taken).toMatchObject({
170 attachments: [
171 {
172 id: "img-finalized",
173 name: "finalized.webp",
174 },
175 ],
176 droppedImageNames: ["too-large.png"],
177 unreadableImageNames: ["unreadable.png"],
178 pendingImageCount: 0,
179 });
180 });
181
182 it("preserves uploaded file references without storing file contents", () => {
183 const store = usePromptStashStore.getState();
184 const file = {
185 id: "file-1",
186 name: "report.pdf",
187 mimeType: "application/pdf",
188 sizeBytes: 42,
189 attachmentId: "pending-report-pdf",
190 environmentId: EnvironmentId.make("environment-1"),
191 };
192
193 writePromptStashStorageForTest(
194 JSON.stringify({
195 version: 2,
196 state: { entries: [{ ...makeEntry({ id: "with-file" }), files: [file] }] },
197 }),
198 );
199 store.finalizeEntryImages("with-file", {
200 attachments: [],
201 droppedImageNames: [],
202 unreadableImageNames: [],
203 });
204
205 expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
206 });
207
208 it("finalizeEntryImages reports false when the entry was already taken", () => {
209 const store = usePromptStashStore.getState();
210 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
211 store.takeEntry("racing");
212
213 const { attached } = store.finalizeEntryImages("racing", {
214 attachments: [],
215 droppedImageNames: [],
216 unreadableImageNames: [],
217 });
218
219 expect(attached).toBe(false);
220 });
221
222 it("settles a pending count left behind by a crashed or closed session", () => {
223 writePromptStashStorageForTest(
224 JSON.stringify({
225 version: 2,
226 state: {
227 entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
228 },
229 }),
230 );
231
232 const entry = usePromptStashStore.getState().entries[0];
233 expect(entry?.pendingImageCount).toBe(0);
234 expect(entry?.unreadableImageNames).toHaveLength(2);
235 });
236
237 it("ignores an unreadable v1 payload seeded under the current key", () => {
238 writePromptStashStorageForTest(
239 JSON.stringify({
240 version: 1,
241 state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
242 }),
243 );
244 expect(usePromptStashStore.getState().entries).toEqual([]);
245 });
246
247 // regression: #35010 stashing in one tab erased what another tab stashed after it loaded
248 it("keeps an entry another tab stashed after this tab loaded", async () => {
249 const sharedStorage = createMemoryStorage();
250 vi.stubGlobal("localStorage", sharedStorage);
251 vi.stubGlobal("window", new EventTarget());
252 vi.resetModules();
253 try {
254 const thisTab = await import("./promptStashStore");
255 sharedStorage.setItem(
256 PROMPT_STASH_STORAGE_KEY,
257 JSON.stringify({ version: 2, state: { entries: [makeEntry({ id: "other-tab" })] } }),
258 );
259 window.dispatchEvent(Object.assign(new Event("storage"), { key: PROMPT_STASH_STORAGE_KEY }));
260
261 thisTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "this-tab" }));
262
263 const saved = JSON.parse(sharedStorage.getItem(PROMPT_STASH_STORAGE_KEY) as string);
264 expect(saved.state.entries.map((entry: PromptStashEntry) => entry.id)).toEqual([
265 "this-tab",
266 "other-tab",
267 ]);
268
269 thisTab.usePromptStashStore.getState().stashEntry({
270 ...makeEntry({ id: "encoding-image" }),
271 pendingImageCount: 1,
272 });
273 vi.resetModules();
274 const secondTab = await import("./promptStashStore");
275 const finalized = makeEntry({ id: "encoding-image", attachmentChars: 12 }).attachments;
276 thisTab.usePromptStashStore.getState().finalizeEntryImages("encoding-image", {
277 attachments: finalized,
278 droppedImageNames: [],
279 unreadableImageNames: [],
280 });
281 secondTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "second-tab-new" }));
282 const afterFinalization = JSON.parse(
283 sharedStorage.getItem(PROMPT_STASH_STORAGE_KEY) as string,
284 );
285 expect(
286 afterFinalization.state.entries.find(
287 (entry: PromptStashEntry) => entry.id === "encoding-image",
288 )?.attachments,
289 ).toEqual(finalized);
290 } finally {
291 vi.unstubAllGlobals();
292 vi.resetModules();
293 }
294 });
295
296 it.each(["restore", "take"] as const)(
297 "keeps a failed finalize after another tab stashes, then handles %s",
298 async (action) => {
299 const storage = createMemoryStorage();
300 vi.stubGlobal("localStorage", {
301 ...storage,
302 setItem: (key: string, value: string) => {
303 if (value.includes("rejected-image")) throw new Error("QuotaExceededError");
304 storage.setItem(key, value);
305 },
306 });
307 vi.resetModules();
308 try {
309 const { usePromptStashStore: store } = await import("./promptStashStore");
310 store.getState().stashEntry({ ...makeEntry({ id: "too-big" }), pendingImageCount: 1 });
311 vi.resetModules();
312 const { usePromptStashStore: otherTab } = await import("./promptStashStore");
313 const { attachments } = makeEntry({ id: "rejected-image", attachmentChars: 4 });
314 const images = { attachments, droppedImageNames: [], unreadableImageNames: [] };
315 expect(store.getState().finalizeEntryImages("too-big", images)).toEqual({
316 attached: true,
317 durable: false,
318 });
319 otherTab.getState().stashEntry(makeEntry({ id: "unrelated" }));
320
321 if (action === "take") {
322 otherTab.getState().takeEntry("too-big");
323 expect(store.getState().finalizeEntryImages("too-big", images)).toEqual({
324 attached: false,
325 durable: true,
326 });
327 expect(store.getState().takeEntry("too-big").entry).toBeNull();
328 return;
329 }
330
331 expect(store.getState().takeEntry("too-big").entry).toMatchObject({
332 attachments,
333 unreadableImageNames: [],
334 });
335 } finally {
336 vi.unstubAllGlobals();
337 vi.resetModules();
338 }
339 },
340 );
341});
342
343describe("prompt stash context records", () => {
344 it("restores the records behind a persisted prompt's chips", () => {
345 const records = [
346 {
347 version: 1 as const,
348 contextId: "ctx-1" as never,
349 kind: "terminal" as const,
350 label: "Terminal 1 line 4",
351 terminalId: "default",
352 terminalLabel: "Terminal 1",
353 lineStart: 4,
354 lineEnd: 4,
355 text: "boom",
356 },
357 ];
358 writePromptStashStorageForTest(
359 JSON.stringify({
360 version: 2,
361 state: {
362 entries: [
363 {
364 id: "entry-records",
365 createdAt: "2026-01-01T00:00:00.000Z",
366 prompt: "see [Terminal 1 line 4](t3-context://v1/terminal/ctx-1)",
367 attachments: [],
368 droppedImageNames: [],
369 records,
370 },
371 ],
372 },
373 }),
374 );
375 const taken = usePromptStashStore.getState().takeEntry("entry-records");
376 expect(taken.entry?.records).toEqual(records);
377 });
378});