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

ThreadManagementService.test.ts

431 lines14.6 KB

1import { expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 NodeId,
6 type OrchestrationV2Command,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadProjection,
9 ProjectId,
10 ProviderInstanceId,
11 RunId,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as Deferred from "effect/Deferred";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as TestClock from "effect/testing/TestClock";
20​
21import { LegacyV1ThreadImporter, LegacyV1ThreadImportError } from "./LegacyV1ThreadImporter.ts";
22import { OrchestratorProjectionError, OrchestratorV2 } from "./Orchestrator.ts";
23import {
24 existingThreadIdsForCommand,
25 layer,
26 layerWithLegacyImporter,
27 ThreadManagementDurableRunProjectionError,
28 ThreadManagementProjectThreadsListError,
29 ThreadManagementProjectionLoadError,
30 ThreadManagementRunNotFoundError,
31 ThreadManagementService,
32 ThreadManagementThreadNotFoundError,
33 ThreadManagementThreadNotInterruptibleError,
34 ThreadManagementThreadArchivedError,
35 ThreadManagementNoSteerableRunError,
36 withCreationProvenance,
37} from "./ThreadManagementService.ts";
38​
39it("stamps authoritative provenance on commands that create threads or messages", () => {
40 const command: OrchestrationV2Command = {
41 type: "thread.create",
42 createdBy: "agent",
43 creationSource: "mcp",
44 commandId: CommandId.make("command:thread-management:create"),
45 threadId: ThreadId.make("thread:thread-management:create"),
46 projectId: ProjectId.make("project:thread-management"),
47 title: "Thread management",
48 modelSelection: {
49 instanceId: ProviderInstanceId.make("codex"),
50 model: "gpt-5-codex",
51 },
52 runtimeMode: "full-access",
53 interactionMode: "default",
54 branch: null,
55 worktreePath: null,
56 };
57​
58 expect(
59 withCreationProvenance(command, {
60 createdBy: "user",
61 creationSource: "web",
62 }),
63 ).toMatchObject({
64 createdBy: "user",
65 creationSource: "web",
66 });
67});
68​
69it("leaves commands that do not create durable authored content unchanged", () => {
70 const command: OrchestrationV2Command = {
71 type: "run.interrupt",
72 commandId: CommandId.make("command:thread-management:interrupt"),
73 threadId: ThreadId.make("thread:thread-management:interrupt"),
74 runId: RunId.make("run:thread-management:interrupt"),
75 };
76​
77 expect(
78 withCreationProvenance(command, {
79 createdBy: "user",
80 creationSource: "web",
81 }),
82 ).toBe(command);
83});
84​
85it("identifies every existing thread that must be hydrated before dispatch", () => {
86 const sourceThreadId = ThreadId.make("thread:thread-management:source");
87 const targetThreadId = ThreadId.make("thread:thread-management:target");
88 const parentThreadId = ThreadId.make("thread:thread-management:parent");
89​
90 expect(
91 existingThreadIdsForCommand({
92 type: "thread.create",
93 createdBy: "user",
94 creationSource: "web",
95 commandId: CommandId.make("command:thread-management:create"),
96 threadId: targetThreadId,
97 projectId: ProjectId.make("project:thread-management"),
98 title: "Created thread",
99 modelSelection: {
100 instanceId: ProviderInstanceId.make("codex"),
101 model: "gpt-5-codex",
102 },
103 runtimeMode: "full-access",
104 interactionMode: "default",
105 branch: null,
106 worktreePath: null,
107 }),
108 ).toEqual([]);
109​
110 expect(
111 existingThreadIdsForCommand({
112 type: "thread.archive",
113 commandId: CommandId.make("command:thread-management:archive"),
114 threadId: targetThreadId,
115 }),
116 ).toEqual([targetThreadId]);
117​
118 // Read-state commands skip transcript hydration entirely: they fire on
119 // every activity bump while a thread is open and never touch messages.
120 expect(
121 existingThreadIdsForCommand({
122 type: "thread.visit",
123 commandId: CommandId.make("command:thread-management:visit"),
124 threadId: targetThreadId,
125 visitedAt: "2026-07-30T00:00:00.000Z",
126 }),
127 ).toEqual([]);
128​
129 expect(
130 existingThreadIdsForCommand({
131 type: "thread.mark-unread",
132 commandId: CommandId.make("command:thread-management:mark-unread"),
133 threadId: targetThreadId,
134 }),
135 ).toEqual([]);
136​
137 expect(
138 existingThreadIdsForCommand({
139 type: "thread.fork",
140 createdBy: "user",
141 creationSource: "web",
142 commandId: CommandId.make("command:thread-management:fork"),
143 sourceThreadId,
144 targetThreadId,
145 sourcePoint: {
146 type: "run",
147 runId: RunId.make("run:thread-management:source"),
148 },
149 }),
150 ).toEqual([sourceThreadId]);
151​
152 expect(
153 existingThreadIdsForCommand({
154 type: "thread.merge_back",
155 createdBy: "user",
156 creationSource: "web",
157 commandId: CommandId.make("command:thread-management:merge"),
158 sourceThreadId,
159 targetThreadId,
160 sourcePoint: {
161 type: "run",
162 runId: RunId.make("run:thread-management:source"),
163 },
164 }),
165 ).toEqual([sourceThreadId, targetThreadId]);
166​
167 expect(
168 existingThreadIdsForCommand({
169 type: "delegated_task.request",
170 createdBy: "agent",
171 creationSource: "provider",
172 commandId: CommandId.make("command:thread-management:delegate"),
173 parentThreadId,
174 parentRunId: RunId.make("run:thread-management:parent"),
175 parentNodeId: NodeId.make("node:thread-management:parent"),
176 task: "Inspect the migration",
177 modelSelection: {
178 instanceId: ProviderInstanceId.make("codex"),
179 model: "gpt-5-codex",
180 },
181 runtimeMode: "full-access",
182 interactionMode: "default",
183 }),
184 ).toEqual([parentThreadId]);
185​
186 expect(
187 existingThreadIdsForCommand({
188 type: "delegated_task.wake-policy",
189 commandId: CommandId.make("command:thread-management:wake-policy"),
190 parentThreadId,
191 taskId: NodeId.make("node:thread-management:delegated"),
192 completionWake: "always",
193 }),
194 ).toEqual([parentThreadId]);
195​
196 expect(
197 existingThreadIdsForCommand({
198 type: "thread.created.record",
199 commandId: CommandId.make("command:thread-management:record"),
200 parentThreadId,
201 parentRunId: RunId.make("run:thread-management:parent"),
202 parentNodeId: NodeId.make("node:thread-management:parent"),
203 targetThreadId,
204 targetRunId: null,
205 }),
206 ).toEqual([parentThreadId, targetThreadId]);
207});
208​
209it("derives thread management messages from structural error attributes", () => {
210 const projectId = ProjectId.make("project:thread-management:errors");
211 const threadId = ThreadId.make("thread:thread-management:errors");
212 const runId = RunId.make("run:thread-management:errors");
213 const messageId = MessageId.make("message:thread-management:errors");
214 const infrastructureCause = new Error("private sqlite detail");
215​
216 const threadNotFound = new ThreadManagementThreadNotFoundError({
217 projectId,
218 threadId,
219 });
220 expect(threadNotFound).toMatchObject({ projectId, threadId });
221 expect(threadNotFound.message).toBe(`Thread ${threadId} was not found in project ${projectId}.`);
222​
223 const runNotFound = new ThreadManagementRunNotFoundError({ threadId, runId });
224 expect(runNotFound).toMatchObject({ threadId, runId });
225 expect(runNotFound.message).toBe(`Run ${runId} does not belong to thread ${threadId}.`);
226​
227 const archived = new ThreadManagementThreadArchivedError({
228 threadId,
229 });
230 expect(archived).toMatchObject({ threadId });
231 expect(archived.message).toBe(`Thread ${threadId} is archived and cannot receive messages.`);
232​
233 const notSteerable = new ThreadManagementNoSteerableRunError({
234 threadId,
235 mode: "restart",
236 });
237 expect(notSteerable).toMatchObject({
238 threadId,
239 mode: "restart",
240 });
241 expect(notSteerable.message).toBe(
242 `Thread ${threadId} has no running turn that can be restarted.`,
243 );
244​
245 const notInterruptible = new ThreadManagementThreadNotInterruptibleError({
246 threadId,
247 runId,
248 });
249 expect(notInterruptible).toMatchObject({ threadId, runId });
250 expect(notInterruptible.message).toBe(`Run ${runId} is not currently interruptible.`);
251​
252 const listFailure = new ThreadManagementProjectThreadsListError({
253 projectId,
254 cause: infrastructureCause,
255 });
256 expect(listFailure).toMatchObject({ projectId, cause: infrastructureCause });
257 expect(listFailure.message).toBe(`Unable to list threads in project ${projectId}.`);
258 expect(listFailure.message).not.toContain(infrastructureCause.message);
259​
260 const durableProjectionFailure = new ThreadManagementDurableRunProjectionError({
261 threadId,
262 messageId,
263 });
264 expect(durableProjectionFailure).toMatchObject({ threadId, messageId });
265 expect(durableProjectionFailure.message).toBe(
266 `Message ${messageId} was accepted on thread ${threadId} without a durable run projection.`,
267 );
268});
269​
270it.effect("classifies projection infrastructure failures separately from a missing thread", () => {
271 const projectId = ProjectId.make("project:thread-management:projection-failure");
272 const threadId = ThreadId.make("thread:thread-management:projection-failure");
273 const infrastructureCause = new Error("sqlite read failed");
274 const projectionError = new OrchestratorProjectionError({
275 threadId,
276 cause: infrastructureCause,
277 });
278 const testLayer = layer.pipe(
279 Layer.provide(
280 Layer.mock(OrchestratorV2)({
281 getThreadProjection: () => Effect.fail(projectionError),
282 }),
283 ),
284 );
285​
286 return Effect.gen(function* () {
287 const service = yield* ThreadManagementService;
288 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
289​
290 expect(error).toBeInstanceOf(ThreadManagementProjectionLoadError);
291 expect(error).toMatchObject({
292 projectId,
293 threadId,
294 cause: projectionError,
295 });
296 expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`);
297 }).pipe(Effect.provide(testLayer));
298});
299​
300it.effect("uses thread-not-found only after a projection loads outside the project", () => {
301 const projectId = ProjectId.make("project:thread-management:requested");
302 const otherProjectId = ProjectId.make("project:thread-management:other");
303 const threadId = ThreadId.make("thread:thread-management:wrong-project");
304 const projection = {
305 thread: {
306 id: threadId,
307 projectId: otherProjectId,
308 deletedAt: null,
309 },
310 } as OrchestrationV2ThreadProjection;
311 const testLayer = layer.pipe(
312 Layer.provide(
313 Layer.mock(OrchestratorV2)({
314 getThreadProjection: () => Effect.succeed(projection),
315 }),
316 ),
317 );
318​
319 return Effect.gen(function* () {
320 const service = yield* ThreadManagementService;
321 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
322​
323 expect(error).toBeInstanceOf(ThreadManagementThreadNotFoundError);
324 expect(error).toMatchObject({ projectId, threadId });
325 expect("cause" in error).toBe(false);
326 }).pipe(Effect.provide(testLayer));
327});
328​
329it.effect("preserves failed legacy materialization when reading checkpoint context", () => {
330 const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure");
331 const importError = new LegacyV1ThreadImportError({
332 threadId,
333 operation: "hydrate transcript for",
334 cause: new Error("checkpoint import failed"),
335 });
336 const testLayer = layerWithLegacyImporter.pipe(
337 Layer.provide(
338 Layer.mergeAll(
339 Layer.mock(OrchestratorV2)({
340 getCheckpointContext: () =>
341 Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
342 }),
343 Layer.mock(LegacyV1ThreadImporter)({
344 ensureTranscript: () => Effect.fail(importError),
345 }),
346 ),
347 ),
348 );
349 return Effect.gen(function* () {
350 const service = yield* ThreadManagementService;
351 const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip);
352 expect(error).toBeInstanceOf(OrchestratorProjectionError);
353 expect(error).toMatchObject({ threadId, cause: importError });
354 }).pipe(Effect.provide(testLayer));
355});
356​
357for (const scenario of [
358 { finalStatus: "completed" as const, timedOut: false },
359 { finalStatus: "failed" as const, timedOut: false },
360 { finalStatus: "cancelled" as const, timedOut: false },
361 { finalStatus: "interrupted" as const, timedOut: false },
362 { finalStatus: "rolled_back" as const, timedOut: false },
363 { finalStatus: "running" as const, timedOut: true },
364 { finalStatus: "missing" as const },
365]) {
366 it.effect(`waitForThread timeout final read when selected run is ${scenario.finalStatus}`, () =>
367 Effect.gen(function* () {
368 const projectId = ProjectId.make("project:thread-management:wait-timeout");
369 const threadId = ThreadId.make("thread:thread-management:wait-timeout");
370 const runId = RunId.make("run:thread-management:wait-timeout");
371 const loopRead = yield* Deferred.make<void>();
372 let reads = 0;
373 const projection = (status: OrchestrationV2Run["status"] | "missing") =>
374 ({
375 thread: { id: threadId, projectId, deletedAt: null },
376 runs: status === "missing" ? [] : [{ id: runId, status }],
377 }) as unknown as OrchestrationV2ThreadProjection;
378 const testLayer = layer.pipe(
379 Layer.provide(
380 Layer.mock(OrchestratorV2)({
381 getThreadProjection: () =>
382 Effect.gen(function* () {
383 reads += 1;
384 if (reads === 1) {
385 return projection("running");
386 }
387 if (reads === 2) {
388 // Park inside the wait loop so the timeout path runs while a
389 // final projection read can still observe a terminal run.
390 yield* Deferred.succeed(loopRead, undefined);
391 return yield* Effect.never;
392 }
393 return projection(scenario.finalStatus);
394 }),
395 }),
396 ),
397 );
398 const service = yield* ThreadManagementService.pipe(Effect.provide(testLayer));
399 const fiber = yield* service
400 .waitForThread({
401 projectId,
402 threadId,
403 runId,
404 timeoutMs: 1,
405 })
406 .pipe(Effect.result, Effect.forkChild);
407 yield* Deferred.await(loopRead);
408 yield* TestClock.adjust(Duration.millis(1));
409 const result = yield* Fiber.join(fiber);
410​
411 if (scenario.finalStatus === "missing") {
412 expect(result._tag).toBe("Failure");
413 expect(result).toMatchObject({
414 failure: expect.any(ThreadManagementRunNotFoundError),
415 });
416 expect(result).toMatchObject({
417 failure: { threadId, runId },
418 });
419 } else {
420 expect(result._tag).toBe("Success");
421 expect(result).toMatchObject({
422 success: {
423 threadId,
424 timedOut: scenario.timedOut,
425 run: { id: runId, status: scenario.finalStatus },
426 },
427 });
428 }
429 }),
430 );