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

Normalizer.attachments.test.ts

360 lines13.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4​
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import {
8 type ClientOrchestrationCommand,
9 CommandId,
10 MessageId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15​
16import * as ServerConfig from "../config.ts";
17import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
18import { cleanupFailedUploadedAttachments, normalizeDispatchCommand } from "./Normalizer.ts";
19​
20const testLayer = Layer.mergeAll(
21 WorkspacePaths.layer,
22 ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
23).pipe(Layer.provideMerge(NodeServices.layer));
24​
25const attachmentUuid = "00000000-0000-4000-8000-0000000000aa";
26​
27function turnStartCommand(input: {
28 readonly threadId?: string;
29 readonly attachments: ReadonlyArray<
30 | { readonly id: string; readonly sizeBytes: number }
31 | { readonly dataUrl: string; readonly sizeBytes: number }
32 >;
33}): ClientOrchestrationCommand {
34 return {
35 type: "thread.turn.start",
36 commandId: CommandId.make("command-1"),
37 threadId: ThreadId.make(input.threadId ?? "thread-1"),
38 message: {
39 messageId: MessageId.make("message-1"),
40 role: "user",
41 text: "look at this",
42 attachments: input.attachments.map((attachment) => ({
43 type: "image" as const,
44 name: "screenshot.png",
45 mimeType: "image/png",
46 ...attachment,
47 })),
48 },
49 runtimeMode: "full-access",
50 interactionMode: "default",
51 createdAt: "2026-08-01T00:00:00.000Z",
52 };
54​
55describe("normalizeDispatchCommand attachments", () => {
56 it.effect("preserves inline image attachments from existing mobile clients", () =>
57 Effect.gen(function* () {
58 const config = yield* ServerConfig.ServerConfig;
59 const normalized = yield* normalizeDispatchCommand(
60 turnStartCommand({
61 attachments: [{ dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 }],
62 }),
63 );
64 if (normalized.type !== "thread.turn.start") {
65 throw new Error("Expected a thread.turn.start command.");
66 }
67​
68 const attachment = normalized.message.attachments[0]!;
69 expect(attachment.id.startsWith("thread-1-")).toBe(true);
70 expect(
71 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${attachment.id}.png`)),
72 ).toEqual(Buffer.from("pixels"));
73 }).pipe(Effect.provide(testLayer)),
74 );
75​
76 it.effect("claims uploaded attachments while retaining a retryable pending copy", () =>
77 Effect.gen(function* () {
78 const config = yield* ServerConfig.ServerConfig;
79 const bytes = Buffer.from("pixels");
80 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
81 NodeFS.writeFileSync(pendingPath, bytes);
82​
83 const normalized = yield* normalizeDispatchCommand(
84 turnStartCommand({
85 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
86 }),
87 );
88 if (normalized.type !== "thread.turn.start") {
89 throw new Error("Expected a thread.turn.start command.");
90 }
91​
92 const attachmentId = normalized.message.attachments[0]!.id;
93 expect(attachmentId.startsWith("thread-1-")).toBe(true);
94 expect(attachmentId).not.toBe(`thread-1-${attachmentUuid}`);
95 expect(NodeFS.existsSync(pendingPath)).toBe(true);
96 const claimedPngPath = NodePath.join(config.attachmentsDir, `${attachmentId}.png`);
97 expect(NodeFS.existsSync(claimedPngPath)).toBe(true);
98 // A copy, not a hard link: editing the delivered file must not mutate
99 // the retryable pending upload.
100 expect(NodeFS.statSync(claimedPngPath).ino).not.toBe(NodeFS.statSync(pendingPath).ino);
101 expect(NodeFS.readFileSync(claimedPngPath)).toEqual(bytes);
102 }).pipe(Effect.provide(testLayer)),
103 );
104​
105 it.effect("normalizes inline and uploaded attachments in the same turn", () =>
106 Effect.gen(function* () {
107 const config = yield* ServerConfig.ServerConfig;
108 NodeFS.writeFileSync(
109 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
110 Buffer.from("pixels"),
111 );
112​
113 const normalized = yield* normalizeDispatchCommand(
114 turnStartCommand({
115 attachments: [
116 { dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
117 { id: `pending-${attachmentUuid}`, sizeBytes: 6 },
118 ],
119 }),
120 );
121 if (normalized.type !== "thread.turn.start") {
122 throw new Error("Expected a thread.turn.start command.");
123 }
124​
125 expect(normalized.message.attachments).toHaveLength(2);
126 expect(normalized.message.attachments[1]?.id.startsWith("thread-1-")).toBe(true);
127 }).pipe(Effect.provide(testLayer)),
128 );
129​
130 it.effect("claims uploaded documents without changing their original extension", () =>
131 Effect.gen(function* () {
132 const config = yield* ServerConfig.ServerConfig;
133 const pendingId = `pending-${attachmentUuid}-pdf`;
134 const pendingPath = NodePath.join(config.attachmentsDir, `${pendingId}.pdf`);
135 NodeFS.writeFileSync(pendingPath, Buffer.from("report"));
136​
137 const imageCommand = turnStartCommand({ attachments: [] });
138 if (imageCommand.type !== "thread.turn.start") {
139 throw new Error("Expected a thread.turn.start command.");
140 }
141 const normalized = yield* normalizeDispatchCommand({
142 ...imageCommand,
143 message: {
144 ...imageCommand.message,
145 attachments: [
146 {
147 type: "file",
148 id: pendingId,
149 name: "report.pdf",
150 mimeType: "application/pdf",
151 sizeBytes: 6,
152 },
153 ],
154 },
155 });
156 if (normalized.type !== "thread.turn.start") {
157 throw new Error("Expected a thread.turn.start command.");
158 }
159​
160 const attachment = normalized.message.attachments[0]!;
161 expect(attachment.type).toBe("file");
162 expect(attachment.id).toMatch(/^thread-1-.*-pdf$/);
163 const claimedPath = NodePath.join(config.attachmentsDir, `${attachment.id}.pdf`);
164 expect(NodeFS.readFileSync(claimedPath)).toEqual(Buffer.from("report"));
165 expect(NodeFS.statSync(claimedPath).ino).not.toBe(NodeFS.statSync(pendingPath).ino);
166 }).pipe(Effect.provide(testLayer)),
167 );
168​
169 it.effect("retries a failed bootstrap with a fresh thread id", () =>
170 Effect.gen(function* () {
171 const config = yield* ServerConfig.ServerConfig;
172 const bytes = Buffer.from("pixels");
173 NodeFS.writeFileSync(
174 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
175 bytes,
176 );
177​
178 const first = yield* normalizeDispatchCommand(
179 turnStartCommand({
180 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
181 }),
182 );
183 if (first.type !== "thread.turn.start") {
184 throw new Error("Expected a thread.turn.start command.");
185 }
186 NodeFS.rmSync(
187 NodePath.join(config.attachmentsDir, `${first.message.attachments[0]!.id}.png`),
188 );
189​
190 const retried = yield* normalizeDispatchCommand(
191 turnStartCommand({
192 threadId: "thread-retry",
193 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
194 }),
195 );
196 if (retried.type !== "thread.turn.start") {
197 throw new Error("Expected a thread.turn.start command.");
198 }
199 expect(retried.message.attachments[0]?.id.startsWith("thread-retry-")).toBe(true);
200 }).pipe(Effect.provide(testLayer)),
201 );
202​
203 it.effect("removes failed attachment claims without deleting their pending uploads", () =>
204 Effect.gen(function* () {
205 const config = yield* ServerConfig.ServerConfig;
206 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
207 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
208 const command = turnStartCommand({
209 attachments: [
210 { dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
211 { id: `pending-${attachmentUuid}`, sizeBytes: 6 },
212 ],
213 });
214 const normalized = yield* normalizeDispatchCommand(command);
215 if (normalized.type !== "thread.turn.start") {
216 throw new Error("Expected a thread.turn.start command.");
217 }
218​
219 const inlinePath = NodePath.join(
220 config.attachmentsDir,
221 `${normalized.message.attachments[0]!.id}.png`,
222 );
223 const claimedPath = NodePath.join(
224 config.attachmentsDir,
225 `${normalized.message.attachments[1]!.id}.png`,
226 );
227 yield* cleanupFailedUploadedAttachments(command, normalized);
228​
229 expect(NodeFS.existsSync(pendingPath)).toBe(true);
230 expect(NodeFS.existsSync(claimedPath)).toBe(false);
231 expect(NodeFS.existsSync(inlinePath)).toBe(true);
232 }).pipe(Effect.provide(testLayer)),
233 );
234​
235 it.effect("removes a failed claimed copy after its pending original was removed", () =>
236 Effect.gen(function* () {
237 const config = yield* ServerConfig.ServerConfig;
238 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
239 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
240 const command = turnStartCommand({
241 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
242 });
243 const normalized = yield* normalizeDispatchCommand(command);
244 if (normalized.type !== "thread.turn.start") {
245 throw new Error("Expected a thread.turn.start command.");
246 }
247​
248 const claimedPath = NodePath.join(
249 config.attachmentsDir,
250 `${normalized.message.attachments[0]!.id}.png`,
251 );
252 NodeFS.rmSync(pendingPath);
253​
254 yield* cleanupFailedUploadedAttachments(command, normalized);
255​
256 expect(NodeFS.existsSync(claimedPath)).toBe(false);
257 }).pipe(Effect.provide(testLayer)),
258 );
259​
260 it.effect("keeps concurrent claims independent when one dispatch fails", () =>
261 Effect.gen(function* () {
262 const config = yield* ServerConfig.ServerConfig;
263 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
264 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
265 const command = turnStartCommand({
266 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
267 });
268​
269 const [failed, succeeded] = yield* Effect.all(
270 [normalizeDispatchCommand(command), normalizeDispatchCommand(command)],
271 { concurrency: 2 },
272 );
273 if (failed.type !== "thread.turn.start" || succeeded.type !== "thread.turn.start") {
274 throw new Error("Expected thread.turn.start commands.");
275 }
276​
277 const failedPath = NodePath.join(
278 config.attachmentsDir,
279 `${failed.message.attachments[0]!.id}.png`,
280 );
281 const succeededPath = NodePath.join(
282 config.attachmentsDir,
283 `${succeeded.message.attachments[0]!.id}.png`,
284 );
285 expect(failedPath).not.toBe(succeededPath);
286​
287 yield* cleanupFailedUploadedAttachments(command, failed);
288​
289 expect(NodeFS.existsSync(pendingPath)).toBe(true);
290 expect(NodeFS.existsSync(failedPath)).toBe(false);
291 expect(NodeFS.existsSync(succeededPath)).toBe(true);
292 }).pipe(Effect.provide(testLayer)),
293 );
294​
295 it.effect("removes earlier claimed copies when a later attachment cannot be normalized", () =>
296 Effect.gen(function* () {
297 const config = yield* ServerConfig.ServerConfig;
298 const pendingId = `pending-${attachmentUuid}`;
299 const pendingPath = NodePath.join(config.attachmentsDir, `${pendingId}.png`);
300 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
301​
302 const failure = yield* normalizeDispatchCommand(
303 turnStartCommand({
304 attachments: [
305 { id: pendingId, sizeBytes: 6 },
306 {
307 id: "pending-00000000-0000-4000-8000-0000000000ff",
308 sizeBytes: 6,
309 },
310 ],
311 }),
312 ).pipe(Effect.flip);
313​
314 expect(failure.message).toContain("not found");
315 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${pendingId}.png`]);
316 }).pipe(Effect.provide(testLayer)),
317 );
318​
319 it.effect("rejects uploaded attachments with the wrong size or thread", () =>
320 Effect.gen(function* () {
321 const config = yield* ServerConfig.ServerConfig;
322 NodeFS.writeFileSync(
323 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
324 Buffer.from("pixels"),
325 );
326​
327 const wrongSize = yield* normalizeDispatchCommand(
328 turnStartCommand({
329 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 999 }],
330 }),
331 ).pipe(Effect.flip);
332 expect(wrongSize.message).toContain("size");
333​
334 const wrongThread = yield* normalizeDispatchCommand(
335 turnStartCommand({
336 attachments: [{ id: `another-thread-${attachmentUuid}`, sizeBytes: 6 }],
337 }),
338 ).pipe(Effect.flip);
339 expect(wrongThread.message).toContain("pending upload");
340​
341 const mismatchedTypeCommand = turnStartCommand({
342 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
343 });
344 if (mismatchedTypeCommand.type !== "thread.turn.start") {
345 throw new Error("Expected a thread.turn.start command.");
346 }
347 const mismatchedType = yield* normalizeDispatchCommand({
348 ...mismatchedTypeCommand,
349 message: {
350 ...mismatchedTypeCommand.message,
351 attachments: mismatchedTypeCommand.message.attachments.map((attachment) => ({
352 ...attachment,
353 mimeType: "image/jpeg",
354 })),
355 },
356 }).pipe(Effect.flip);
357 expect(mismatchedType.message).toContain("attachment type");
358 }).pipe(Effect.provide(testLayer)),
359 );
360});