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