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