Open History to see the last commit
1import * as DocumentText from "../provider/DocumentText.ts";
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { expect, it } from "@effect/vitest";
7import {
8 ChatAttachmentId,
9 CommandId,
10 EventId,
11 GuestMessageId,
12 MessageId,
13 RunId,
14 RuntimeRequestId,
15 ThreadId,
16 TurnItemId,
17 type OrchestrationV2Command,
18 type OrchestrationV2ServerCommand,
19 type OrchestrationV2StoredEvent,
20 type UserInputAttachments,
21} from "@t3tools/contracts";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import {
26 createAttachmentId,
27 createPendingAttachmentId,
28 resolveAttachmentPath,
29} from "../attachmentStore.ts";
30import * as ServerConfig from "../config.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import {
33 OrchestratorCommandPreviouslyRejectedError,
34 OrchestratorDispatchError,
35} from "./Orchestrator.ts";
36import * as ThreadManagementService from "./ThreadManagementService.ts";
37import * as ThreadMessageIntake from "./ThreadMessageIntake.ts";
38
39const dispatchCommand = (command: OrchestrationV2Command, sender = { managesProviders: true }) =>
40 ThreadMessageIntake.dispatchCommand(command, sender);
41
42const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
43 prefix: "t3-question-intake-",
44}).pipe(
45 Layer.provideMerge(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
46 Layer.provideMerge(ServerSettings.layerTest()),
47);
48
49const layerFailingDispatchHandler =
50 (captured: OrchestrationV2ServerCommand[]) => (command: OrchestrationV2ServerCommand) => {
51 captured.push(command);
52 return Effect.fail(
53 new OrchestratorDispatchError({
54 commandId: command.commandId,
55 commandType: command.type,
56 cause: "Stop after intake",
57 }),
58 );
59 };
60
61const noPendingRuntimeRequests: ThreadManagementService.ThreadManagementServiceShape["getThreadRecords"] =
62 () =>
63 Effect.succeed({ runtimeRequests: [] } as unknown as Effect.Success<
64 ReturnType<ThreadManagementService.ThreadManagementServiceShape["getThreadRecords"]>
65 >);
66
67const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) =>
68 Layer.mock(ThreadManagementService.ThreadManagementService)({
69 dispatch: layerFailingDispatchHandler(captured),
70 getThreadRecords: noPendingRuntimeRequests,
71 });
72
73const NOW = DateTime.makeUnsafe("2026-09-13T00:00:00.000Z");
74
75const answeredRespondEvents = (input: {
76 readonly threadId: ThreadId;
77 readonly requestId: string;
78 readonly attachmentsByQuestionId: UserInputAttachments;
79}): OrchestrationV2StoredEvent[] => [
80 {
81 sequence: 1,
82 commandId: null,
83 event: {
84 id: EventId.make("evt-recorded-answer"),
85 type: "turn-item.updated",
86 threadId: input.threadId,
87 occurredAt: NOW,
88 payload: {
89 id: TurnItemId.make("item-recorded-answer"),
90 type: "user_input_request",
91 threadId: input.threadId,
92 runId: null,
93 nodeId: null,
94 providerThreadId: null,
95 providerTurnId: null,
96 nativeItemRef: null,
97 parentItemId: null,
98 ordinal: 1,
99 status: "completed",
100 title: null,
101 startedAt: null,
102 completedAt: NOW,
103 updatedAt: NOW,
104 requestId: RuntimeRequestId.make(input.requestId),
105 questions: [],
106 questionAnswer: {
107 requestId: input.requestId,
108 answers: {},
109 attachmentsByQuestionId: input.attachmentsByQuestionId,
110 },
111 },
112 },
113 },
114];
115
116it.effect("claims question uploads and passes readable paths through the V2 request command", () =>
117 Effect.gen(function* () {
118 const config = yield* ServerConfig.ServerConfig;
119 const id = ChatAttachmentId.make(createPendingAttachmentId()!);
120 NodeFS.writeFileSync(
121 NodePath.join(config.attachmentsDir, `${id}.png`),
122 new Uint8Array([1, 2, 3]),
123 );
124 const captured: OrchestrationV2ServerCommand[] = [];
125 yield* dispatchCommand({
126 type: "runtime-request.respond",
127 commandId: CommandId.make("answer-1"),
128 threadId: ThreadId.make("thread-answer"),
129 requestId: RuntimeRequestId.make("request-1"),
130 answers: { q: ["Selected option"] },
131 attachmentsByQuestionId: {
132 q: [{ type: "image", id, name: "screen.png", mimeType: "image/png", sizeBytes: 3 }],
133 },
134 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
135 expect(captured).toHaveLength(1);
136 const command = captured[0]!;
137 expect(command.type).toBe("runtime-request.respond");
138 if (command.type !== "runtime-request.respond") return;
139 const attachment = command.attachmentsByQuestionId?.q?.[0];
140 expect(attachment).toBeDefined();
141 const path = resolveAttachmentPath({
142 attachmentsDir: config.attachmentsDir,
143 attachment: attachment!,
144 });
145 expect(path).not.toBeNull();
146 expect(NodeFS.readFileSync(path!)).toEqual(Buffer.from([1, 2, 3]));
147 expect(command.answers?.q).toEqual([
148 "Selected option",
149 `Attached image "screen.png": ${JSON.stringify(path)}`,
150 ]);
151 }).pipe(Effect.provide(layerIntakeTest)),
152);
153
154it.effect("leaves an async answer's text alone so its files travel as message attachments", () =>
155 Effect.gen(function* () {
156 const config = yield* ServerConfig.ServerConfig;
157 const id = ChatAttachmentId.make(createPendingAttachmentId()!);
158 NodeFS.writeFileSync(
159 NodePath.join(config.attachmentsDir, `${id}.png`),
160 new Uint8Array([1, 2, 3]),
161 );
162 const threadId = ThreadId.make("thread-async-answer");
163 const requestId = RuntimeRequestId.make("request-async");
164 const captured: OrchestrationV2ServerCommand[] = [];
165 yield* dispatchCommand({
166 type: "runtime-request.respond",
167 commandId: CommandId.make("answer-async"),
168 threadId,
169 requestId,
170 answers: { q: "" },
171 attachmentsByQuestionId: {
172 q: [{ type: "image", id, name: "screen.png", mimeType: "image/png", sizeBytes: 3 }],
173 },
174 }).pipe(
175 Effect.provide(
176 Layer.mock(ThreadManagementService.ThreadManagementService)({
177 dispatch: layerFailingDispatchHandler(captured),
178 getThreadRecords: () =>
179 Effect.succeed({
180 runtimeRequests: [
181 {
182 id: requestId,
183 nodeId: null,
184 providerTurnId: null,
185 nativeRequestRef: null,
186 kind: "user_input",
187 status: "pending",
188 responseCapability: { type: "message" },
189 createdAt: NOW,
190 resolvedAt: null,
191 },
192 ],
193 } as unknown as Effect.Success<
194 ReturnType<ThreadManagementService.ThreadManagementServiceShape["getThreadRecords"]>
195 >),
196 }),
197 ),
198 Effect.result,
199 );
200 expect(captured).toHaveLength(1);
201 const command = captured[0]!;
202 if (command.type !== "runtime-request.respond") throw new Error("expected a response");
203 expect(command.answers).toEqual({ q: "" });
204 expect(command.attachmentsByQuestionId?.q).toHaveLength(1);
205 }).pipe(Effect.provide(layerIntakeTest)),
206);
207
208it.effect("retains claimed copies when dispatch failure may have been accepted", () =>
209 Effect.gen(function* () {
210 const config = yield* ServerConfig.ServerConfig;
211 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
212 NodeFS.writeFileSync(
213 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
214 new Uint8Array([1, 2, 3]),
215 );
216 const captured: OrchestrationV2ServerCommand[] = [];
217 const result = yield* dispatchCommand({
218 type: "runtime-request.respond",
219 commandId: CommandId.make("answer-ambiguous"),
220 threadId: ThreadId.make("thread-ambiguous"),
221 requestId: RuntimeRequestId.make("request-ambiguous"),
222 answers: { q: ["one"] },
223 attachmentsByQuestionId: {
224 q: [
225 {
226 type: "image",
227 id: pendingId,
228 name: "screen.png",
229 mimeType: "image/png",
230 sizeBytes: 3,
231 },
232 ],
233 },
234 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
235 expect(result._tag).toBe("Failure");
236 expect(captured).toHaveLength(1);
237 const threadFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
238 entry.startsWith("thread-ambiguous-"),
239 );
240 expect(threadFiles).toHaveLength(1);
241 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
242 }).pipe(Effect.provide(layerIntakeTest)),
243);
244
245it.effect("releases claimed copies when the command was already rejected", () =>
246 Effect.gen(function* () {
247 const config = yield* ServerConfig.ServerConfig;
248 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
249 NodeFS.writeFileSync(
250 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
251 new Uint8Array([1, 2, 3]),
252 );
253 const result = yield* dispatchCommand({
254 type: "runtime-request.respond",
255 commandId: CommandId.make("answer-rejected"),
256 threadId: ThreadId.make("thread-rejected"),
257 requestId: RuntimeRequestId.make("request-rejected"),
258 answers: { q: ["one"] },
259 attachmentsByQuestionId: {
260 q: [
261 {
262 type: "image",
263 id: pendingId,
264 name: "screen.png",
265 mimeType: "image/png",
266 sizeBytes: 3,
267 },
268 ],
269 },
270 }).pipe(
271 Effect.provide(
272 Layer.mock(ThreadManagementService.ThreadManagementService)({
273 getThreadRecords: noPendingRuntimeRequests,
274 dispatch: (command) =>
275 Effect.fail(
276 new OrchestratorCommandPreviouslyRejectedError({
277 commandId: command.commandId,
278 commandType: command.type,
279 detail: "rejected earlier",
280 }),
281 ),
282 }),
283 ),
284 Effect.result,
285 );
286 expect(result._tag).toBe("Failure");
287 expect(
288 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
289 entry.startsWith("thread-rejected-"),
290 ),
291 ).toEqual([]);
292 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
293 }).pipe(Effect.provide(layerIntakeTest)),
294);
295
296it.effect("releases claimed copies when dispatch replays an earlier accepted response", () =>
297 Effect.gen(function* () {
298 const config = yield* ServerConfig.ServerConfig;
299 const threadId = ThreadId.make("thread-replay");
300 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
301 NodeFS.writeFileSync(
302 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
303 new Uint8Array([1, 2, 3]),
304 );
305 const earlierAttachment = {
306 type: "image" as const,
307 id: ChatAttachmentId.make("thread-replay-00000000-0000-4000-8000-0000000000aa"),
308 name: "screen.png",
309 mimeType: "image/png",
310 sizeBytes: 3,
311 };
312 NodeFS.writeFileSync(
313 NodePath.join(config.attachmentsDir, `${earlierAttachment.id}.png`),
314 new Uint8Array([4, 4, 4]),
315 );
316 const storedEvents = answeredRespondEvents({
317 threadId,
318 requestId: "request-replay",
319 attachmentsByQuestionId: { q: [earlierAttachment] },
320 });
321 const result = yield* dispatchCommand({
322 type: "runtime-request.respond",
323 commandId: CommandId.make("answer-replay"),
324 threadId,
325 requestId: RuntimeRequestId.make("request-replay"),
326 answers: { q: ["one"] },
327 attachmentsByQuestionId: {
328 q: [
329 {
330 type: "image",
331 id: pendingId,
332 name: "screen.png",
333 mimeType: "image/png",
334 sizeBytes: 3,
335 },
336 ],
337 },
338 }).pipe(
339 Effect.provide(
340 Layer.mock(ThreadManagementService.ThreadManagementService)({
341 getThreadRecords: noPendingRuntimeRequests,
342 dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
343 }),
344 ),
345 Effect.result,
346 );
347 expect(result._tag).toBe("Success");
348 expect(
349 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
350 entry.startsWith("thread-replay-"),
351 ),
352 ).toEqual([`${earlierAttachment.id}.png`]);
353 expect(
354 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${earlierAttachment.id}.png`)),
355 ).toEqual(Buffer.from([4, 4, 4]));
356 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
357 }).pipe(Effect.provide(layerIntakeTest)),
358);
359
360it.effect("a retried response re-claims the preserved pending uploads", () =>
361 Effect.gen(function* () {
362 const config = yield* ServerConfig.ServerConfig;
363 const threadId = ThreadId.make("thread-retry");
364 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
365 const lateId = ChatAttachmentId.make(createPendingAttachmentId()!);
366 NodeFS.writeFileSync(
367 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
368 new Uint8Array([1, 2, 3]),
369 );
370 const command: OrchestrationV2Command = {
371 type: "runtime-request.respond",
372 commandId: CommandId.make("answer-retry"),
373 threadId,
374 requestId: RuntimeRequestId.make("request-retry"),
375 answers: { q1: ["one"], q2: ["two"] },
376 attachmentsByQuestionId: {
377 q1: [
378 {
379 type: "image",
380 id: pendingId,
381 name: "screen.png",
382 mimeType: "image/png",
383 sizeBytes: 3,
384 },
385 ],
386 q2: [
387 {
388 type: "image",
389 id: lateId,
390 name: "late.png",
391 mimeType: "image/png",
392 sizeBytes: 2,
393 },
394 ],
395 },
396 };
397 const captured: OrchestrationV2ServerCommand[] = [];
398 const first = yield* dispatchCommand(command).pipe(
399 Effect.provide(layerFailingDispatch(captured)),
400 Effect.result,
401 );
402 expect(first._tag).toBe("Failure");
403 expect(captured).toHaveLength(0);
404
405 NodeFS.writeFileSync(
406 NodePath.join(config.attachmentsDir, `${lateId}.png`),
407 new Uint8Array([7, 7]),
408 );
409 const retry = yield* dispatchCommand(command).pipe(
410 Effect.provide(
411 Layer.mock(ThreadManagementService.ThreadManagementService)({
412 getThreadRecords: noPendingRuntimeRequests,
413 dispatch: (dispatched) => {
414 captured.push(dispatched);
415 return Effect.succeed({ sequence: 1, storedEvents: [] });
416 },
417 }),
418 ),
419 Effect.result,
420 );
421 expect(retry._tag).toBe("Success");
422 const dispatched = captured[0]!;
423 expect(dispatched.type).toBe("runtime-request.respond");
424 if (dispatched.type !== "runtime-request.respond") return;
425 for (const attachment of [
426 ...(dispatched.attachmentsByQuestionId?.q1 ?? []),
427 ...(dispatched.attachmentsByQuestionId?.q2 ?? []),
428 ]) {
429 const path = resolveAttachmentPath({
430 attachmentsDir: config.attachmentsDir,
431 attachment,
432 });
433 expect(path).not.toBeNull();
434 expect(NodeFS.existsSync(path!)).toBe(true);
435 }
436 expect(
437 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
438 entry.startsWith("thread-retry-"),
439 ),
440 ).toHaveLength(2);
441 }).pipe(Effect.provide(layerIntakeTest)),
442);
443
444it.effect("sends a guest message with the guest's files, never ones the client names", () =>
445 Effect.gen(function* () {
446 const config = yield* ServerConfig.ServerConfig;
447 const guestFile = {
448 type: "image" as const,
449 id: ChatAttachmentId.make(createAttachmentId("thread-guest")!),
450 name: "screen.png",
451 mimeType: "image/png",
452 sizeBytes: 3,
453 };
454 NodeFS.writeFileSync(
455 NodePath.join(config.attachmentsDir, `${guestFile.id}.png`),
456 new Uint8Array([1, 2, 3]),
457 );
458 const guestMessageId = GuestMessageId.make("guest-message:files");
459 const captured: OrchestrationV2ServerCommand[] = [];
460 const layerGuestShare = Layer.mock(ThreadManagementService.ThreadManagementService)({
461 dispatch: layerFailingDispatchHandler(captured),
462 // Only the share is read.
463 getThreadSnapshotWindow: () =>
464 Effect.succeed({
465 projection: {
466 thread: {
467 guestShare: {
468 messages: [{ id: guestMessageId, status: "pending", attachments: [guestFile] }],
469 },
470 },
471 },
472 } as unknown as Effect.Success<
473 ReturnType<
474 ThreadManagementService.ThreadManagementServiceShape["getThreadSnapshotWindow"]
475 >
476 >),
477 });
478 yield* dispatchCommand({
479 type: "message.dispatch",
480 commandId: CommandId.make("send-guest-message"),
481 threadId: ThreadId.make("thread-guest"),
482 messageId: MessageId.make("message-guest"),
483 guestMessageId,
484 text: "",
485 attachments: [{ ...guestFile, id: ChatAttachmentId.make("thread-guest-owner-file") }],
486 dispatchMode: { type: "queue_after_active" },
487 createdBy: "user",
488 creationSource: "web",
489 }).pipe(Effect.provide(layerGuestShare), Effect.result);
490 const command = captured[0];
491 if (command?.type !== "message.dispatch") throw new Error("Expected a message dispatch.");
492 expect(command.attachments).toHaveLength(1);
493 // The guest's file, which is already the thread's.
494 expect(command.attachments).toEqual([guestFile]);
495 }).pipe(Effect.provide(layerIntakeTest)),
496);
497
498it.effect("refuses a queued edit that keeps a file another edit already deleted", () =>
499 Effect.gen(function* () {
500 const config = yield* ServerConfig.ServerConfig;
501 const storedFile = (name: string) => ({
502 type: "image" as const,
503 id: ChatAttachmentId.make(createAttachmentId("thread-queued-edit")!),
504 name,
505 mimeType: "image/png",
506 sizeBytes: 3,
507 });
508 const kept = storedFile("kept.png");
509 const deleted = storedFile("deleted.png");
510 NodeFS.writeFileSync(
511 NodePath.join(config.attachmentsDir, `${kept.id}.png`),
512 new Uint8Array([1, 2, 3]),
513 );
514 const captured: OrchestrationV2ServerCommand[] = [];
515 const edit = (attachments: ReadonlyArray<typeof kept>) =>
516 dispatchCommand({
517 type: "queued-run.edit",
518 commandId: CommandId.make(`queued-edit-${attachments.length}`),
519 threadId: ThreadId.make("thread-queued-edit"),
520 runId: RunId.make("run-queued-edit"),
521 text: "Edited from a stale view.",
522 attachments,
523 }).pipe(
524 Effect.provide(
525 Layer.mock(ThreadManagementService.ThreadManagementService)({
526 dispatch: layerFailingDispatchHandler(captured),
527 hasReceipt: (commandId) =>
528 Effect.succeed(captured.some((command) => command.commandId === commandId)),
529 }),
530 ),
531 Effect.result,
532 );
533
534 yield* edit([kept]);
535 expect(captured).toHaveLength(1);
536 const result = yield* edit([kept, deleted]);
537 expect(result._tag).toBe("Failure");
538 expect(captured).toHaveLength(1);
539 // A retry of the accepted edit replays its receipt even after a later cleanup removed its file.
540 NodeFS.rmSync(NodePath.join(config.attachmentsDir, `${kept.id}.png`));
541 yield* edit([kept]);
542 expect(captured).toHaveLength(2);
543 }).pipe(Effect.provide(layerIntakeTest)),
544);
545
546it.effect("a queued /logout edit without provider management must keep an attachment", () =>
547 Effect.gen(function* () {
548 const threadId = ThreadId.make("thread-sign-out-edit");
549 const image = {
550 type: "image" as const,
551 id: ChatAttachmentId.make(createAttachmentId(threadId)!),
552 name: "shot.png",
553 mimeType: "image/png",
554 sizeBytes: 3,
555 };
556 const config = yield* ServerConfig.ServerConfig;
557 NodeFS.writeFileSync(
558 NodePath.join(config.attachmentsDir, `${image.id}.png`),
559 new Uint8Array([1, 2, 3]),
560 );
561 const captured: OrchestrationV2ServerCommand[] = [];
562 // The edit omits `attachments`, as an older client's does, so the queued ones stay.
563 const edit = (run: string, managesProviders: boolean) =>
564 dispatchCommand(
565 {
566 type: "queued-run.edit",
567 commandId: CommandId.make(`edit-${run}-${managesProviders}`),
568 threadId,
569 runId: RunId.make(run),
570 text: " /LOGOUT ",
571 },
572 { managesProviders },
573 ).pipe(
574 Effect.provide(
575 Layer.mock(ThreadManagementService.ThreadManagementService)({
576 dispatch: layerFailingDispatchHandler(captured),
577 hasReceipt: (commandId) => Effect.succeed(commandId === "edit-replayed-false"),
578 getThreadRecords: () =>
579 Effect.succeed({
580 runs: ["attached", "bare"].map((id) => ({
581 id: RunId.make(id),
582 status: "queued",
583 userMessageId: MessageId.make(id),
584 })),
585 } as never),
586 getMessagesById: (_threadId, [id]) =>
587 Effect.succeed(
588 new Map([[id, { attachments: id === "attached" ? [image] : [] }]]) as never,
589 ),
590 }),
591 ),
592 Effect.flip,
593 );
594
595 expect((yield* edit("bare", false))._tag).toBe("EnvironmentAuthorizationError");
596 expect((yield* edit("started", false))._tag).toBe("EnvironmentAuthorizationError");
597 expect(captured).toEqual([]);
598 yield* edit("attached", false);
599 yield* edit("bare", true);
600 // A retry of an accepted edit reaches its receipt after its run left the queue.
601 yield* edit("replayed", false);
602 // The kept files are pinned, so an edit racing this one cannot strip them afterwards.
603 expect(captured).toMatchObject([
604 { runId: "attached", attachments: [image] },
605 { runId: "bare" },
606 { runId: "replayed" },
607 ]);
608 expect(captured[1]).not.toHaveProperty("attachments");
609 expect(captured[2]).not.toHaveProperty("attachments");
610 }).pipe(Effect.provide(layerIntakeTest)),
611);