Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

promptStashStore.test.ts

331 lines10.4 KB

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 };
44​
45function resetPromptStashStore() {
46 usePromptStashStore.setState({ entries: [] });
47 writePromptStashStorageForTest("");
48 removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
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 writePromptStashStorageForTest(
242 JSON.stringify({
243 version: 2,
244 state: { entries: [{ ...makeEntry({ id: "with-file" }), files: [file] }] },
245 }),
246 );
247 store.finalizeEntryImages("with-file", {
248 attachments: [],
249 droppedImageNames: [],
250 unreadableImageNames: [],
251 });
252​
253 expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
254 });
255​
256 it("finalizeEntryImages reports false when the entry was already taken", () => {
257 const store = usePromptStashStore.getState();
258 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
259 store.takeEntry("racing");
260​
261 const { attached } = store.finalizeEntryImages("racing", {
262 attachments: [],
263 droppedImageNames: [],
264 unreadableImageNames: [],
265 });
266​
267 expect(attached).toBe(false);
268 });
269​
270 it("settles a pending count left behind by a crashed or closed session", () => {
271 writePromptStashStorageForTest(
272 JSON.stringify({
273 version: 2,
274 state: {
275 entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
276 },
277 }),
278 );
279​
280 const entry = usePromptStashStore.getState().entries[0];
281 expect(entry?.pendingImageCount).toBe(0);
282 expect(entry?.unreadableImageNames).toHaveLength(2);
283 });
284​
285 it("ignores an unreadable v1 payload seeded under the current key", () => {
286 writePromptStashStorageForTest(
287 JSON.stringify({
288 version: 1,
289 state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
290 }),
291 );
292 expect(usePromptStashStore.getState().entries).toEqual([]);
293 });
294});
295​
296describe("prompt stash context records", () => {
297 it("restores the records behind a persisted prompt's chips", () => {
298 const records = [
299 {
300 version: 1 as const,
301 contextId: "ctx-1" as never,
302 kind: "terminal" as const,
303 label: "Terminal 1 line 4",
304 terminalId: "default",
305 terminalLabel: "Terminal 1",
306 lineStart: 4,
307 lineEnd: 4,
308 text: "boom",
309 },
310 ];
311 writePromptStashStorageForTest(
312 JSON.stringify({
313 version: 2,
314 state: {
315 entries: [
316 {
317 id: "entry-records",
318 createdAt: "2026-01-01T00:00:00.000Z",
319 prompt: "see [Terminal 1 line 4](t3-context://v1/terminal/ctx-1)",
320 attachments: [],
321 droppedImageNames: [],
322 records,
323 },
324 ],
325 },
326 }),
327 );
328 const taken = usePromptStashStore.getState().takeEntry("entry-records");
329 expect(taken.entry?.records).toEqual(records);
330 });
331});