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

ThreadManagementService.test.ts

747 lines27.8 KB

1import { expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 NodeId,
6 type OrchestrationV2Command,
7 type OrchestrationV2Run,
8 type OrchestrationV2Subagent,
9 type OrchestrationV2ProviderThread,
10 ProviderThreadId,
11 ProviderDriverKind,
12 ProviderSessionId,
13 type OrchestrationV2StoredEvent,
14 type OrchestrationV2ThreadProjection,
15 type OrchestrationV2ThreadShell,
16 ProjectId,
17 ProviderInstanceId,
18 RunId,
19 ThreadId,
20} from "@t3tools/contracts";
21import * as Deferred from "effect/Deferred";
22import * as DateTime from "effect/DateTime";
23import * as Option from "effect/Option";
24import * as Duration from "effect/Duration";
25import * as Effect from "effect/Effect";
26import * as Fiber from "effect/Fiber";
27import * as Layer from "effect/Layer";
28import * as Queue from "effect/Queue";
29import * as Ref from "effect/Ref";
30import * as Stream from "effect/Stream";
31import * as TestClock from "effect/testing/TestClock";
32​
33import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
34import * as Orchestrator from "./Orchestrator.ts";
35import * as ProviderSessionManager from "./ProviderSessionManager.ts";
36import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
37import * as ThreadManagementService from "./ThreadManagementService.ts";
38import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
39import { DispatchModeLimit, type DispatchModeRefusal } from "./DispatchModeLimit.ts";
40​
41it("stamps authoritative provenance on commands that create threads or messages", () => {
42 const command: OrchestrationV2Command = {
43 type: "thread.create",
44 createdBy: "agent",
45 creationSource: "mcp",
46 commandId: CommandId.make("command:thread-management:create"),
47 threadId: ThreadId.make("thread:thread-management:create"),
48 projectId: ProjectId.make("project:thread-management"),
49 title: "Thread management",
50 modelSelection: {
51 instanceId: ProviderInstanceId.make("codex"),
52 model: "gpt-5-codex",
53 },
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 branch: null,
57 worktreePath: null,
58 };
59​
60 expect(
61 ThreadManagementService.withCreationProvenance(command, {
62 createdBy: "user",
63 creationSource: "web",
64 }),
65 ).toMatchObject({
66 createdBy: "user",
67 creationSource: "web",
68 });
69});
70​
71it("leaves commands that do not create durable authored content unchanged", () => {
72 const command: OrchestrationV2Command = {
73 type: "run.interrupt",
74 commandId: CommandId.make("command:thread-management:interrupt"),
75 threadId: ThreadId.make("thread:thread-management:interrupt"),
76 runId: RunId.make("run:thread-management:interrupt"),
77 };
78​
79 expect(
80 ThreadManagementService.withCreationProvenance(command, {
81 createdBy: "user",
82 creationSource: "web",
83 }),
84 ).toBe(command);
85});
86​
87it("identifies every existing thread that must be hydrated before dispatch", () => {
88 const sourceThreadId = ThreadId.make("thread:thread-management:source");
89 const targetThreadId = ThreadId.make("thread:thread-management:target");
90 const parentThreadId = ThreadId.make("thread:thread-management:parent");
91​
92 expect(
93 ThreadManagementService.existingThreadIdsForCommand({
94 type: "thread.create",
95 createdBy: "user",
96 creationSource: "web",
97 commandId: CommandId.make("command:thread-management:create"),
98 threadId: targetThreadId,
99 projectId: ProjectId.make("project:thread-management"),
100 title: "Created thread",
101 modelSelection: {
102 instanceId: ProviderInstanceId.make("codex"),
103 model: "gpt-5-codex",
104 },
105 runtimeMode: "full-access",
106 interactionMode: "default",
107 branch: null,
108 worktreePath: null,
109 }),
110 ).toEqual([]);
111​
112 expect(
113 ThreadManagementService.existingThreadIdsForCommand({
114 type: "thread.archive",
115 commandId: CommandId.make("command:thread-management:archive"),
116 threadId: targetThreadId,
117 }),
118 ).toEqual([targetThreadId]);
119​
120 // Read-state commands skip transcript hydration entirely: they fire on
121 // every activity bump while a thread is open and never touch messages.
122 expect(
123 ThreadManagementService.existingThreadIdsForCommand({
124 type: "thread.visit",
125 commandId: CommandId.make("command:thread-management:visit"),
126 threadId: targetThreadId,
127 visitedAt: "2026-07-30T00:00:00.000Z",
128 }),
129 ).toEqual([]);
130​
131 expect(
132 ThreadManagementService.existingThreadIdsForCommand({
133 type: "thread.mark-unread",
134 commandId: CommandId.make("command:thread-management:mark-unread"),
135 threadId: targetThreadId,
136 }),
137 ).toEqual([]);
138​
139 expect(
140 ThreadManagementService.existingThreadIdsForCommand({
141 type: "thread.fork",
142 createdBy: "user",
143 creationSource: "web",
144 commandId: CommandId.make("command:thread-management:fork"),
145 sourceThreadId,
146 targetThreadId,
147 sourcePoint: {
148 type: "run",
149 runId: RunId.make("run:thread-management:source"),
150 },
151 }),
152 ).toEqual([sourceThreadId]);
153​
154 expect(
155 ThreadManagementService.existingThreadIdsForCommand({
156 type: "thread.merge_back",
157 createdBy: "user",
158 creationSource: "web",
159 commandId: CommandId.make("command:thread-management:merge"),
160 sourceThreadId,
161 targetThreadId,
162 sourcePoint: {
163 type: "run",
164 runId: RunId.make("run:thread-management:source"),
165 },
166 }),
167 ).toEqual([sourceThreadId, targetThreadId]);
168​
169 expect(
170 ThreadManagementService.existingThreadIdsForCommand({
171 type: "delegated_task.request",
172 createdBy: "agent",
173 creationSource: "provider",
174 commandId: CommandId.make("command:thread-management:delegate"),
175 parentThreadId,
176 parentRunId: RunId.make("run:thread-management:parent"),
177 parentNodeId: NodeId.make("node:thread-management:parent"),
178 task: "Inspect the migration",
179 modelSelection: {
180 instanceId: ProviderInstanceId.make("codex"),
181 model: "gpt-5-codex",
182 },
183 runtimeMode: "full-access",
184 interactionMode: "default",
185 }),
186 ).toEqual([parentThreadId]);
187​
188 expect(
189 ThreadManagementService.existingThreadIdsForCommand({
190 type: "delegated_task.wake-policy",
191 commandId: CommandId.make("command:thread-management:wake-policy"),
192 parentThreadId,
193 taskId: NodeId.make("node:thread-management:delegated"),
194 completionWake: "always",
195 }),
196 ).toEqual([parentThreadId]);
197​
198 expect(
199 ThreadManagementService.existingThreadIdsForCommand({
200 type: "thread.created.record",
201 commandId: CommandId.make("command:thread-management:record"),
202 parentThreadId,
203 parentRunId: RunId.make("run:thread-management:parent"),
204 parentNodeId: NodeId.make("node:thread-management:parent"),
205 targetThreadId,
206 targetRunId: null,
207 }),
208 ).toEqual([parentThreadId, targetThreadId]);
209});
210​
211it("derives thread management messages from structural error attributes", () => {
212 const projectId = ProjectId.make("project:thread-management:errors");
213 const threadId = ThreadId.make("thread:thread-management:errors");
214 const runId = RunId.make("run:thread-management:errors");
215 const messageId = MessageId.make("message:thread-management:errors");
216 const infrastructureCause = new Error("private sqlite detail");
217​
218 const threadNotFound = new ThreadManagementService.ThreadManagementThreadNotFoundError({
219 projectId,
220 threadId,
221 });
222 expect(threadNotFound).toMatchObject({ projectId, threadId });
223 expect(threadNotFound.message).toBe(`Thread ${threadId} was not found in project ${projectId}.`);
224​
225 const runNotFound = new ThreadManagementService.ThreadManagementRunNotFoundError({
226 threadId,
227 runId,
228 });
229 expect(runNotFound).toMatchObject({ threadId, runId });
230 expect(runNotFound.message).toBe(`Run ${runId} does not belong to thread ${threadId}.`);
231​
232 const archived = new ThreadManagementService.ThreadManagementThreadArchivedError({
233 threadId,
234 });
235 expect(archived).toMatchObject({ threadId });
236 expect(archived.message).toBe(`Thread ${threadId} is archived and cannot receive messages.`);
237​
238 const notSteerable = new ThreadManagementService.ThreadManagementNoSteerableRunError({
239 threadId,
240 mode: "restart",
241 });
242 expect(notSteerable).toMatchObject({
243 threadId,
244 mode: "restart",
245 });
246 expect(notSteerable.message).toBe(
247 `Thread ${threadId} has no running turn that can be restarted.`,
248 );
249​
250 const notInterruptible = new ThreadManagementService.ThreadManagementThreadNotInterruptibleError({
251 threadId,
252 runId,
253 });
254 expect(notInterruptible).toMatchObject({ threadId, runId });
255 expect(notInterruptible.message).toBe(`Run ${runId} is not currently interruptible.`);
256​
257 const listFailure = new ThreadManagementService.ThreadManagementProjectThreadsListError({
258 projectId,
259 cause: infrastructureCause,
260 });
261 expect(listFailure).toMatchObject({ projectId, cause: infrastructureCause });
262 expect(listFailure.message).toBe(`Unable to list threads in project ${projectId}.`);
263 expect(listFailure.message).not.toContain(infrastructureCause.message);
264​
265 const durableProjectionFailure =
266 new ThreadManagementService.ThreadManagementDurableRunProjectionError({
267 threadId,
268 messageId,
269 });
270 expect(durableProjectionFailure).toMatchObject({ threadId, messageId });
271 expect(durableProjectionFailure.message).toBe(
272 `Message ${messageId} was accepted on thread ${threadId} without a durable run projection.`,
273 );
274});
275​
276it.effect("classifies projection infrastructure failures separately from a missing thread", () => {
277 const projectId = ProjectId.make("project:thread-management:projection-failure");
278 const threadId = ThreadId.make("thread:thread-management:projection-failure");
279 const infrastructureCause = new Error("sqlite read failed");
280 const projectionError = new Orchestrator.OrchestratorProjectionError({
281 threadId,
282 cause: infrastructureCause,
283 });
284 const layerTest = ThreadManagementService.layer.pipe(
285 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
286 Layer.provide(
287 Layer.mock(Orchestrator.OrchestratorV2)({
288 getThreadProjection: () => Effect.fail(projectionError),
289 }),
290 ),
291 );
292​
293 return Effect.gen(function* () {
294 const service = yield* ThreadManagementService.ThreadManagementService;
295 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
296​
297 expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementProjectionLoadError);
298 expect(error).toMatchObject({
299 projectId,
300 threadId,
301 cause: projectionError,
302 });
303 expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`);
304 }).pipe(Effect.provide(layerTest));
305});
306​
307it.effect("uses thread-not-found only after a projection loads outside the project", () => {
308 const projectId = ProjectId.make("project:thread-management:requested");
309 const otherProjectId = ProjectId.make("project:thread-management:other");
310 const threadId = ThreadId.make("thread:thread-management:wrong-project");
311 const projection = {
312 thread: {
313 id: threadId,
314 projectId: otherProjectId,
315 deletedAt: null,
316 },
317 } as OrchestrationV2ThreadProjection;
318 const layerTest = ThreadManagementService.layer.pipe(
319 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
320 Layer.provide(
321 Layer.mock(Orchestrator.OrchestratorV2)({
322 getThreadProjection: () => Effect.succeed(projection),
323 }),
324 ),
325 );
326​
327 return Effect.gen(function* () {
328 const service = yield* ThreadManagementService.ThreadManagementService;
329 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
330​
331 expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementThreadNotFoundError);
332 expect(error).toMatchObject({ projectId, threadId });
333 expect("cause" in error).toBe(false);
334 }).pipe(Effect.provide(layerTest));
335});
336​
337it.effect("preserves failed legacy materialization when reading checkpoint context", () => {
338 const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure");
339 const importError = new LegacyV1ThreadImporter.LegacyV1ThreadImportError({
340 threadId,
341 operation: "hydrate transcript for",
342 cause: new Error("checkpoint import failed"),
343 });
344 const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe(
345 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
346 Layer.provide(
347 Layer.mergeAll(
348 Layer.mock(Orchestrator.OrchestratorV2)({
349 getCheckpointContext: () =>
350 Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
351 }),
352 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
353 ensureTranscript: () => Effect.fail(importError),
354 }),
355 ),
356 ),
357 );
358 return Effect.gen(function* () {
359 const service = yield* ThreadManagementService.ThreadManagementService;
360 const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip);
361 expect(error).toBeInstanceOf(Orchestrator.OrchestratorProjectionError);
362 expect(error).toMatchObject({ threadId, cause: importError });
363 }).pipe(Effect.provide(layerTest));
364});
365​
366it.effect.each([
367 { finalStatus: "completed" as const, timedOut: false },
368 { finalStatus: "failed" as const, timedOut: false },
369 { finalStatus: "cancelled" as const, timedOut: false },
370 { finalStatus: "interrupted" as const, timedOut: false },
371 { finalStatus: "rolled_back" as const, timedOut: false },
372 { finalStatus: "running" as const, timedOut: true },
373 { finalStatus: "missing" as const },
374])("waitForThread timeout final read when selected run is $finalStatus", (scenario) =>
375 Effect.gen(function* () {
376 const projectId = ProjectId.make("project:thread-management:wait-timeout");
377 const threadId = ThreadId.make("thread:thread-management:wait-timeout");
378 const runId = RunId.make("run:thread-management:wait-timeout");
379 const subscribed = yield* Deferred.make<void>();
380 let reads = 0;
381 const projection = (status: OrchestrationV2Run["status"] | "missing") =>
382 ({
383 thread: { id: threadId, projectId, deletedAt: null },
384 runs: status === "missing" ? [] : [{ id: runId, status }],
385 }) as unknown as OrchestrationV2ThreadProjection;
386 const layerTest = ThreadManagementService.layer.pipe(
387 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
388 Layer.provide(
389 Layer.mock(Orchestrator.OrchestratorV2)({
390 getThreadEventSequence: () => Effect.succeed(0),
391 // No run update arrives, so the timeout path runs while a final
392 // projection read can still observe a terminal run.
393 streamStoredEventsFrom: () =>
394 Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
395 Stream.drain,
396 Stream.concat(Stream.never),
397 ),
398 getThreadRecords: () =>
399 Effect.sync(() => {
400 reads += 1;
401 return projection(reads === 1 ? "running" : scenario.finalStatus);
402 }),
403 }),
404 ),
405 );
406 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
407 Effect.provide(layerTest),
408 );
409 const fiber = yield* service
410 .waitForThread({
411 projectId,
412 threadId,
413 runId,
414 timeoutMs: 1,
415 })
416 .pipe(Effect.result, Effect.forkChild);
417 yield* Deferred.await(subscribed);
418 yield* TestClock.adjust(Duration.millis(1));
419 const result = yield* Fiber.join(fiber);
420​
421 if (scenario.finalStatus === "missing") {
422 expect(result._tag).toBe("Failure");
423 expect(result).toMatchObject({
424 failure: expect.any(ThreadManagementService.ThreadManagementRunNotFoundError),
425 });
426 expect(result).toMatchObject({
427 failure: { threadId, runId },
428 });
429 } else {
430 expect(result._tag).toBe("Success");
431 expect(result).toMatchObject({
432 success: {
433 threadId,
434 timedOut: scenario.timedOut,
435 run: { id: runId, status: scenario.finalStatus },
436 },
437 });
438 }
439 }),
440);
441​
442it.effect("waitForThread reads the run again only when the run updates", () =>
443 Effect.gen(function* () {
444 const projectId = ProjectId.make("project:thread-management:wait-event");
445 const threadId = ThreadId.make("thread:thread-management:wait-event");
446 const runId = RunId.make("run:thread-management:wait-event");
447 const subscribed = yield* Deferred.make<void>();
448 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
449 let status: OrchestrationV2Run["status"] = "running";
450 let reads = 0;
451 const stored = (sequence: number, event: object) =>
452 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
453 const layerTest = ThreadManagementService.layer.pipe(
454 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
455 Layer.provide(
456 Layer.mock(Orchestrator.OrchestratorV2)({
457 getThreadEventSequence: () => Effect.succeed(0),
458 // Only the run.updated stream carries events in this test.
459 streamStoredEventsFrom: (input) =>
460 input?.eventType === "run.updated"
461 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
462 Stream.drain,
463 Stream.concat(Stream.fromQueue(events)),
464 )
465 : Stream.never,
466 getThreadRecords: () =>
467 Effect.sync(() => {
468 reads += 1;
469 return {
470 thread: { id: threadId, projectId, deletedAt: null },
471 runs: [{ id: runId, status }],
472 } as unknown as OrchestrationV2ThreadProjection;
473 }),
474 }),
475 ),
476 );
477 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
478 Effect.provide(layerTest),
479 );
480 const fiber = yield* service
481 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
482 .pipe(Effect.forkChild);
483 yield* Deferred.await(subscribed);
484 status = "completed";
485 yield* Queue.offer(events, stored(1, { type: "run.updated", payload: { id: "other-run" } }));
486 yield* Queue.offer(events, stored(2, { type: "run.updated", payload: { id: runId, status } }));
487 const result = yield* Fiber.join(fiber);
488​
489 expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "completed" } });
490 // The first read plus one for this run's update. The other run caused none.
491 expect(reads).toBe(2);
492 }),
493);
494​
495it.effect.each([
496 "running",
497 "missing",
498 "completed",
499 "unsupported",
500 "missing-native-id",
501 "wrong-thread",
502 "no-session",
503 "unsupported-runtime",
504 "provider-failed",
505 "provider-timeout",
506 "within-limit",
507 "runtime-raised",
508 "interaction-raised",
509] as const)("stops a persisted workflow with state %s", (state) =>
510 Effect.gen(function* () {
511 const threadId = ThreadId.make("thread:workflow-stop");
512 const subagentId = NodeId.make("node:workflow-stop");
513 const runId = RunId.make("run:workflow-stop");
514 const providerThreadId = ProviderThreadId.make("provider-thread:workflow-stop");
515 const providerSessionId = ProviderSessionId.make("provider-session:workflow-stop");
516 const driver = ProviderDriverKind.make("claudeAgent");
517 const instanceId = ProviderInstanceId.make("claudeAgent");
518 const now = yield* DateTime.now;
519 let targetModes: Pick<OrchestrationV2ThreadShell, "runtimeMode" | "interactionMode"> = {
520 runtimeMode: "approval-required",
521 interactionMode: "plan",
522 };
523 const task: OrchestrationV2Subagent = {
524 id: subagentId,
525 threadId,
526 runId,
527 parentNodeId: NodeId.make("node:workflow-parent"),
528 origin: "provider_native",
529 createdBy: "agent",
530 driver,
531 providerInstanceId: instanceId,
532 providerThreadId: null,
533 childThreadId: null,
534 nativeTaskRef:
535 state === "missing-native-id"
536 ? null
537 : {
538 driver,
539 nativeId: "native-workflow-id",
540 strength: "strong",
541 },
542 workflow: { phases: [], agents: [] },
543 prompt: "Run the workflow",
544 title: null,
545 model: null,
546 status: state === "completed" ? "completed" : "running",
547 result: null,
548 startedAt: now,
549 completedAt: null,
550 updatedAt: now,
551 ...(state === "unsupported" ? { driver: ProviderDriverKind.make("codex") } : {}),
552 };
553 const providerThread: OrchestrationV2ProviderThread = {
554 id: providerThreadId,
555 driver,
556 providerInstanceId: instanceId,
557 providerSessionId,
558 appThreadId: state === "wrong-thread" ? ThreadId.make("other-thread") : threadId,
559 ownerNodeId: null,
560 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
561 nativeConversationHeadRef: null,
562 status: "idle",
563 firstRunOrdinal: 1,
564 lastRunOrdinal: 1,
565 handoffIds: [],
566 forkedFrom: null,
567 pendingBackgroundTasks: [],
568 contextUsage: null,
569 nativeMetadata: null,
570 createdAt: now,
571 updatedAt: now,
572 };
573 const calls: Array<{ taskId: string; providerThread: OrchestrationV2ProviderThread }> = [];
574 const stopStarted = yield* Deferred.make<void>();
575 const runtime = {
576 driver,
577 providerSessionId,
578 instanceId,
579 ...(state === "unsupported-runtime"
580 ? {}
581 : {
582 stopTask: (input: (typeof calls)[number]) =>
583 state === "provider-failed"
584 ? Effect.fail(
585 new ProviderAdapter.ProviderAdapterProtocolError({
586 driver,
587 detail: "private provider detail",
588 }),
589 )
590 : state === "provider-timeout"
591 ? Deferred.succeed(stopStarted, undefined).pipe(Effect.andThen(Effect.never))
592 : Effect.sync(() => {
593 calls.push(input);
594 }),
595 }),
596 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
597 const layerTest = ThreadManagementService.layer.pipe(
598 Layer.provide(
599 Layer.mergeAll(
600 Layer.mock(Orchestrator.OrchestratorV2)({
601 getThreadRecords: () =>
602 Effect.sync(
603 () =>
604 ({
605 thread: { id: threadId, deletedAt: null, ...targetModes },
606 subagents: state === "missing" ? [] : [task],
607 runs: [{ id: runId, providerThreadId }],
608 providerThreads: [providerThread],
609 }) as unknown as OrchestrationV2ThreadProjection,
610 ),
611 }),
612 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
613 get: (id) => {
614 expect(id).toBe(providerSessionId);
615 return Effect.succeed(state === "no-session" ? Option.none() : Option.some(runtime));
616 },
617 }),
618 ),
619 ),
620 );
621 yield* Effect.gen(function* () {
622 const service = yield* ThreadManagementService.ThreadManagementService;
623 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
624 const stop = service
625 .stopWorkflow({ threadId, subagentId })
626 .pipe(
627 Effect.provideService(
628 DispatchModeLimit,
629 state === "within-limit" || state === "runtime-raised" || state === "interaction-raised"
630 ? { runtimeMode: "approval-required", interactionMode: "plan", refused }
631 : undefined,
632 ),
633 Effect.result,
634 );
635 const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
636 const result =
637 state === "runtime-raised" || state === "interaction-raised"
638 ? yield* Effect.gen(function* () {
639 const started = yield* Deferred.make<void>();
640 const pending = yield* executor.withLock(
641 threadId,
642 Effect.gen(function* () {
643 const fiber = yield* Deferred.succeed(started, undefined).pipe(
644 Effect.andThen(stop),
645 Effect.forkChild,
646 );
647 yield* Deferred.await(started);
648 targetModes =
649 state === "runtime-raised"
650 ? { ...targetModes, runtimeMode: "full-access" }
651 : { ...targetModes, interactionMode: "default" };
652 return fiber;
653 }),
654 );
655 return yield* Fiber.join(pending);
656 })
657 : state === "provider-timeout"
658 ? yield* Effect.gen(function* () {
659 const finished = yield* Ref.make(false);
660 const pending = yield* stop.pipe(
661 Effect.tap(() => Ref.set(finished, true)),
662 Effect.forkChild,
663 );
664 yield* Deferred.await(stopStarted);
665 yield* TestClock.adjust("15 seconds");
666 expect(yield* Ref.get(finished)).toBe(true);
667 const result = yield* Fiber.join(pending);
668 expect(yield* executor.withLock(threadId, Effect.succeed("lock-released"))).toBe(
669 "lock-released",
670 );
671 return result;
672 })
673 : yield* stop;
674 if (state === "running" || state === "within-limit") {
675 expect(result).toMatchObject({ _tag: "Success" });
676 expect(calls).toEqual([{ taskId: "native-workflow-id", providerThread }]);
677 expect(task.status).toBe("running");
678 } else {
679 expect(result).toMatchObject({
680 _tag: "Failure",
681 failure: {
682 _tag: "OrchestrationV2StopWorkflowError",
683 threadId,
684 subagentId,
685 reason:
686 state === "missing" || state === "completed"
687 ? "not-running"
688 : state === "unsupported" || state === "unsupported-runtime"
689 ? "unsupported"
690 : state === "provider-failed" || state === "provider-timeout"
691 ? "stop-failed"
692 : "unavailable",
693 },
694 });
695 expect(calls).toEqual([]);
696 if (state === "provider-timeout") {
697 expect(result).toMatchObject({ failure: { cause: { _tag: "TimeoutError" } } });
698 }
699 if (state === "runtime-raised" || state === "interaction-raised") {
700 expect(yield* Ref.get(refused)).toEqual({
701 threadId,
702 ...targetModes,
703 mode: state === "runtime-raised" ? "runtime" : "interaction",
704 });
705 }
706 }
707 }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer)));
708 }),
709);
710​
711it.effect.each([
712 { status: "completed" as const, settles: true },
713 { status: "failed" as const, settles: false },
714 { status: "interrupted" as const, settles: false },
715])("settleAfterRun settles only when the run $status", ({ status, settles }) =>
716 Effect.gen(function* () {
717 const projectId = ProjectId.make("project:thread-management:settle-after-run");
718 const threadId = ThreadId.make("thread:thread-management:settle-after-run");
719 const runId = RunId.make("run:thread-management:settle-after-run");
720 const dispatched: Array<string> = [];
721 const layerTest = ThreadManagementService.layer.pipe(
722 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
723 Layer.provide(
724 Layer.mock(Orchestrator.OrchestratorV2)({
725 getThreadEventSequence: () => Effect.succeed(0),
726 getThreadRecords: () =>
727 Effect.succeed({
728 thread: { id: threadId, projectId, deletedAt: null },
729 runs: [{ id: runId, status }],
730 } as unknown as OrchestrationV2ThreadProjection),
731 dispatch: (command) =>
732 Effect.sync(() => {
733 dispatched.push(command.type);
734 return { sequence: 1, storedEvents: [] } as never;
735 }),
736 }),
737 ),
738 );
739 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
740 Effect.provide(layerTest),
741 );
742​
743 yield* service.settleAfterRun({ projectId, threadId, runId });
744​
745 expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
746 }),
747);