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

ThreadMessageIntake.test.ts

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