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 { dispatchCommand } from "./ThreadMessageIntake.ts";
38
39const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
40 prefix: "t3-question-intake-",
41}).pipe(
42 Layer.provideMerge(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
43 Layer.provideMerge(ServerSettings.layerTest()),
44);
45
46const layerFailingDispatchHandler =
47 (captured: OrchestrationV2ServerCommand[]) => (command: OrchestrationV2ServerCommand) => {
48 captured.push(command);
49 return Effect.fail(
50 new OrchestratorDispatchError({
51 commandId: command.commandId,
52 commandType: command.type,
53 cause: "Stop after intake",
54 }),
55 );
56 };
57
58const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) =>
59 Layer.mock(ThreadManagementService.ThreadManagementService)({
60 dispatch: layerFailingDispatchHandler(captured),
61 });
62
63const NOW = DateTime.makeUnsafe("2026-09-13T00:00:00.000Z");
64
65const answeredRespondEvents = (input: {
66 readonly threadId: ThreadId;
67 readonly requestId: string;
68 readonly attachmentsByQuestionId: UserInputAttachments;
69}): OrchestrationV2StoredEvent[] => [
70 {
71 sequence: 1,
72 commandId: null,
73 event: {
74 id: EventId.make("evt-recorded-answer"),
75 type: "turn-item.updated",
76 threadId: input.threadId,
77 occurredAt: NOW,
78 payload: {
79 id: TurnItemId.make("item-recorded-answer"),
80 type: "user_input_request",
81 threadId: input.threadId,
82 runId: null,
83 nodeId: null,
84 providerThreadId: null,
85 providerTurnId: null,
86 nativeItemRef: null,
87 parentItemId: null,
88 ordinal: 1,
89 status: "completed",
90 title: null,
91 startedAt: null,
92 completedAt: NOW,
93 updatedAt: NOW,
94 requestId: RuntimeRequestId.make(input.requestId),
95 questions: [],
96 questionAnswer: {
97 requestId: input.requestId,
98 answers: {},
99 attachmentsByQuestionId: input.attachmentsByQuestionId,
100 },
101 },
102 },
103 },
104];
105
106it.effect("claims question uploads and passes readable paths through the V2 request command", () =>
107 Effect.gen(function* () {
108 const config = yield* ServerConfig.ServerConfig;
109 const id = ChatAttachmentId.make(createPendingAttachmentId()!);
110 NodeFS.writeFileSync(
111 NodePath.join(config.attachmentsDir, `${id}.png`),
112 new Uint8Array([1, 2, 3]),
113 );
114 const captured: OrchestrationV2ServerCommand[] = [];
115 yield* dispatchCommand({
116 type: "runtime-request.respond",
117 commandId: CommandId.make("answer-1"),
118 threadId: ThreadId.make("thread-answer"),
119 requestId: RuntimeRequestId.make("request-1"),
120 answers: { q: ["Selected option"] },
121 attachmentsByQuestionId: {
122 q: [{ type: "image", id, name: "screen.png", mimeType: "image/png", sizeBytes: 3 }],
123 },
124 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
125 expect(captured).toHaveLength(1);
126 const command = captured[0]!;
127 expect(command.type).toBe("runtime-request.respond");
128 if (command.type !== "runtime-request.respond") return;
129 const attachment = command.attachmentsByQuestionId?.q?.[0];
130 expect(attachment).toBeDefined();
131 const path = resolveAttachmentPath({
132 attachmentsDir: config.attachmentsDir,
133 attachment: attachment!,
134 });
135 expect(path).not.toBeNull();
136 expect(NodeFS.readFileSync(path!)).toEqual(Buffer.from([1, 2, 3]));
137 expect(command.answers?.q).toEqual([
138 "Selected option",
139 `Attached image "screen.png": ${JSON.stringify(path)}`,
140 ]);
141 }).pipe(Effect.provide(layerIntakeTest)),
142);
143
144it.effect("retains claimed copies when dispatch failure may have been accepted", () =>
145 Effect.gen(function* () {
146 const config = yield* ServerConfig.ServerConfig;
147 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
148 NodeFS.writeFileSync(
149 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
150 new Uint8Array([1, 2, 3]),
151 );
152 const captured: OrchestrationV2ServerCommand[] = [];
153 const result = yield* dispatchCommand({
154 type: "runtime-request.respond",
155 commandId: CommandId.make("answer-ambiguous"),
156 threadId: ThreadId.make("thread-ambiguous"),
157 requestId: RuntimeRequestId.make("request-ambiguous"),
158 answers: { q: ["one"] },
159 attachmentsByQuestionId: {
160 q: [
161 {
162 type: "image",
163 id: pendingId,
164 name: "screen.png",
165 mimeType: "image/png",
166 sizeBytes: 3,
167 },
168 ],
169 },
170 }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
171 expect(result._tag).toBe("Failure");
172 expect(captured).toHaveLength(1);
173 const threadFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
174 entry.startsWith("thread-ambiguous-"),
175 );
176 expect(threadFiles).toHaveLength(1);
177 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
178 }).pipe(Effect.provide(layerIntakeTest)),
179);
180
181it.effect("releases claimed copies when the command was already rejected", () =>
182 Effect.gen(function* () {
183 const config = yield* ServerConfig.ServerConfig;
184 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
185 NodeFS.writeFileSync(
186 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
187 new Uint8Array([1, 2, 3]),
188 );
189 const result = yield* dispatchCommand({
190 type: "runtime-request.respond",
191 commandId: CommandId.make("answer-rejected"),
192 threadId: ThreadId.make("thread-rejected"),
193 requestId: RuntimeRequestId.make("request-rejected"),
194 answers: { q: ["one"] },
195 attachmentsByQuestionId: {
196 q: [
197 {
198 type: "image",
199 id: pendingId,
200 name: "screen.png",
201 mimeType: "image/png",
202 sizeBytes: 3,
203 },
204 ],
205 },
206 }).pipe(
207 Effect.provide(
208 Layer.mock(ThreadManagementService.ThreadManagementService)({
209 dispatch: (command) =>
210 Effect.fail(
211 new OrchestratorCommandPreviouslyRejectedError({
212 commandId: command.commandId,
213 commandType: command.type,
214 detail: "rejected earlier",
215 }),
216 ),
217 }),
218 ),
219 Effect.result,
220 );
221 expect(result._tag).toBe("Failure");
222 expect(
223 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
224 entry.startsWith("thread-rejected-"),
225 ),
226 ).toEqual([]);
227 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
228 }).pipe(Effect.provide(layerIntakeTest)),
229);
230
231it.effect("releases claimed copies when dispatch replays an earlier accepted response", () =>
232 Effect.gen(function* () {
233 const config = yield* ServerConfig.ServerConfig;
234 const threadId = ThreadId.make("thread-replay");
235 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
236 NodeFS.writeFileSync(
237 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
238 new Uint8Array([1, 2, 3]),
239 );
240 const earlierAttachment = {
241 type: "image" as const,
242 id: ChatAttachmentId.make("thread-replay-00000000-0000-4000-8000-0000000000aa"),
243 name: "screen.png",
244 mimeType: "image/png",
245 sizeBytes: 3,
246 };
247 NodeFS.writeFileSync(
248 NodePath.join(config.attachmentsDir, `${earlierAttachment.id}.png`),
249 new Uint8Array([4, 4, 4]),
250 );
251 const storedEvents = answeredRespondEvents({
252 threadId,
253 requestId: "request-replay",
254 attachmentsByQuestionId: { q: [earlierAttachment] },
255 });
256 const result = yield* dispatchCommand({
257 type: "runtime-request.respond",
258 commandId: CommandId.make("answer-replay"),
259 threadId,
260 requestId: RuntimeRequestId.make("request-replay"),
261 answers: { q: ["one"] },
262 attachmentsByQuestionId: {
263 q: [
264 {
265 type: "image",
266 id: pendingId,
267 name: "screen.png",
268 mimeType: "image/png",
269 sizeBytes: 3,
270 },
271 ],
272 },
273 }).pipe(
274 Effect.provide(
275 Layer.mock(ThreadManagementService.ThreadManagementService)({
276 dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
277 }),
278 ),
279 Effect.result,
280 );
281 expect(result._tag).toBe("Success");
282 expect(
283 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
284 entry.startsWith("thread-replay-"),
285 ),
286 ).toEqual([`${earlierAttachment.id}.png`]);
287 expect(
288 NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${earlierAttachment.id}.png`)),
289 ).toEqual(Buffer.from([4, 4, 4]));
290 expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
291 }).pipe(Effect.provide(layerIntakeTest)),
292);
293
294it.effect("a retried response re-claims the preserved pending uploads", () =>
295 Effect.gen(function* () {
296 const config = yield* ServerConfig.ServerConfig;
297 const threadId = ThreadId.make("thread-retry");
298 const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
299 const lateId = ChatAttachmentId.make(createPendingAttachmentId()!);
300 NodeFS.writeFileSync(
301 NodePath.join(config.attachmentsDir, `${pendingId}.png`),
302 new Uint8Array([1, 2, 3]),
303 );
304 const command: OrchestrationV2Command = {
305 type: "runtime-request.respond",
306 commandId: CommandId.make("answer-retry"),
307 threadId,
308 requestId: RuntimeRequestId.make("request-retry"),
309 answers: { q1: ["one"], q2: ["two"] },
310 attachmentsByQuestionId: {
311 q1: [
312 {
313 type: "image",
314 id: pendingId,
315 name: "screen.png",
316 mimeType: "image/png",
317 sizeBytes: 3,
318 },
319 ],
320 q2: [
321 {
322 type: "image",
323 id: lateId,
324 name: "late.png",
325 mimeType: "image/png",
326 sizeBytes: 2,
327 },
328 ],
329 },
330 };
331 const captured: OrchestrationV2ServerCommand[] = [];
332 const first = yield* dispatchCommand(command).pipe(
333 Effect.provide(layerFailingDispatch(captured)),
334 Effect.result,
335 );
336 expect(first._tag).toBe("Failure");
337 expect(captured).toHaveLength(0);
338
339 NodeFS.writeFileSync(
340 NodePath.join(config.attachmentsDir, `${lateId}.png`),
341 new Uint8Array([7, 7]),
342 );
343 const retry = yield* dispatchCommand(command).pipe(
344 Effect.provide(
345 Layer.mock(ThreadManagementService.ThreadManagementService)({
346 dispatch: (dispatched) => {
347 captured.push(dispatched);
348 return Effect.succeed({ sequence: 1, storedEvents: [] });
349 },
350 }),
351 ),
352 Effect.result,
353 );
354 expect(retry._tag).toBe("Success");
355 const dispatched = captured[0]!;
356 expect(dispatched.type).toBe("runtime-request.respond");
357 if (dispatched.type !== "runtime-request.respond") return;
358 for (const attachment of [
359 ...(dispatched.attachmentsByQuestionId?.q1 ?? []),
360 ...(dispatched.attachmentsByQuestionId?.q2 ?? []),
361 ]) {
362 const path = resolveAttachmentPath({
363 attachmentsDir: config.attachmentsDir,
364 attachment,
365 });
366 expect(path).not.toBeNull();
367 expect(NodeFS.existsSync(path!)).toBe(true);
368 }
369 expect(
370 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
371 entry.startsWith("thread-retry-"),
372 ),
373 ).toHaveLength(2);
374 }).pipe(Effect.provide(layerIntakeTest)),
375);
376
377it.effect("sends a guest message with the guest's files, never ones the client names", () =>
378 Effect.gen(function* () {
379 const config = yield* ServerConfig.ServerConfig;
380 const guestFile = {
381 type: "image" as const,
382 id: ChatAttachmentId.make(createAttachmentId("thread-guest")!),
383 name: "screen.png",
384 mimeType: "image/png",
385 sizeBytes: 3,
386 };
387 NodeFS.writeFileSync(
388 NodePath.join(config.attachmentsDir, `${guestFile.id}.png`),
389 new Uint8Array([1, 2, 3]),
390 );
391 const guestMessageId = GuestMessageId.make("guest-message:files");
392 const captured: OrchestrationV2ServerCommand[] = [];
393 const layerGuestShare = Layer.mock(ThreadManagementService.ThreadManagementService)({
394 dispatch: layerFailingDispatchHandler(captured),
395 // Only the share is read.
396 getThreadSnapshotWindow: () =>
397 Effect.succeed({
398 projection: {
399 thread: {
400 guestShare: {
401 messages: [{ id: guestMessageId, status: "pending", attachments: [guestFile] }],
402 },
403 },
404 },
405 } as unknown as Effect.Success<
406 ReturnType<
407 ThreadManagementService.ThreadManagementServiceShape["getThreadSnapshotWindow"]
408 >
409 >),
410 });
411 yield* dispatchCommand({
412 type: "message.dispatch",
413 commandId: CommandId.make("send-guest-message"),
414 threadId: ThreadId.make("thread-guest"),
415 messageId: MessageId.make("message-guest"),
416 guestMessageId,
417 text: "",
418 attachments: [{ ...guestFile, id: ChatAttachmentId.make("thread-guest-owner-file") }],
419 dispatchMode: { type: "queue_after_active" },
420 createdBy: "user",
421 creationSource: "web",
422 }).pipe(Effect.provide(layerGuestShare), Effect.result);
423 const command = captured[0];
424 if (command?.type !== "message.dispatch") throw new Error("Expected a message dispatch.");
425 expect(command.attachments).toHaveLength(1);
426 // The guest's file, which is already the thread's.
427 expect(command.attachments).toEqual([guestFile]);
428 }).pipe(Effect.provide(layerIntakeTest)),
429);
430
431it.effect("refuses a queued edit that keeps a file another edit already deleted", () =>
432 Effect.gen(function* () {
433 const config = yield* ServerConfig.ServerConfig;
434 const storedFile = (name: string) => ({
435 type: "image" as const,
436 id: ChatAttachmentId.make(createAttachmentId("thread-queued-edit")!),
437 name,
438 mimeType: "image/png",
439 sizeBytes: 3,
440 });
441 const kept = storedFile("kept.png");
442 const deleted = storedFile("deleted.png");
443 NodeFS.writeFileSync(
444 NodePath.join(config.attachmentsDir, `${kept.id}.png`),
445 new Uint8Array([1, 2, 3]),
446 );
447 const captured: OrchestrationV2ServerCommand[] = [];
448 const edit = (attachments: ReadonlyArray<typeof kept>) =>
449 dispatchCommand({
450 type: "queued-run.edit",
451 commandId: CommandId.make(`queued-edit-${attachments.length}`),
452 threadId: ThreadId.make("thread-queued-edit"),
453 runId: RunId.make("run-queued-edit"),
454 text: "Edited from a stale view.",
455 attachments,
456 }).pipe(
457 Effect.provide(
458 Layer.mock(ThreadManagementService.ThreadManagementService)({
459 dispatch: layerFailingDispatchHandler(captured),
460 hasReceipt: (commandId) =>
461 Effect.succeed(captured.some((command) => command.commandId === commandId)),
462 }),
463 ),
464 Effect.result,
465 );
466
467 yield* edit([kept]);
468 expect(captured).toHaveLength(1);
469 const result = yield* edit([kept, deleted]);
470 expect(result._tag).toBe("Failure");
471 expect(captured).toHaveLength(1);
472 // A retry of the accepted edit replays its receipt even after a later cleanup removed its file.
473 NodeFS.rmSync(NodePath.join(config.attachmentsDir, `${kept.id}.png`));
474 yield* edit([kept]);
475 expect(captured).toHaveLength(2);
476 }).pipe(Effect.provide(layerIntakeTest)),
477);