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