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