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

promptStashStore.test.ts

276 lines8.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​
80describe("promptStashStore", () => {
81 beforeEach(() => {
82 resetPromptStashStore();
83 });
84​
85 afterEach(() => {
86 resetPromptStashStore();
87 });
88​
89 it("restores citations and bound comments from a persisted stash", () => {
90 const citation = {
91 version: 1 as const,
92 environmentId: EnvironmentId.make("remote-source"),
93 threadId: ThreadId.make("source-thread"),
94 messageId: MessageId.make("source-message"),
95 text: "A quote to revisit later.",
96 comment: "Revisit this tomorrow.\nCheck whether the example still applies.",
97 start: 0,
98 end: 24,
99 prefix: "",
100 suffix: " Next.",
101 };
102 const prompt = `Revisit ${serializeAssistantCitation(citation)}`;
103 writePromptStashStorageForTest(
104 JSON.stringify({
105 version: 2,
106 state: { entries: [makeEntry({ id: "citation-stash", prompt })] },
107 }),
108 );
109 const restored = usePromptStashStore.getState().takeEntry("citation-stash").entry;
110 expect(restored?.prompt).toBe(prompt);
111 expect(
112 collectAssistantCitations(restored?.prompt ?? "").map((entry) => entry.citation),
113 ).toEqual([citation]);
114 expect(usePromptStashStore.getState().takeEntry("citation-stash").entry).toBeNull();
115 });
116​
117 it("evicts the oldest entry past the cap and returns it", () => {
118 const store = usePromptStashStore.getState();
119 for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) {
120 expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull();
121 }
122 const { evicted } = store.stashEntry(makeEntry({ id: "overflow" }));
123 expect(evicted?.id).toBe("entry-0");
124 const entries = usePromptStashStore.getState().entries;
125 expect(entries).toHaveLength(MAX_STASH_ENTRIES);
126 expect(entries[0]?.id).toBe("overflow");
127 });
128​
129 // regression: #4787 stashed prompts were lost when switching providers
130 it("distinguishes a memory-only write (written, not durable) from a failed one", () => {
131 const store = usePromptStashStore.getState();
132 const result = store.stashEntry(makeEntry({ id: "memory-only" }));
133 expect(result.written).toBe(true);
134 expect(result.durable).toBe(false);
135 expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([
136 "memory-only",
137 ]);
138 });
139​
140 it("takeEntry returns images and drop metadata finalized after a menu snapshot", () => {
141 const store = usePromptStashStore.getState();
142 store.stashEntry({ ...makeEntry({ id: "pending-restore" }), pendingImageCount: 1 });
143 const menuSnapshot = usePromptStashStore.getState().entries[0];
144 expect(menuSnapshot?.attachments).toEqual([]);
145​
146 store.finalizeEntryImages("pending-restore", {
147 attachments: [
148 {
149 id: "img-finalized",
150 name: "finalized.webp",
151 mimeType: "image/webp",
152 sizeBytes: 12,
153 dataUrl: "data:image/webp;base64,BBBB",
154 },
155 ],
156 droppedImageNames: ["too-large.png"],
157 unreadableImageNames: ["unreadable.png"],
158 });
159​
160 const { entry: taken } = store.takeEntry("pending-restore");
161 expect(taken).not.toBe(menuSnapshot);
162 expect(taken).toMatchObject({
163 attachments: [
164 {
165 id: "img-finalized",
166 name: "finalized.webp",
167 },
168 ],
169 droppedImageNames: ["too-large.png"],
170 unreadableImageNames: ["unreadable.png"],
171 pendingImageCount: 0,
172 });
173 });
174​
175 it("preserves uploaded file references without storing file contents", () => {
176 const store = usePromptStashStore.getState();
177 const file = {
178 id: "file-1",
179 name: "report.pdf",
180 mimeType: "application/pdf",
181 sizeBytes: 42,
182 attachmentId: "pending-report-pdf",
183 environmentId: EnvironmentId.make("environment-1"),
184 };
185​
186 writePromptStashStorageForTest(
187 JSON.stringify({
188 version: 2,
189 state: { entries: [{ ...makeEntry({ id: "with-file" }), files: [file] }] },
190 }),
191 );
192 store.finalizeEntryImages("with-file", {
193 attachments: [],
194 droppedImageNames: [],
195 unreadableImageNames: [],
196 });
197​
198 expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
199 });
200​
201 it("finalizeEntryImages reports false when the entry was already taken", () => {
202 const store = usePromptStashStore.getState();
203 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
204 store.takeEntry("racing");
205​
206 const { attached } = store.finalizeEntryImages("racing", {
207 attachments: [],
208 droppedImageNames: [],
209 unreadableImageNames: [],
210 });
211​
212 expect(attached).toBe(false);
213 });
214​
215 it("settles a pending count left behind by a crashed or closed session", () => {
216 writePromptStashStorageForTest(
217 JSON.stringify({
218 version: 2,
219 state: {
220 entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
221 },
222 }),
223 );
224​
225 const entry = usePromptStashStore.getState().entries[0];
226 expect(entry?.pendingImageCount).toBe(0);
227 expect(entry?.unreadableImageNames).toHaveLength(2);
228 });
229​
230 it("ignores an unreadable v1 payload seeded under the current key", () => {
231 writePromptStashStorageForTest(
232 JSON.stringify({
233 version: 1,
234 state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
235 }),
236 );
237 expect(usePromptStashStore.getState().entries).toEqual([]);
238 });
239});
240​
241describe("prompt stash context records", () => {
242 it("restores the records behind a persisted prompt's chips", () => {
243 const records = [
244 {
245 version: 1 as const,
246 contextId: "ctx-1" as never,
247 kind: "terminal" as const,
248 label: "Terminal 1 line 4",
249 terminalId: "default",
250 terminalLabel: "Terminal 1",
251 lineStart: 4,
252 lineEnd: 4,
253 text: "boom",
254 },
255 ];
256 writePromptStashStorageForTest(
257 JSON.stringify({
258 version: 2,
259 state: {
260 entries: [
261 {
262 id: "entry-records",
263 createdAt: "2026-01-01T00:00:00.000Z",
264 prompt: "see [Terminal 1 line 4](t3-context://v1/terminal/ctx-1)",
265 attachments: [],
266 droppedImageNames: [],
267 records,
268 },
269 ],
270 },
271 }),
272 );
273 const taken = usePromptStashStore.getState().takeEntry("entry-records");
274 expect(taken.entry?.records).toEqual(records);
275 });
276});