Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { expect, it } from "@effect/vitest";
6import {
7 ChatAttachmentId,
8 CommandId,
9 EventId,
10 MessageId,
11 ProjectId,
12 ProviderInstanceId,
13 RuntimeRequestId,
14 ThreadId,
15 TurnItemId,
16 type OrchestrationV2Command,
17 type OrchestrationV2ServerCommand,
18 type OrchestrationV2StoredEvent,
19 type UserInputAttachments,
20} from "@t3tools/contracts";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import { createPendingAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
25import * as ServerConfig from "../config.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import {
28 OrchestratorCommandPreviouslyRejectedError,
29 OrchestratorDispatchError,
30} from "./Orchestrator.ts";
31import * as ThreadManagementService from "./ThreadManagementService.ts";
32import { dispatchCommand, sendToThread } from "./ThreadMessageIntake.ts";
33
34const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
35 prefix: "t3-question-intake-",
36}).pipe(Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ServerSettings.layerTest()));
37
38const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) =>
39 Layer.mock(ThreadManagementService.ThreadManagementService)({
40 dispatch: (command) => {
41 captured.push(command);
42 return Effect.fail(
43 new OrchestratorDispatchError({
44 commandId: command.commandId,
45 commandType: command.type,
46 cause: "Stop after intake",
47 }),
48 );
49 },
50 });
51
52const NOW = DateTime.makeUnsafe("2026-09-13T00:00:00.000Z");
53
54const answeredRespondEvents = (input: {
55 readonly threadId: ThreadId;
56 readonly requestId: string;
57 readonly attachmentsByQuestionId: UserInputAttachments;
58}): OrchestrationV2StoredEvent[] => [
59 {
60 sequence: 1,
61 commandId: null,
62 event: {
63 id: EventId.make("evt-recorded-answer"),
64 type: "turn-item.updated",
65 threadId: input.threadId,
66 occurredAt: NOW,
67 payload: {
68 id: TurnItemId.make("item-recorded-answer"),
69 type: "user_input_request",
70 threadId: input.threadId,
71 runId: null,
72 nodeId: null,
73 providerThreadId: null,
74 providerTurnId: null,
75 nativeItemRef: null,
76 parentItemId: null,
77 ordinal: 1,
78 status: "completed",
79 title: null,
80 startedAt: null,
81 completedAt: NOW,
82 updatedAt: NOW,
83 requestId: RuntimeRequestId.make(input.requestId),
84 questions: [],
85 questionAnswer: {
86 requestId: input.requestId,
87 answers: {},
88 attachmentsByQuestionId: input.attachmentsByQuestionId,
89 },
90 },
91 },
92 },
93];
94
95const textOnlyRespondEvents = (input: {
96 readonly threadId: ThreadId;
97 readonly requestId: string;
98}): OrchestrationV2StoredEvent[] => [
99 {
100 sequence: 1,
101 commandId: null,
102 event: {
103 id: EventId.make("evt-recorded-answer"),
104 type: "turn-item.updated",
105 threadId: input.threadId,
106 occurredAt: NOW,
107 payload: {
108 id: TurnItemId.make("item-recorded-answer"),
109 type: "user_input_request",
110 threadId: input.threadId,
111 runId: null,
112 nodeId: null,
113 providerThreadId: null,
114 providerTurnId: null,
115 nativeItemRef: null,
116 parentItemId: null,
117 ordinal: 1,
118 status: "completed",
119 title: null,
120 startedAt: null,
121 completedAt: NOW,
122 updatedAt: NOW,
123 requestId: RuntimeRequestId.make(input.requestId),
124 questions: [],
125 },
126 },
127 },
128];
129
130it.effect("claims question uploads and passes readable paths through the V2 request command", () =>
131 Effect.gen(function* () {
132 const config = yield* ServerConfig.ServerConfig;
133 const id = ChatAttachmentId.make(createPendingAttachmentId()!);
134 NodeFS.writeFileSync(
135 NodePath.join(config.attachmentsDir, `${id}.png`),
136 new Uint8Array([1, 2, 3]),
137 );
138 const captured: OrchestrationV2ServerCommand[] = [];
139 yield* dispatchCommand({
140 type: "runtime-request.respond",
141 commandId: CommandId.make("answer-1"),
142 threadId: ThreadId.make("thread-answer"),
143 requestId: RuntimeRequestId.make("request-1"),
144 answers: { q: ["Selected option"] },
145 attachmentsByQuestionId: {
146 q: [{ type: "image", id, name: "screen.png", mimeType: "image/png", sizeBytes: 3 }],
147 },
148 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
149 expect(captured).toHaveLength(1);
150 const command = captured[0]!;
151 expect(command.type).toBe("runtime-request.respond");
152 if (command.type !== "runtime-request.respond") return;
153 const attachment = command.attachmentsByQuestionId?.q?.[0];
154 expect(attachment).toBeDefined();
155 const path = resolveAttachmentPath({
156 attachmentsDir: config.attachmentsDir,
157 attachment: attachment!,
158 });
159 expect(path).not.toBeNull();
160 expect(NodeFS.readFileSync(path!)).toEqual(Buffer.from([1, 2, 3]));
161 expect(command.answers?.q).toEqual([
162 "Selected option",
163 `Attached image "screen.png": "${path}"`,
164 ]);
165 }).pipe(Effect.provide(layerIntakeTest)),
166);
167
168it.effect("rolls back earlier question claims when a later pending upload is missing", () =>
169 Effect.gen(function* () {
170 const config = yield* ServerConfig.ServerConfig;
171 const threadId = ThreadId.make("thread-q-fail");
172 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
173 const existingId = ChatAttachmentId.make("thread-q-fail-00000000-0000-4000-8000-000000000001");
174 NodeFS.writeFileSync(
175 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
176 new Uint8Array([1, 2, 3]),
177 );
178 NodeFS.writeFileSync(
179 NodePath.join(config.attachmentsDir, `${existingId}.png`),
180 new Uint8Array([9, 9, 9, 9]),
181 );
182 const captured: OrchestrationV2ServerCommand[] = [];
183 const result = yield* dispatchCommand({
184 type: "runtime-request.respond",
185 commandId: CommandId.make("answer-missing-pending"),
186 threadId,
187 requestId: RuntimeRequestId.make("request-missing-pending"),
188 answers: { q1: ["one"], q2: ["two"] },
189 attachmentsByQuestionId: {
190 q1: [
191 {
192 type: "image",
193 id: existingId,
194 name: "keep.png",
195 mimeType: "image/png",
196 sizeBytes: 4,
197 },
198 {
199 type: "image",
200 id: pendingId,
201 name: "screen.png",
202 mimeType: "image/png",
203 sizeBytes: 3,
204 },
205 ],
206 q2: [
207 {
208 type: "image",
209 id: ChatAttachmentId.make(createPendingAttachmentId()!),
210 name: "gone.png",
211 mimeType: "image/png",
212 sizeBytes: 3,
213 },
214 ],
215 },
216 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
217 expect(result._tag).toBe("Failure");
218 if (result._tag === "Failure") {
219 expect(result.failure._tag).toBe("AttachmentClaimError");
220 }
221 expect(captured).toHaveLength(0);
222 expect(NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toEqual(
223 Buffer.from([1, 2, 3]),
224 );
225 expect(
226 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
227 entry.startsWith("thread-q-fail-"),
228 ),
229 ).toEqual([`${existingId}.png`]);
230 }).pipe(Effect.provide(layerIntakeTest)),
231);
232
233it.effect("rolls back earlier question claims when attachment path preparation fails", () =>
234 Effect.gen(function* () {
235 const config = yield* ServerConfig.ServerConfig;
236 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
237 NodeFS.writeFileSync(
238 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
239 new Uint8Array([1, 2, 3]),
240 );
241 const captured: OrchestrationV2ServerCommand[] = [];
242 const result = yield* dispatchCommand({
243 type: "runtime-request.respond",
244 commandId: CommandId.make("answer-missing-claimed"),
245 threadId: ThreadId.make("thread-path-fail"),
246 requestId: RuntimeRequestId.make("request-missing-claimed"),
247 answers: { q1: ["one"], q2: ["two"] },
248 attachmentsByQuestionId: {
249 q1: [
250 {
251 type: "image",
252 id: pendingId,
253 name: "screen.png",
254 mimeType: "image/png",
255 sizeBytes: 3,
256 },
257 ],
258 q2: [
259 {
260 type: "image",
261 id: ChatAttachmentId.make("thread-path-fail-00000000-0000-4000-8000-000000000099"),
262 name: "missing.png",
263 mimeType: "image/png",
264 sizeBytes: 3,
265 },
266 ],
267 },
268 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
269 expect(result._tag).toBe("Failure");
270 if (result._tag === "Failure") {
271 expect(result.failure._tag).toBe("AttachmentClaimError");
272 }
273 expect(captured).toHaveLength(0);
274 expect(NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toEqual(
275 Buffer.from([1, 2, 3]),
276 );
277 expect(
278 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
279 entry.startsWith("thread-path-fail-"),
280 ),
281 ).toEqual([]);
282 }).pipe(Effect.provide(layerIntakeTest)),
283);
284
285it.effect("retains claimed copies when dispatch failure may have been accepted", () =>
286 Effect.gen(function* () {
287 const config = yield* ServerConfig.ServerConfig;
288 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
289 NodeFS.writeFileSync(
290 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
291 new Uint8Array([1, 2, 3]),
292 );
293 const captured: OrchestrationV2ServerCommand[] = [];
294 const result = yield* dispatchCommand({
295 type: "runtime-request.respond",
296 commandId: CommandId.make("answer-ambiguous"),
297 threadId: ThreadId.make("thread-ambiguous"),
298 requestId: RuntimeRequestId.make("request-ambiguous"),
299 answers: { q: ["one"] },
300 attachmentsByQuestionId: {
301 q: [
302 {
303 type: "image",
304 id: pendingId,
305 name: "screen.png",
306 mimeType: "image/png",
307 sizeBytes: 3,
308 },
309 ],
310 },
311 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
312 expect(result._tag).toBe("Failure");
313 expect(captured).toHaveLength(1);
314 const threadFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
315 entry.startsWith("thread-ambiguous-"),
316 );
317 expect(threadFiles).toHaveLength(1);
318 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
319 }).pipe(Effect.provide(layerIntakeTest)),
320);
321
322it.effect("releases claimed copies when the command was already rejected", () =>
323 Effect.gen(function* () {
324 const config = yield* ServerConfig.ServerConfig;
325 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
326 NodeFS.writeFileSync(
327 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
328 new Uint8Array([1, 2, 3]),
329 );
330 const result = yield* dispatchCommand({
331 type: "runtime-request.respond",
332 commandId: CommandId.make("answer-rejected"),
333 threadId: ThreadId.make("thread-rejected"),
334 requestId: RuntimeRequestId.make("request-rejected"),
335 answers: { q: ["one"] },
336 attachmentsByQuestionId: {
337 q: [
338 {
339 type: "image",
340 id: pendingId,
341 name: "screen.png",
342 mimeType: "image/png",
343 sizeBytes: 3,
344 },
345 ],
346 },
347 }).pipe(
348 Effect.provide(
349 Layer.mock(ThreadManagementService.ThreadManagementService)({
350 dispatch: (command) =>
351 Effect.fail(
352 new OrchestratorCommandPreviouslyRejectedError({
353 commandId: command.commandId,
354 commandType: command.type,
355 detail: "rejected earlier",
356 }),
357 ),
358 }),
359 ),
360 Effect.result,
361 );
362 expect(result._tag).toBe("Failure");
363 expect(
364 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
365 entry.startsWith("thread-rejected-"),
366 ),
367 ).toEqual([]);
368 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
369 }).pipe(Effect.provide(layerIntakeTest)),
370);
371
372it.effect("releases claimed copies when dispatch replays an earlier accepted response", () =>
373 Effect.gen(function* () {
374 const config = yield* ServerConfig.ServerConfig;
375 const threadId = ThreadId.make("thread-replay");
376 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
377 NodeFS.writeFileSync(
378 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
379 new Uint8Array([1, 2, 3]),
380 );
381 const earlierAttachment = {
382 type: "image" as const,
383 id: ChatAttachmentId.make("thread-replay-00000000-0000-4000-8000-0000000000aa"),
384 name: "screen.png",
385 mimeType: "image/png",
386 sizeBytes: 3,
387 };
388 NodeFS.writeFileSync(
389 NodePath.join(config.attachmentsDir, `${earlierAttachment.id}.png`),
390 new Uint8Array([4, 4, 4]),
391 );
392 const storedEvents = answeredRespondEvents({
393 threadId,
394 requestId: "request-replay",
395 attachmentsByQuestionId: { q: [earlierAttachment] },
396 });
397 const result = yield* dispatchCommand({
398 type: "runtime-request.respond",
399 commandId: CommandId.make("answer-replay"),
400 threadId,
401 requestId: RuntimeRequestId.make("request-replay"),
402 answers: { q: ["one"] },
403 attachmentsByQuestionId: {
404 q: [
405 {
406 type: "image",
407 id: pendingId,
408 name: "screen.png",
409 mimeType: "image/png",
410 sizeBytes: 3,
411 },
412 ],
413 },
414 }).pipe(
415 Effect.provide(
416 Layer.mock(ThreadManagementService.ThreadManagementService)({
417 dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
418 }),
419 ),
420 Effect.result,
421 );
422 expect(result._tag).toBe("Success");
423 expect(
424 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
425 entry.startsWith("thread-replay-"),
426 ),
427 ).toEqual([`${earlierAttachment.id}.png`]);
428 expect(
429 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${earlierAttachment.id}.png`)),
430 ).toEqual(Buffer.from([4, 4, 4]));
431 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
432 }).pipe(Effect.provide(layerIntakeTest)),
433);
434
435it.effect("releases claimed copies when the recorded answer has no attachments", () =>
436 Effect.gen(function* () {
437 const config = yield* ServerConfig.ServerConfig;
438 const threadId = ThreadId.make("thread-empty-answer");
439 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
440 NodeFS.writeFileSync(
441 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
442 new Uint8Array([1, 2, 3]),
443 );
444 const storedEvents = answeredRespondEvents({
445 threadId,
446 requestId: "request-empty-answer",
447 attachmentsByQuestionId: {},
448 });
449 const result = yield* dispatchCommand({
450 type: "runtime-request.respond",
451 commandId: CommandId.make("answer-empty"),
452 threadId,
453 requestId: RuntimeRequestId.make("request-empty-answer"),
454 answers: { q: ["one"] },
455 attachmentsByQuestionId: {
456 q: [
457 {
458 type: "image",
459 id: pendingId,
460 name: "screen.png",
461 mimeType: "image/png",
462 sizeBytes: 3,
463 },
464 ],
465 },
466 }).pipe(
467 Effect.provide(
468 Layer.mock(ThreadManagementService.ThreadManagementService)({
469 dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
470 }),
471 ),
472 Effect.result,
473 );
474 expect(result._tag).toBe("Success");
475 expect(
476 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
477 entry.startsWith("thread-empty-answer-"),
478 ),
479 ).toEqual([]);
480 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
481 }).pipe(Effect.provide(layerIntakeTest)),
482);
483
484it.effect("releases claimed copies when the recorded answer was text-only", () =>
485 Effect.gen(function* () {
486 const config = yield* ServerConfig.ServerConfig;
487 const threadId = ThreadId.make("thread-text-only-answer");
488 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
489 NodeFS.writeFileSync(
490 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
491 new Uint8Array([1, 2, 3]),
492 );
493 const storedEvents = textOnlyRespondEvents({
494 threadId,
495 requestId: "request-text-only",
496 });
497 const result = yield* dispatchCommand({
498 type: "runtime-request.respond",
499 commandId: CommandId.make("answer-text-only"),
500 threadId,
501 requestId: RuntimeRequestId.make("request-text-only"),
502 answers: { q: ["one"] },
503 attachmentsByQuestionId: {
504 q: [
505 {
506 type: "image",
507 id: pendingId,
508 name: "screen.png",
509 mimeType: "image/png",
510 sizeBytes: 3,
511 },
512 ],
513 },
514 }).pipe(
515 Effect.provide(
516 Layer.mock(ThreadManagementService.ThreadManagementService)({
517 dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
518 }),
519 ),
520 Effect.result,
521 );
522 expect(result._tag).toBe("Success");
523 expect(
524 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
525 entry.startsWith("thread-text-only-answer-"),
526 ),
527 ).toEqual([]);
528 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
529 }).pipe(Effect.provide(layerIntakeTest)),
530);
531
532it.effect("retains claimed copies referenced by a fresh recorded answer", () =>
533 Effect.gen(function* () {
534 const config = yield* ServerConfig.ServerConfig;
535 const threadId = ThreadId.make("thread-fresh-answer");
536 const firstId = ChatAttachmentId.make(createPendingAttachmentId()!);
537 const secondId = ChatAttachmentId.make(createPendingAttachmentId()!);
538 NodeFS.writeFileSync(
539 NodePath.join(config.attachmentsDir, `${firstId}.png`),
540 new Uint8Array([1, 2, 3]),
541 );
542 NodeFS.writeFileSync(
543 NodePath.join(config.attachmentsDir, `${secondId}.png`),
544 new Uint8Array([7, 7]),
545 );
546 const result = yield* dispatchCommand({
547 type: "runtime-request.respond",
548 commandId: CommandId.make("answer-fresh"),
549 threadId,
550 requestId: RuntimeRequestId.make("request-fresh"),
551 answers: { q1: ["one"], q2: ["two"] },
552 attachmentsByQuestionId: {
553 q1: [
554 {
555 type: "image",
556 id: firstId,
557 name: "one.png",
558 mimeType: "image/png",
559 sizeBytes: 3,
560 },
561 ],
562 q2: [
563 {
564 type: "image",
565 id: secondId,
566 name: "two.png",
567 mimeType: "image/png",
568 sizeBytes: 2,
569 },
570 ],
571 },
572 }).pipe(
573 Effect.provide(
574 Layer.mock(ThreadManagementService.ThreadManagementService)({
575 dispatch: (command) =>
576 Effect.succeed({
577 sequence: 1,
578 storedEvents: answeredRespondEvents({
579 threadId,
580 requestId: "request-fresh",
581 attachmentsByQuestionId:
582 command.type === "runtime-request.respond"
583 ? (command.attachmentsByQuestionId ?? {})
584 : {},
585 }),
586 }),
587 }),
588 ),
589 Effect.result,
590 );
591 expect(result._tag).toBe("Success");
592 expect(
593 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
594 entry.startsWith("thread-fresh-answer-"),
595 ),
596 ).toHaveLength(2);
597 }).pipe(Effect.provide(layerIntakeTest)),
598);
599
600it.effect("releases claimed copies when preparation dies with a defect", () =>
601 Effect.gen(function* () {
602 const config = yield* ServerConfig.ServerConfig;
603 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
604 NodeFS.writeFileSync(
605 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
606 new Uint8Array([1, 2, 3]),
607 );
608 const poisoned = {
609 get id(): string {
610 throw new Error("poisoned");
611 },
612 };
613 const captured: OrchestrationV2ServerCommand[] = [];
614 const result = yield* dispatchCommand({
615 type: "runtime-request.respond",
616 commandId: CommandId.make("answer-defect"),
617 threadId: ThreadId.make("thread-defect"),
618 requestId: RuntimeRequestId.make("request-defect"),
619 answers: { q1: ["one"], q2: ["two"] },
620 attachmentsByQuestionId: {
621 q1: [
622 {
623 type: "image",
624 id: pendingId,
625 name: "screen.png",
626 mimeType: "image/png",
627 sizeBytes: 3,
628 },
629 ],
630 q2: [poisoned] as never,
631 },
632 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.exit);
633 expect(result._tag).toBe("Failure");
634 expect(captured).toHaveLength(0);
635 expect(
636 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
637 entry.startsWith("thread-defect-"),
638 ),
639 ).toEqual([]);
640 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
641 }).pipe(Effect.provide(layerIntakeTest)),
642);
643
644it.effect("a retried response re-claims the preserved pending uploads", () =>
645 Effect.gen(function* () {
646 const config = yield* ServerConfig.ServerConfig;
647 const threadId = ThreadId.make("thread-retry");
648 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
649 const lateId = ChatAttachmentId.make(createPendingAttachmentId()!);
650 NodeFS.writeFileSync(
651 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
652 new Uint8Array([1, 2, 3]),
653 );
654 const command: OrchestrationV2Command = {
655 type: "runtime-request.respond",
656 commandId: CommandId.make("answer-retry"),
657 threadId,
658 requestId: RuntimeRequestId.make("request-retry"),
659 answers: { q1: ["one"], q2: ["two"] },
660 attachmentsByQuestionId: {
661 q1: [
662 {
663 type: "image",
664 id: pendingId,
665 name: "screen.png",
666 mimeType: "image/png",
667 sizeBytes: 3,
668 },
669 ],
670 q2: [
671 {
672 type: "image",
673 id: lateId,
674 name: "late.png",
675 mimeType: "image/png",
676 sizeBytes: 2,
677 },
678 ],
679 },
680 };
681 const captured: OrchestrationV2ServerCommand[] = [];
682 const first = yield* dispatchCommand(command).pipe(
683 Effect.provide(layerFailingDispatch(captured)),
684 Effect.result,
685 );
686 expect(first._tag).toBe("Failure");
687 expect(captured).toHaveLength(0);
688
689 NodeFS.writeFileSync(
690 NodePath.join(config.attachmentsDir, `${lateId}.png`),
691 new Uint8Array([7, 7]),
692 );
693 const retry = yield* dispatchCommand(command).pipe(
694 Effect.provide(
695 Layer.mock(ThreadManagementService.ThreadManagementService)({
696 dispatch: (dispatched) => {
697 captured.push(dispatched);
698 return Effect.succeed({ sequence: 1, storedEvents: [] });
699 },
700 }),
701 ),
702 Effect.result,
703 );
704 expect(retry._tag).toBe("Success");
705 const dispatched = captured[0]!;
706 expect(dispatched.type).toBe("runtime-request.respond");
707 if (dispatched.type !== "runtime-request.respond") return;
708 for (const attachment of [
709 ...(dispatched.attachmentsByQuestionId?.q1 ?? []),
710 ...(dispatched.attachmentsByQuestionId?.q2 ?? []),
711 ]) {
712 const path = resolveAttachmentPath({
713 attachmentsDir: config.attachmentsDir,
714 attachment,
715 });
716 expect(path).not.toBeNull();
717 expect(NodeFS.existsSync(path!)).toBe(true);
718 }
719 expect(
720 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
721 entry.startsWith("thread-retry-"),
722 ),
723 ).toHaveLength(2);
724 }).pipe(Effect.provide(layerIntakeTest)),
725);
726
727it.effect("applies the image budget across all questions before dispatch", () =>
728 Effect.gen(function* () {
729 const attachments = Array.from({ length: 5 }, (_, index) => ({
730 type: "image" as const,
731 id: ChatAttachmentId.make(`existing-budget-${index}`),
732 name: `${index}.png`,
733 mimeType: "image/png",
734 sizeBytes: 10 * 1024 * 1024,
735 }));
736 const captured: OrchestrationV2ServerCommand[] = [];
737 const result = yield* Effect.exit(
738 dispatchCommand({
739 type: "runtime-request.respond",
740 commandId: CommandId.make("command-image-budget"),
741 threadId: ThreadId.make("thread-image-budget"),
742 requestId: RuntimeRequestId.make("question-image-budget"),
743 answers: {},
744 attachmentsByQuestionId: { q1: attachments, q2: attachments },
745 }).pipe(Effect.provide(layerFailingDispatch(captured))),
746 );
747 expect(result._tag).toBe("Failure");
748 if (result._tag === "Failure") expect(String(result.cause)).toContain("80 MiB");
749 expect(captured).toEqual([]);
750 }).pipe(Effect.provide(layerIntakeTest)),
751);
752
753it.effect("releases claimed copies when a project disables the message's provider instance", () =>
754 Effect.gen(function* () {
755 const config = yield* ServerConfig.ServerConfig;
756 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
757 NodeFS.writeFileSync(
758 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
759 new Uint8Array([1, 2, 3]),
760 );
761 const result = yield* sendToThread({
762 projectId: ProjectId.make("project-disabled-send"),
763 commandId: CommandId.make("command-disabled-send"),
764 threadId: ThreadId.make("thread-disabled-send"),
765 messageId: MessageId.make("message-disabled-send"),
766 text: "Hello",
767 attachments: [
768 {
769 type: "image",
770 id: pendingId,
771 name: "screen.png",
772 mimeType: "image/png",
773 sizeBytes: 3,
774 },
775 ],
776 mode: "auto",
777 createdBy: "user",
778 creationSource: "web",
779 }).pipe(
780 Effect.provide(
781 Layer.mock(ThreadManagementService.ThreadManagementService)({
782 sendToThread: (input) =>
783 Effect.fail(
784 new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
785 projectId: input.projectId,
786 instanceId: ProviderInstanceId.make("codex"),
787 }),
788 ),
789 }),
790 ),
791 Effect.result,
792 );
793 expect(result._tag).toBe("Failure");
794 expect(
795 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
796 entry.startsWith("thread-disabled-send-"),
797 ),
798 ).toEqual([]);
799 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
800 }).pipe(Effect.provide(layerIntakeTest)),
801);