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

attachmentStore.test.ts

285 lines10.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5​
6import { describe, expect, it } from "vite-plus/test";
7​
8import {
9 attachmentFileExtension,
10 chatAttachmentStableKey,
11 createAttachmentId,
12 createDeterministicAttachmentId,
13 createPendingAttachmentId,
14 parseAttachmentUuid,
15 parseAttachmentFileExtension,
16 planAttachmentClaim,
17 parseThreadSegmentFromAttachmentId,
18 resolveAttachmentPathById,
19 sweepStalePendingAttachments,
20 threadHtmlRenderAttachmentIds,
21} from "./attachmentStore.ts";
22​
23describe("attachmentStore", () => {
24 it("derives stable attachment ids for idempotent message retries", () => {
25 const first = createDeterministicAttachmentId("thread-1", "message-1:0");
26 const retry = createDeterministicAttachmentId("thread-1", "message-1:0");
27 const next = createDeterministicAttachmentId("thread-1", "message-1:1");
28​
29 expect(first).toBe(retry);
30 expect(next).not.toBe(first);
31 expect(first && parseThreadSegmentFromAttachmentId(first)).toBe("thread-1");
32 });
33​
34 it("gives a queued edit's new image its own id instead of an earlier image's", () => {
35 const imageA = new Uint8Array([1, 2, 3]);
36 const imageB = new Uint8Array([4, 5, 6]);
37 const sent = createDeterministicAttachmentId(
38 "thread-1",
39 chatAttachmentStableKey("message-1", 0, imageA),
40 );
41 const retried = createDeterministicAttachmentId(
42 "thread-1",
43 chatAttachmentStableKey("message-1", 0, imageA),
44 );
45 const edited = createDeterministicAttachmentId(
46 "thread-1",
47 chatAttachmentStableKey("message-1", 0, imageB),
48 );
49​
50 expect(retried).toBe(sent);
51 expect(edited).not.toBe(sent);
52 });
53​
54 it("keeps deterministic ids distinct when sanitized thread segments collide", () => {
55 const dotted = createDeterministicAttachmentId("thread.a", "message-1:0");
56 const dashed = createDeterministicAttachmentId("thread-a", "message-1:0");
57​
58 expect(dotted).toBeTruthy();
59 expect(dashed).toBeTruthy();
60 expect(dotted).not.toBe(dashed);
61 expect(dotted && parseThreadSegmentFromAttachmentId(dotted)).toBe("thread-a");
62 expect(dashed && parseThreadSegmentFromAttachmentId(dashed)).toBe("thread-a");
63 });
64​
65 it("sanitizes thread ids when creating attachment ids", () => {
66 const attachmentId = createAttachmentId("thread.folder/unsafe space");
67 expect(attachmentId).toBeTruthy();
68 if (!attachmentId) {
69 return;
70 }
71​
72 const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
73 expect(threadSegment).toBeTruthy();
74 expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
75 expect(threadSegment).not.toContain(".");
76 expect(threadSegment).not.toContain("%");
77 expect(threadSegment).not.toContain("/");
78 });
79​
80 it("parses exact thread segments from attachment ids without prefix collisions", () => {
81 const fooId = "foo-00000000-0000-4000-8000-000000000001";
82 const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
83​
84 expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
85 expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
86 });
87​
88 it("normalizes created thread segments to lowercase", () => {
89 const attachmentId = createAttachmentId("Thread.Foo");
90 expect(attachmentId).toBeTruthy();
91 if (!attachmentId) {
92 return;
93 }
94 expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
95 });
96​
97 it("reserves the pending attachment segment", () => {
98 const pendingId = createPendingAttachmentId();
99 expect(parseThreadSegmentFromAttachmentId(pendingId)).toBe("pending");
100 expect(parseAttachmentUuid(pendingId)).toMatch(/^[a-f0-9-]{36}$/);
101 expect(parseThreadSegmentFromAttachmentId(createAttachmentId("pending")!)).toBe("_pending");
102 expect(parseThreadSegmentFromAttachmentId(createAttachmentId("pending_thread")!)).toBe(
103 "pending_thread",
104 );
105 });
106​
107 it("preserves safe file extensions in attachment ids and paths", () => {
108 const attachmentId = createPendingAttachmentId(".PDF");
109​
110 expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("pending");
111 expect(parseAttachmentUuid(attachmentId)).toMatch(/^[a-f0-9-]{36}$/);
112 expect(parseAttachmentFileExtension(attachmentId)).toBe("pdf");
113 expect(attachmentFileExtension("report.PDF")).toBe(".pdf");
114 expect(attachmentFileExtension("report")).toBe(".bin");
115 expect(attachmentFileExtension("report.extensiontoolong")).toBe(".bin");
116 expect(attachmentFileExtension("archive.part")).toBe(".bin");
117 expect(createAttachmentId("x".repeat(80), ".abcdefghij")?.length).toBeLessThanOrEqual(128);
118 });
119​
120 it("resolves attachment path by id using the extension that exists on disk", () => {
121 const attachmentsDir = NodeFS.mkdtempSync(
122 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
123 );
124 try {
125 const attachmentId = "thread-1-attachment";
126 const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
127 NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
128​
129 const resolved = resolveAttachmentPathById({
130 attachmentsDir,
131 attachmentId,
132 });
133 expect(resolved).toBe(pngPath);
134 } finally {
135 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
136 }
137 });
138​
139 it("returns null when no attachment file exists for the id", () => {
140 const attachmentsDir = NodeFS.mkdtempSync(
141 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
142 );
143 try {
144 const resolved = resolveAttachmentPathById({
145 attachmentsDir,
146 attachmentId: "thread-1-missing",
147 });
148 expect(resolved).toBeNull();
149 } finally {
150 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
151 }
152 });
153​
154 it("resolves generic attachments without scanning the attachment directory", () => {
155 const attachmentsDir = NodeFS.mkdtempSync(
156 NodePath.join(NodeOS.tmpdir(), "t3code-file-attachment-"),
157 );
158 try {
159 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-zip";
160 const archivePath = NodePath.join(attachmentsDir, `${attachmentId}.zip`);
161 NodeFS.writeFileSync(archivePath, Buffer.from("archive"));
162​
163 expect(resolveAttachmentPathById({ attachmentsDir, attachmentId })).toBe(archivePath);
164 } finally {
165 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
166 }
167 });
168​
169 it("plans pending attachment claims with direct filename lookups", () => {
170 const attachmentsDir = NodeFS.mkdtempSync(
171 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-claim-"),
172 );
173 try {
174 const uuid = "00000000-0000-4000-8000-000000000001";
175 const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.png`);
176 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
177​
178 const claim = planAttachmentClaim({
179 attachmentsDir,
180 threadId: "thread-1",
181 attachmentId: `pending-${uuid}`,
182 });
183 expect(claim).toMatchObject({
184 ok: true,
185 currentPath: pendingPath,
186 });
187 if (!claim.ok) {
188 return;
189 }
190 expect(parseThreadSegmentFromAttachmentId(claim.finalId)).toBe("thread-1");
191 expect(parseAttachmentUuid(claim.finalId)).not.toBe(uuid);
192 expect(claim.finalPath).toBe(NodePath.join(attachmentsDir, `${claim.finalId}.png`));
193 } finally {
194 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
195 }
196 });
197​
198 it("rejects thread-owned attachments even when thread segments collide", () => {
199 const attachmentsDir = NodeFS.mkdtempSync(
200 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-ownership-"),
201 );
202 try {
203 const attachmentId = "a-b-00000000-0000-4000-8000-000000000003";
204 NodeFS.writeFileSync(NodePath.join(attachmentsDir, `${attachmentId}.png`), "pixels");
205​
206 expect(planAttachmentClaim({ attachmentsDir, threadId: "a b", attachmentId })).toEqual({
207 ok: false,
208 reason: "attachment must be a pending upload",
209 });
210 } finally {
211 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
212 }
213 });
214​
215 it("removes expired pending and partial files without touching thread attachments", () => {
216 const attachmentsDir = NodeFS.mkdtempSync(
217 NodePath.join(NodeOS.tmpdir(), "t3code-attachment-sweep-"),
218 );
219 try {
220 const now = 1_800_000_000_000;
221 const oldTimeSeconds = (now - 2 * 24 * 60 * 60 * 1000) / 1000;
222 const uuid = "00000000-0000-4000-8000-000000000002";
223 const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.png`);
224 const pendingFilePath = NodePath.join(attachmentsDir, `pending-${uuid}-pdf.pdf`);
225 const threadPath = NodePath.join(attachmentsDir, `thread-1-${uuid}.png`);
226 const partialPath = NodePath.join(attachmentsDir, `${uuid}.part`);
227 for (const filePath of [pendingPath, pendingFilePath, threadPath, partialPath]) {
228 NodeFS.writeFileSync(filePath, Buffer.from("pixels"));
229 NodeFS.utimesSync(filePath, oldTimeSeconds, oldTimeSeconds);
230 }
231​
232 expect(sweepStalePendingAttachments({ attachmentsDir, nowMs: now })).toEqual({ deleted: 3 });
233 expect(NodeFS.existsSync(pendingPath)).toBe(false);
234 expect(NodeFS.existsSync(pendingFilePath)).toBe(false);
235 expect(NodeFS.existsSync(partialPath)).toBe(false);
236 expect(NodeFS.existsSync(threadPath)).toBe(true);
237 } finally {
238 NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
239 }
240 });
241});
242​
243describe("threadHtmlRenderAttachmentIds", () => {
244 it("returns pages this thread published and skips other threads' and failed calls", () => {
245 const own = createAttachmentId("thread-a", "html")!;
246 const other = createAttachmentId("thread-b", "html")!;
247 const render = (attachmentId: string, extra = {}) => ({
248 toolName: "mcp__t3-code__html_render",
249 output: [
250 {
251 type: "text",
252 text: JSON.stringify({ htmlRender: { attachmentId, title: "x", height: 300 }, ...extra }),
253 },
254 ],
255 });
256 expect(
257 threadHtmlRenderAttachmentIds("thread-a", [
258 render(own),
259 render(other),
260 render(createAttachmentId("thread-a", "html")!, { isError: true }),
261 { toolName: "mcp__t3-code__html_preview", output: render(own).output },
262 ]),
263 ).toEqual([own]);
264 });
265​
266 it("includes captured MCP App documents from any tool", () => {
267 const app = createAttachmentId("thread-a", "html")!;
268 expect(
269 threadHtmlRenderAttachmentIds("thread-a", [
270 {
271 toolName: "weather.get_weather",
272 output: {
273 t3McpApp: {
274 attachmentId: app,
275 server: "weather",
276 tool: "get_weather",
277 resourceUri: "ui://weather/dashboard",
278 },
279 result: { content: [] },
280 },
281 },
282 ]),
283 ).toEqual([app]);
284 });
285});