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

ThreadMessageIntake.test.ts

766 lines26.0 KB

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