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

Normalizer.attachments.test.ts

561 lines21.8 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 ClientOrchestrationCommand,
9 CommandId,
10 ApprovalRequestId,
11 MessageId,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17​
18import * as ServerConfig from "../config.ts";
19import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
20import { cleanupFailedUploadedAttachments, normalizeDispatchCommand } from "./Normalizer.ts";
21​
22const testLayer = Layer.mergeAll(
23 WorkspacePaths.layer,
24 ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
25).pipe(Layer.provideMerge(NodeServices.layer));
26​
27const attachmentUuid = "00000000-0000-4000-8000-0000000000aa";
28const isClientCommand = Schema.is(ClientOrchestrationCommand);
29​
30function turnStartCommand(input: {
31 readonly threadId?: string;
32 readonly attachments: ReadonlyArray<
33 | { readonly id: string; readonly sizeBytes: number }
34 | { readonly dataUrl: string; readonly sizeBytes: number }
35 >;
36}): ClientOrchestrationCommand {
37 return {
38 type: "thread.turn.start",
39 commandId: CommandId.make("command-1"),
40 threadId: ThreadId.make(input.threadId ?? "thread-1"),
41 message: {
42 messageId: MessageId.make("message-1"),
43 role: "user",
44 text: "look at this",
45 attachments: input.attachments.map((attachment) => ({
46 type: "image" as const,
47 name: "screenshot.png",
48 mimeType: "image/png",
49 ...attachment,
50 })),
51 },
52 runtimeMode: "full-access",
53 interactionMode: "default",
54 createdAt: "2026-08-01T00:00:00.000Z",
55 };
57​
58describe("normalizeDispatchCommand attachments", () => {
59 it.effect("preserves inline image attachments from existing mobile clients", () =>
60 Effect.gen(function* () {
61 const config = yield* ServerConfig.ServerConfig;
62 const normalized = yield* normalizeDispatchCommand(
63 turnStartCommand({
64 attachments: [{ dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 }],
65 }),
66 );
67 if (normalized.type !== "thread.turn.start") {
68 throw new Error("Expected a thread.turn.start command.");
69 }
70​
71 const attachment = normalized.message.attachments[0]!;
72 expect(attachment.id.startsWith("thread-1-")).toBe(true);
73 expect(
74 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${attachment.id}.png`)),
75 ).toEqual(Buffer.from("pixels"));
76 }).pipe(Effect.provide(testLayer)),
77 );
78​
79 it.effect("claims uploaded attachments while retaining a retryable pending copy", () =>
80 Effect.gen(function* () {
81 const config = yield* ServerConfig.ServerConfig;
82 const bytes = Buffer.from("pixels");
83 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
84 NodeFS.writeFileSync(pendingPath, bytes);
85​
86 const normalized = yield* normalizeDispatchCommand(
87 turnStartCommand({
88 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
89 }),
90 );
91 if (normalized.type !== "thread.turn.start") {
92 throw new Error("Expected a thread.turn.start command.");
93 }
94​
95 const attachmentId = normalized.message.attachments[0]!.id;
96 expect(attachmentId.startsWith("thread-1-")).toBe(true);
97 expect(attachmentId).not.toBe(`thread-1-${attachmentUuid}`);
98 expect(NodeFS.existsSync(pendingPath)).toBe(true);
99 const claimedPngPath = NodePath.join(config.attachmentsDir, `${attachmentId}.png`);
100 expect(NodeFS.existsSync(claimedPngPath)).toBe(true);
101 // A copy, not a hard link: editing the delivered file must not mutate
102 // the retryable pending upload.
103 expect(NodeFS.statSync(claimedPngPath).ino).not.toBe(NodeFS.statSync(pendingPath).ino);
104 expect(NodeFS.readFileSync(claimedPngPath)).toEqual(bytes);
105 }).pipe(Effect.provide(testLayer)),
106 );
107​
108 it.effect("normalizes inline and uploaded attachments in the same turn", () =>
109 Effect.gen(function* () {
110 const config = yield* ServerConfig.ServerConfig;
111 NodeFS.writeFileSync(
112 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
113 Buffer.from("pixels"),
114 );
115​
116 const normalized = yield* normalizeDispatchCommand(
117 turnStartCommand({
118 attachments: [
119 { dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
120 { id: `pending-${attachmentUuid}`, sizeBytes: 6 },
121 ],
122 }),
123 );
124 if (normalized.type !== "thread.turn.start") {
125 throw new Error("Expected a thread.turn.start command.");
126 }
127​
128 expect(normalized.message.attachments).toHaveLength(2);
129 expect(normalized.message.attachments[1]?.id.startsWith("thread-1-")).toBe(true);
130 }).pipe(Effect.provide(testLayer)),
131 );
132​
133 it.effect("claims uploaded documents without changing their original extension", () =>
134 Effect.gen(function* () {
135 const config = yield* ServerConfig.ServerConfig;
136 const pendingId = `pending-${attachmentUuid}-pdf`;
137 const pendingPath = NodePath.join(config.attachmentsDir, `${pendingId}.pdf`);
138 NodeFS.writeFileSync(pendingPath, Buffer.from("report"));
139​
140 const imageCommand = turnStartCommand({ attachments: [] });
141 if (imageCommand.type !== "thread.turn.start") {
142 throw new Error("Expected a thread.turn.start command.");
143 }
144 const normalized = yield* normalizeDispatchCommand({
145 ...imageCommand,
146 message: {
147 ...imageCommand.message,
148 attachments: [
149 {
150 type: "file",
151 id: pendingId,
152 name: "report.pdf",
153 mimeType: "application/pdf",
154 sizeBytes: 6,
155 },
156 ],
157 },
158 });
159 if (normalized.type !== "thread.turn.start") {
160 throw new Error("Expected a thread.turn.start command.");
161 }
162​
163 const attachment = normalized.message.attachments[0]!;
164 expect(attachment.type).toBe("file");
165 expect(attachment.id).toMatch(/^thread-1-.*-pdf$/);
166 const claimedPath = NodePath.join(config.attachmentsDir, `${attachment.id}.pdf`);
167 expect(NodeFS.readFileSync(claimedPath)).toEqual(Buffer.from("report"));
168 expect(NodeFS.statSync(claimedPath).ino).not.toBe(NodeFS.statSync(pendingPath).ino);
169 }).pipe(Effect.provide(testLayer)),
170 );
171​
172 it.effect("retries a failed bootstrap with a fresh thread id", () =>
173 Effect.gen(function* () {
174 const config = yield* ServerConfig.ServerConfig;
175 const bytes = Buffer.from("pixels");
176 NodeFS.writeFileSync(
177 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
178 bytes,
179 );
180​
181 const first = yield* normalizeDispatchCommand(
182 turnStartCommand({
183 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
184 }),
185 );
186 if (first.type !== "thread.turn.start") {
187 throw new Error("Expected a thread.turn.start command.");
188 }
189 NodeFS.rmSync(
190 NodePath.join(config.attachmentsDir, `${first.message.attachments[0]!.id}.png`),
191 );
192​
193 const retried = yield* normalizeDispatchCommand(
194 turnStartCommand({
195 threadId: "thread-retry",
196 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: bytes.byteLength }],
197 }),
198 );
199 if (retried.type !== "thread.turn.start") {
200 throw new Error("Expected a thread.turn.start command.");
201 }
202 expect(retried.message.attachments[0]?.id.startsWith("thread-retry-")).toBe(true);
203 }).pipe(Effect.provide(testLayer)),
204 );
205​
206 it.effect("removes failed attachment claims without deleting their pending uploads", () =>
207 Effect.gen(function* () {
208 const config = yield* ServerConfig.ServerConfig;
209 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
210 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
211 const command = turnStartCommand({
212 attachments: [
213 { dataUrl: "data:image/png;base64,cGl4ZWxz", sizeBytes: 6 },
214 { id: `pending-${attachmentUuid}`, sizeBytes: 6 },
215 ],
216 });
217 const normalized = yield* normalizeDispatchCommand(command);
218 if (normalized.type !== "thread.turn.start") {
219 throw new Error("Expected a thread.turn.start command.");
220 }
221​
222 const inlinePath = NodePath.join(
223 config.attachmentsDir,
224 `${normalized.message.attachments[0]!.id}.png`,
225 );
226 const claimedPath = NodePath.join(
227 config.attachmentsDir,
228 `${normalized.message.attachments[1]!.id}.png`,
229 );
230 yield* cleanupFailedUploadedAttachments(command, normalized);
231​
232 expect(NodeFS.existsSync(pendingPath)).toBe(true);
233 expect(NodeFS.existsSync(claimedPath)).toBe(false);
234 expect(NodeFS.existsSync(inlinePath)).toBe(true);
235 }).pipe(Effect.provide(testLayer)),
236 );
237​
238 it.effect("removes a failed claimed copy after its pending original was removed", () =>
239 Effect.gen(function* () {
240 const config = yield* ServerConfig.ServerConfig;
241 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
242 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
243 const command = turnStartCommand({
244 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
245 });
246 const normalized = yield* normalizeDispatchCommand(command);
247 if (normalized.type !== "thread.turn.start") {
248 throw new Error("Expected a thread.turn.start command.");
249 }
250​
251 const claimedPath = NodePath.join(
252 config.attachmentsDir,
253 `${normalized.message.attachments[0]!.id}.png`,
254 );
255 NodeFS.rmSync(pendingPath);
256​
257 yield* cleanupFailedUploadedAttachments(command, normalized);
258​
259 expect(NodeFS.existsSync(claimedPath)).toBe(false);
260 }).pipe(Effect.provide(testLayer)),
261 );
262​
263 it.effect("keeps concurrent claims independent when one dispatch fails", () =>
264 Effect.gen(function* () {
265 const config = yield* ServerConfig.ServerConfig;
266 const pendingPath = NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`);
267 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
268 const command = turnStartCommand({
269 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
270 });
271​
272 const [failed, succeeded] = yield* Effect.all(
273 [normalizeDispatchCommand(command), normalizeDispatchCommand(command)],
274 { concurrency: 2 },
275 );
276 if (failed.type !== "thread.turn.start" || succeeded.type !== "thread.turn.start") {
277 throw new Error("Expected thread.turn.start commands.");
278 }
279​
280 const failedPath = NodePath.join(
281 config.attachmentsDir,
282 `${failed.message.attachments[0]!.id}.png`,
283 );
284 const succeededPath = NodePath.join(
285 config.attachmentsDir,
286 `${succeeded.message.attachments[0]!.id}.png`,
287 );
288 expect(failedPath).not.toBe(succeededPath);
289​
290 yield* cleanupFailedUploadedAttachments(command, failed);
291​
292 expect(NodeFS.existsSync(pendingPath)).toBe(true);
293 expect(NodeFS.existsSync(failedPath)).toBe(false);
294 expect(NodeFS.existsSync(succeededPath)).toBe(true);
295 }).pipe(Effect.provide(testLayer)),
296 );
297​
298 it.effect("removes earlier claimed copies when a later attachment cannot be normalized", () =>
299 Effect.gen(function* () {
300 const config = yield* ServerConfig.ServerConfig;
301 const pendingId = `pending-${attachmentUuid}`;
302 const pendingPath = NodePath.join(config.attachmentsDir, `${pendingId}.png`);
303 NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
304​
305 const failure = yield* normalizeDispatchCommand(
306 turnStartCommand({
307 attachments: [
308 { id: pendingId, sizeBytes: 6 },
309 {
310 id: "pending-00000000-0000-4000-8000-0000000000ff",
311 sizeBytes: 6,
312 },
313 ],
314 }),
315 ).pipe(Effect.flip);
316​
317 expect(failure.message).toContain("not found");
318 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${pendingId}.png`]);
319 }).pipe(Effect.provide(testLayer)),
320 );
321​
322 it.effect("rejects uploaded attachments with the wrong size or thread", () =>
323 Effect.gen(function* () {
324 const config = yield* ServerConfig.ServerConfig;
325 NodeFS.writeFileSync(
326 NodePath.join(config.attachmentsDir, `pending-${attachmentUuid}.png`),
327 Buffer.from("pixels"),
328 );
329​
330 const wrongSize = yield* normalizeDispatchCommand(
331 turnStartCommand({
332 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 999 }],
333 }),
334 ).pipe(Effect.flip);
335 expect(wrongSize.message).toContain("size");
336​
337 const wrongThread = yield* normalizeDispatchCommand(
338 turnStartCommand({
339 attachments: [{ id: `another-thread-${attachmentUuid}`, sizeBytes: 6 }],
340 }),
341 ).pipe(Effect.flip);
342 expect(wrongThread.message).toContain("pending upload");
343​
344 const mismatchedTypeCommand = turnStartCommand({
345 attachments: [{ id: `pending-${attachmentUuid}`, sizeBytes: 6 }],
346 });
347 if (mismatchedTypeCommand.type !== "thread.turn.start") {
348 throw new Error("Expected a thread.turn.start command.");
349 }
350 const mismatchedType = yield* normalizeDispatchCommand({
351 ...mismatchedTypeCommand,
352 message: {
353 ...mismatchedTypeCommand.message,
354 attachments: mismatchedTypeCommand.message.attachments.map((attachment) => ({
355 ...attachment,
356 mimeType: "image/jpeg",
357 })),
358 },
359 }).pipe(Effect.flip);
360 expect(mismatchedType.message).toContain("attachment type");
361 }).pipe(Effect.provide(testLayer)),
362 );
363});
364​
365describe("question attachments", () => {
366 it.effect("enforces the total response limit and claims duplicate filenames independently", () =>
367 Effect.gen(function* () {
368 const config = yield* ServerConfig.ServerConfig;
369 const id = `pending-${attachmentUuid}-txt`;
370 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.txt`), "report");
371 const attachment = {
372 type: "file" as const,
373 id,
374 name: 'notes "final" ü.txt',
375 mimeType: "text/plain",
376 sizeBytes: 6,
377 };
378 const command: ClientOrchestrationCommand = {
379 type: "thread.user-input.respond",
380 commandId: CommandId.make("answer-cap"),
381 threadId: ThreadId.make("thread-1"),
382 requestId: ApprovalRequestId.make("request-cap"),
383 answers: { first: "", second: "" },
384 createdAt: "2026-08-01T00:00:00.000Z",
385 attachmentsByQuestionId: {
386 first: Array.from({ length: 4 }, () => attachment),
387 second: Array.from({ length: 5 }, () => attachment),
388 },
389 };
390 const failure = yield* normalizeDispatchCommand(command).pipe(Effect.flip);
391 expect(failure.message).toContain("up to 8");
392 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${id}.txt`]);
393 const accepted = {
394 ...command,
395 attachmentsByQuestionId: {
396 ...command.attachmentsByQuestionId,
397 second: Array.from({ length: 4 }, () => attachment),
398 },
399 };
400 const normalized = yield* normalizeDispatchCommand(accepted);
401 if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
402 const attachments = Object.values(normalized.attachmentsByQuestionId!).flat();
403 expect(attachments).toHaveLength(8);
404 expect(new Set(attachments.map((item) => item.id)).size).toBe(8);
405 for (const item of attachments) {
406 expect(item.name).toBe(attachment.name);
407 expect(
408 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${item.id}.txt`), "utf8"),
409 ).toBe("report");
410 }
411 yield* cleanupFailedUploadedAttachments(accepted, normalized);
412 expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${id}.txt`]);
413 }).pipe(Effect.provide(testLayer)),
414 );
415 it("requires uploaded metadata for question images, including pasted images", () => {
416 expect(
417 isClientCommand({
418 type: "thread.user-input.respond",
419 commandId: "answer",
420 threadId: "thread-1",
421 requestId: "request",
422 answers: { q: "" },
423 createdAt: "2026-08-01T00:00:00.000Z",
424 attachmentsByQuestionId: {
425 q: [
426 {
427 type: "image",
428 name: "image.png",
429 mimeType: "image/png",
430 sizeBytes: 6,
431 dataUrl: "data:image/png;base64,cGl4ZWxz",
432 },
433 ],
434 },
435 }),
436 ).toBe(false);
437 });
438​
439 it.effect("preserves a __proto__ question key and cleans up its claimed files", () =>
440 Effect.gen(function* () {
441 const config = yield* ServerConfig.ServerConfig;
442 const id = `pending-${attachmentUuid}`;
443 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.png`), "pixels");
444 const command: ClientOrchestrationCommand = {
445 type: "thread.user-input.respond",
446 commandId: CommandId.make("answer"),
447 threadId: ThreadId.make("thread-1"),
448 requestId: ApprovalRequestId.make("request"),
449 answers: { ["__proto__"]: "" },
450 createdAt: "2026-08-01T00:00:00.000Z",
451 attachmentsByQuestionId: {
452 ["__proto__"]: [
453 { type: "image", id, name: "image.png", mimeType: "image/png", sizeBytes: 6 },
454 ],
455 },
456 };
457 const normalized = yield* normalizeDispatchCommand(command);
458 if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
459 expect(Object.keys(normalized.attachmentsByQuestionId!)).toEqual(["__proto__"]);
460 const attachment = normalized.attachmentsByQuestionId!["__proto__"]![0]!;
461 const claimedPath = NodePath.join(config.attachmentsDir, `${attachment.id}.png`);
462 expect(NodeFS.existsSync(claimedPath)).toBe(true);
463 yield* cleanupFailedUploadedAttachments(command, normalized);
464 expect(NodeFS.existsSync(claimedPath)).toBe(false);
465 }).pipe(Effect.provide(testLayer)),
466 );
467 it.effect(
468 "claims images and files by question, preserves answers, and cleans up failed dispatches",
469 () =>
470 Effect.gen(function* () {
471 const config = yield* ServerConfig.ServerConfig;
472 const imageId = `pending-${attachmentUuid}`;
473 const fileId = `pending-${attachmentUuid}-txt`;
474 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${imageId}.png`), "pixels");
475 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${fileId}.txt`), "report");
476 const command: ClientOrchestrationCommand = {
477 type: "thread.user-input.respond",
478 commandId: CommandId.make("answer"),
479 threadId: ThreadId.make("thread-1"),
480 requestId: ApprovalRequestId.make("request"),
481 answers: { q1: ["Selected option"], q2: "" },
482 createdAt: "2026-08-01T00:00:00.000Z",
483 attachmentsByQuestionId: {
484 q1: [
485 {
486 type: "image",
487 id: imageId,
488 name: "image.png",
489 mimeType: "image/png",
490 sizeBytes: 6,
491 },
492 ],
493 q2: [
494 {
495 type: "file",
496 id: fileId,
497 name: "report.txt",
498 mimeType: "text/plain",
499 sizeBytes: 6,
500 },
501 ],
502 },
503 };
504 const normalized = yield* normalizeDispatchCommand(command);
505 if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
506 expect(normalized.answers).toEqual(command.answers);
507 const image = normalized.attachmentsByQuestionId!.q1![0]!;
508 const file = normalized.attachmentsByQuestionId!.q2![0]!;
509 expect(
510 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${image.id}.png`), "utf8"),
511 ).toBe("pixels");
512 expect(
513 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${file.id}.txt`), "utf8"),
514 ).toBe("report");
515 yield* cleanupFailedUploadedAttachments(command, normalized);
516 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${image.id}.png`))).toBe(
517 false,
518 );
519 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${file.id}.txt`))).toBe(
520 false,
521 );
522 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${imageId}.png`))).toBe(
523 true,
524 );
525 const retry = yield* normalizeDispatchCommand(command);
526 expect(retry.type).toBe("thread.user-input.respond");
527 }).pipe(Effect.provide(testLayer)),
528 );
529​
530 it.effect("removes all claimed copies if a later question upload is missing", () =>
531 Effect.gen(function* () {
532 const config = yield* ServerConfig.ServerConfig;
533 const id = `pending-${attachmentUuid}`;
534 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.png`), "pixels");
535 const result = yield* normalizeDispatchCommand({
536 type: "thread.user-input.respond",
537 commandId: CommandId.make("answer"),
538 threadId: ThreadId.make("thread-1"),
539 requestId: ApprovalRequestId.make("request"),
540 answers: { q1: "", q2: "" },
541 createdAt: "2026-08-01T00:00:00.000Z",
542 attachmentsByQuestionId: {
543 q1: [{ type: "image", id, name: "image.png", mimeType: "image/png", sizeBytes: 6 }],
544 q2: [
545 {
546 type: "file",
547 id: `${id}-txt`,
548 name: "missing.txt",
549 mimeType: "text/plain",
550 sizeBytes: 6,
551 },
552 ],
553 },
554 }).pipe(Effect.result);
555 expect(result._tag).toBe("Failure");
556 expect(
557 NodeFS.readdirSync(config.attachmentsDir).filter((name) => name.startsWith("thread-1-")),
558 ).toEqual([]);
559 }).pipe(Effect.provide(testLayer)),
560 );
561});