@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 377 lines 12.3 KB
Raw
1 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
3 import {
4 collectAssistantCitations,
5 serializeAssistantCitation,
6 } from "@t3tools/shared/assistantCitations";
7
8 import { removeLocalStorageItem } from "./hooks/useLocalStorage";
9 import { createMemoryStorage } from "./lib/storage";
10
11 import {
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
21 function 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
46 function resetPromptStashStore() {
47 usePromptStashStore.setState({ entries: [] });
48 writePromptStashStorageForTest("");
49 removeLocalStorageItem(PROMPT_STASH_STORAGE_KEY);
50 }
51
52 describe("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
81 describe("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("evicts the oldest entry past the cap and returns it", () => {
119 const store = usePromptStashStore.getState();
120 for (let index = 0; index < MAX_STASH_ENTRIES; index += 1) {
121 expect(store.stashEntry(makeEntry({ id: `entry-${index}` })).evicted).toBeNull();
122 }
123 const { evicted } = store.stashEntry(makeEntry({ id: "overflow" }));
124 expect(evicted?.id).toBe("entry-0");
125 const entries = usePromptStashStore.getState().entries;
126 expect(entries).toHaveLength(MAX_STASH_ENTRIES);
127 expect(entries[0]?.id).toBe("overflow");
128 });
129
130 // regression: #4787 stashed prompts were lost when switching providers
131 it("distinguishes a memory-only write (written, not durable) from a failed one", () => {
132 const store = usePromptStashStore.getState();
133 const result = store.stashEntry(makeEntry({ id: "memory-only" }));
134 expect(result.written).toBe(true);
135 expect(result.durable).toBe(false);
136 expect(usePromptStashStore.getState().entries.map((entry) => entry.id)).toEqual([
137 "memory-only",
138 ]);
139 });
140
141 it("takeEntry returns images and drop metadata finalized after a menu snapshot", () => {
142 const store = usePromptStashStore.getState();
143 store.stashEntry({ ...makeEntry({ id: "pending-restore" }), pendingImageCount: 1 });
144 const menuSnapshot = usePromptStashStore.getState().entries[0];
145 expect(menuSnapshot?.attachments).toEqual([]);
146 store.stashEntry(makeEntry({ id: "stashed-while-encoding" }));
147 expect(
148 usePromptStashStore.getState().entries.find((entry) => entry.id === "pending-restore")
149 ?.pendingImageCount,
150 ).toBe(1);
151
152 store.finalizeEntryImages("pending-restore", {
153 attachments: [
154 {
155 id: "img-finalized",
156 name: "finalized.webp",
157 mimeType: "image/webp",
158 sizeBytes: 12,
159 dataUrl: "data:image/webp;base64,BBBB",
160 },
161 ],
162 droppedImageNames: ["too-large.png"],
163 unreadableImageNames: ["unreadable.png"],
164 });
165
166 const { entry: taken } = store.takeEntry("pending-restore");
167 expect(taken).not.toBe(menuSnapshot);
168 expect(taken).toMatchObject({
169 attachments: [
170 {
171 id: "img-finalized",
172 name: "finalized.webp",
173 },
174 ],
175 droppedImageNames: ["too-large.png"],
176 unreadableImageNames: ["unreadable.png"],
177 pendingImageCount: 0,
178 });
179 });
180
181 it("preserves uploaded file references without storing file contents", () => {
182 const store = usePromptStashStore.getState();
183 const file = {
184 id: "file-1",
185 name: "report.pdf",
186 mimeType: "application/pdf",
187 sizeBytes: 42,
188 attachmentId: "pending-report-pdf",
189 environmentId: EnvironmentId.make("environment-1"),
190 };
191
192 writePromptStashStorageForTest(
193 JSON.stringify({
194 version: 2,
195 state: { entries: [{ ...makeEntry({ id: "with-file" }), files: [file] }] },
196 }),
197 );
198 store.finalizeEntryImages("with-file", {
199 attachments: [],
200 droppedImageNames: [],
201 unreadableImageNames: [],
202 });
203
204 expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
205 });
206
207 it("finalizeEntryImages reports false when the entry was already taken", () => {
208 const store = usePromptStashStore.getState();
209 store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
210 store.takeEntry("racing");
211
212 const { attached } = store.finalizeEntryImages("racing", {
213 attachments: [],
214 droppedImageNames: [],
215 unreadableImageNames: [],
216 });
217
218 expect(attached).toBe(false);
219 });
220
221 it("settles a pending count left behind by a crashed or closed session", () => {
222 writePromptStashStorageForTest(
223 JSON.stringify({
224 version: 2,
225 state: {
226 entries: [{ ...makeEntry({ id: "orphan" }), pendingImageCount: 2 }],
227 },
228 }),
229 );
230
231 const entry = usePromptStashStore.getState().entries[0];
232 expect(entry?.pendingImageCount).toBe(0);
233 expect(entry?.unreadableImageNames).toHaveLength(2);
234 });
235
236 it("ignores an unreadable v1 payload seeded under the current key", () => {
237 writePromptStashStorageForTest(
238 JSON.stringify({
239 version: 1,
240 state: { queuesByScopeKey: { "provider:claudeAgent": [] } },
241 }),
242 );
243 expect(usePromptStashStore.getState().entries).toEqual([]);
244 });
245
246 // regression: #35010 stashing in one tab erased what another tab stashed after it loaded
247 it("keeps an entry another tab stashed after this tab loaded", async () => {
248 const sharedStorage = createMemoryStorage();
249 vi.stubGlobal("localStorage", sharedStorage);
250 vi.stubGlobal("window", new EventTarget());
251 vi.resetModules();
252 try {
253 const thisTab = await import("./promptStashStore");
254 sharedStorage.setItem(
255 PROMPT_STASH_STORAGE_KEY,
256 JSON.stringify({ version: 2, state: { entries: [makeEntry({ id: "other-tab" })] } }),
257 );
258 window.dispatchEvent(Object.assign(new Event("storage"), { key: PROMPT_STASH_STORAGE_KEY }));
259
260 thisTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "this-tab" }));
261
262 const saved = JSON.parse(sharedStorage.getItem(PROMPT_STASH_STORAGE_KEY) as string);
263 expect(saved.state.entries.map((entry: PromptStashEntry) => entry.id)).toEqual([
264 "this-tab",
265 "other-tab",
266 ]);
267
268 thisTab.usePromptStashStore.getState().stashEntry({
269 ...makeEntry({ id: "encoding-image" }),
270 pendingImageCount: 1,
271 });
272 vi.resetModules();
273 const secondTab = await import("./promptStashStore");
274 const finalized = makeEntry({ id: "encoding-image", attachmentChars: 12 }).attachments;
275 thisTab.usePromptStashStore.getState().finalizeEntryImages("encoding-image", {
276 attachments: finalized,
277 droppedImageNames: [],
278 unreadableImageNames: [],
279 });
280 secondTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "second-tab-new" }));
281 const afterFinalization = JSON.parse(
282 sharedStorage.getItem(PROMPT_STASH_STORAGE_KEY) as string,
283 );
284 expect(
285 afterFinalization.state.entries.find(
286 (entry: PromptStashEntry) => entry.id === "encoding-image",
287 )?.attachments,
288 ).toEqual(finalized);
289 } finally {
290 vi.unstubAllGlobals();
291 vi.resetModules();
292 }
293 });
294
295 it.each(["restore", "take"] as const)(
296 "keeps a failed finalize after another tab stashes, then handles %s",
297 async (action) => {
298 const storage = createMemoryStorage();
299 vi.stubGlobal("localStorage", {
300 ...storage,
301 setItem: (key: string, value: string) => {
302 if (value.includes("rejected-image")) throw new Error("QuotaExceededError");
303 storage.setItem(key, value);
304 },
305 });
306 vi.resetModules();
307 try {
308 const { usePromptStashStore: store } = await import("./promptStashStore");
309 store.getState().stashEntry({ ...makeEntry({ id: "too-big" }), pendingImageCount: 1 });
310 vi.resetModules();
311 const { usePromptStashStore: otherTab } = await import("./promptStashStore");
312 const { attachments } = makeEntry({ id: "rejected-image", attachmentChars: 4 });
313 const images = { attachments, droppedImageNames: [], unreadableImageNames: [] };
314 expect(store.getState().finalizeEntryImages("too-big", images)).toEqual({
315 attached: true,
316 durable: false,
317 });
318 otherTab.getState().stashEntry(makeEntry({ id: "unrelated" }));
319
320 if (action === "take") {
321 otherTab.getState().takeEntry("too-big");
322 expect(store.getState().finalizeEntryImages("too-big", images)).toEqual({
323 attached: false,
324 durable: true,
325 });
326 expect(store.getState().takeEntry("too-big").entry).toBeNull();
327 return;
328 }
329
330 expect(store.getState().takeEntry("too-big").entry).toMatchObject({
331 attachments,
332 unreadableImageNames: [],
333 });
334 } finally {
335 vi.unstubAllGlobals();
336 vi.resetModules();
337 }
338 },
339 );
340 });
341
342 describe("prompt stash context records", () => {
343 it("restores the records behind a persisted prompt's chips", () => {
344 const records = [
345 {
346 version: 1 as const,
347 contextId: "ctx-1" as never,
348 kind: "terminal" as const,
349 label: "Terminal 1 line 4",
350 terminalId: "default",
351 terminalLabel: "Terminal 1",
352 lineStart: 4,
353 lineEnd: 4,
354 text: "boom",
355 },
356 ];
357 writePromptStashStorageForTest(
358 JSON.stringify({
359 version: 2,
360 state: {
361 entries: [
362 {
363 id: "entry-records",
364 createdAt: "2026-01-01T00:00:00.000Z",
365 prompt: "see [Terminal 1 line 4](t3-context://v1/terminal/ctx-1)",
366 attachments: [],
367 droppedImageNames: [],
368 records,
369 },
370 ],
371 },
372 }),
373 );
374 const taken = usePromptStashStore.getState().takeEntry("entry-records");
375 expect(taken.entry?.records).toEqual(records);
376 });
377 });