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