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

commands.test.ts

750 lines26.4 KB

1import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 CommandId,
6 EnvironmentId,
7 MessageId,
8 NodeId,
9 ORCHESTRATION_V2_WS_METHODS,
10 ProjectId,
11 ProviderInstanceId,
12 ProviderDriverKind,
13 RunId,
14 ThreadId,
15 TurnItemId,
16 WS_METHODS,
17 type OrchestrationV2Command,
18 type OrchestrationV2ThreadLaunchInput,
19 type OrchestrationV2ThreadProjection,
20 type ProjectMutation,
21} from "@t3tools/contracts";
22import { describe, expect, it } from "@effect/vitest";
23import * as Cause from "effect/Cause";
24import * as SecureRandom from "effect/crypto/SecureRandom";
25import * as Deferred from "effect/Deferred";
26import * as Effect from "effect/Effect";
27import * as Exit from "effect/Exit";
28import * as Fiber from "effect/Fiber";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as SubscriptionRef from "effect/SubscriptionRef";
32import * as TestClock from "effect/testing/TestClock";
33import { RpcClientError } from "effect/rpc";
34​
35import {
36 AVAILABLE_CONNECTION_STATE,
37 PrimaryConnectionTarget,
38 type PreparedConnection,
39 type SupervisorConnectionState,
40} from "../connection/model.ts";
41import * as EnvironmentSupervisor from "../connection/supervisor.ts";
42import * as RpcSession from "../rpc/session.ts";
43import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
44import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
45import {
46 archiveThread,
47 interruptThreadTurn,
48 revertThreadCheckpoint,
49 resumeThreadQueue,
50 startThreadTurn,
51} from "./commands.ts";
52​
53const layerTestRandom = Layer.succeed(
54 SecureRandom.SecureRandom,
55 SecureRandom.make((size) => new Uint8Array(size)),
56);
57​
58const TARGET = new PrimaryConnectionTarget({
59 environmentId: EnvironmentId.make("environment-1"),
60 label: "Test environment",
61 httpBaseUrl: "https://environment.example.test",
62 wsBaseUrl: "wss://environment.example.test",
63});
64​
65const CONNECTED_STATE: SupervisorConnectionState = {
66 ...AVAILABLE_CONNECTION_STATE,
67 desired: true,
68 phase: "connected",
69};
70​
71const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
72 readonly commands: OrchestrationV2Command[];
73 readonly projects: ProjectMutation[];
74 readonly launches?: OrchestrationV2ThreadLaunchInput[];
75 readonly projection?: OrchestrationV2ThreadProjection;
76 readonly projectionRequests?: ThreadId[];
77 readonly advertiseThreadStop?: boolean;
78}) {
79 const client = {
80 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
81 Effect.sync(() => {
82 input.commands.push(command);
83 return { sequence: input.commands.length };
84 }),
85 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (requestInput: {
86 readonly threadId: ThreadId;
87 }) =>
88 Effect.sync(() => {
89 input.projectionRequests?.push(requestInput.threadId);
90 return input.projection ?? v2Projection;
91 }),
92 [ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) =>
93 Effect.sync(() => {
94 input.launches?.push(launchInput);
95 return {
96 threadId: launchInput.threadId ?? v2ThreadId,
97 projection: input.projection ?? v2Projection,
98 resumed: false,
99 };
100 }),
101 [WS_METHODS.projectsMutate]: (mutation: ProjectMutation) =>
102 Effect.sync(() => {
103 input.projects.push(mutation);
104 return {
105 id: mutation.projectId,
106 title: mutation.type === "project.create" ? mutation.title : "Project",
107 workspaceRoot:
108 mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project",
109 repositoryIdentity: null,
110 faviconPath: null,
111 defaultModelSelection: null,
112 scripts: [],
113 createdAt: "2026-06-06T00:00:00.000Z",
114 updatedAt: "2026-06-06T00:00:00.000Z",
115 deletedAt: null,
116 };
117 }),
118 } as unknown as WsRpcProtocolClient;
119 const session: RpcSession.RpcSession = {
120 client,
121 initialConfig: Effect.succeed({
122 environment: {
123 capabilities: {
124 repositoryIdentity: true,
125 ...(input.advertiseThreadStop === true ? { threadStop: true } : {}),
126 },
127 },
128 } as never),
129 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
130 ready: Effect.void,
131 probe: Effect.void,
132 inboundFrames: Effect.succeed(0),
133 closed: Effect.never,
134 };
135 return EnvironmentSupervisor.EnvironmentSupervisor.of({
136 target: TARGET,
137 state: yield* SubscriptionRef.make(CONNECTED_STATE),
138 session: yield* SubscriptionRef.make(Option.some(session)),
139 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
140 connect: Effect.void,
141 disconnect: Effect.void,
142 retryNow: Effect.void,
143 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
144});
145​
146describe("V2 environment commands", () => {
147 it.effect("distinguishes sending a selected queued message from resuming queue order", () =>
148 Effect.gen(function* () {
149 const commands: OrchestrationV2Command[] = [];
150 const supervisor = yield* makeSupervisor({ commands, projects: [] });
151 const threadId = ThreadId.make("thread-1");
152 yield* resumeThreadQueue({
153 commandId: CommandId.make("send-selected"),
154 threadId,
155 runId: RunId.make("selected"),
156 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
157 yield* resumeThreadQueue({
158 commandId: CommandId.make("resume-queue"),
159 threadId,
160 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
161​
162 expect(commands).toEqual([
163 { type: "queued-run.start", commandId: "send-selected", threadId, runId: "selected" },
164 { type: "queue.resume", commandId: "resume-queue", threadId },
165 ]);
166 }).pipe(Effect.provide(layerTestRandom)),
167 );
168​
169 it.effect("preserves caller command ids for idempotent V2 commands", () =>
170 Effect.gen(function* () {
171 const commands: OrchestrationV2Command[] = [];
172 const supervisor = yield* makeSupervisor({ commands, projects: [] });
173​
174 yield* archiveThread({
175 commandId: CommandId.make("queued-command"),
176 threadId: ThreadId.make("thread-1"),
177 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
178​
179 expect(commands).toEqual([
180 { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
181 ]);
182 }).pipe(Effect.provide(layerTestRandom)),
183 );
184​
185 it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () =>
186 Effect.gen(function* () {
187 const scopeId = CheckpointScopeId.make("checkpoint-scope-root");
188 const checkpointId = CheckpointId.make("checkpoint-thread-start");
189 const projection: OrchestrationV2ThreadProjection = {
190 ...v2Projection,
191 checkpoints: [
192 {
193 id: checkpointId,
194 threadId: v2ThreadId,
195 scopeId,
196 runId: null,
197 nodeId: NodeId.make("node-run-1"),
198 parentCheckpointId: null,
199 ordinalWithinScope: 0,
200 appRunOrdinal: null,
201 ref: CheckpointRef.make("refs/t3/thread-start"),
202 status: "ready",
203 files: [],
204 capturedAt: v2Now,
205 },
206 ],
207 };
208 const commands: OrchestrationV2Command[] = [];
209 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
210​
211 yield* revertThreadCheckpoint({
212 commandId: CommandId.make("rollback-thread-start"),
213 threadId: v2ThreadId,
214 turnCount: 0,
215 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
216​
217 expect(commands).toEqual([
218 {
219 type: "checkpoint.rollback",
220 commandId: "rollback-thread-start",
221 threadId: v2ThreadId,
222 scopeId,
223 checkpointId,
224 },
225 ]);
226 }).pipe(Effect.provide(layerTestRandom)),
227 );
228​
229 it.effect("preserves an existing worktree and branch during first-message launch", () =>
230 Effect.gen(function* () {
231 const launches: OrchestrationV2ThreadLaunchInput[] = [];
232 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
233​
234 yield* startThreadTurn({
235 commandId: CommandId.make("launch-existing-worktree"),
236 threadId: v2ThreadId,
237 message: {
238 messageId: MessageId.make("message-existing-worktree"),
239 role: "user",
240 text: "Continue here",
241 attachments: [],
242 },
243 runtimeMode: "full-access",
244 interactionMode: "default",
245 titleSeed: "Continue here",
246 bootstrap: {
247 createThread: {
248 projectId: ProjectId.make("project-1"),
249 title: "Thread",
250 modelSelection: v2Projection.thread.modelSelection,
251 runtimeMode: "full-access",
252 interactionMode: "default",
253 branch: "feature",
254 worktreePath: "/workspace/project-worktrees/feature",
255 createdAt: "2026-06-20T00:00:00.000Z",
256 },
257 },
258 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
259​
260 expect(launches[0]).toMatchObject({
261 threadId: v2ThreadId,
262 title: "Continue here",
263 generateTitle: true,
264 workspaceStrategy: {
265 type: "existing_worktree",
266 worktreePath: "/workspace/project-worktrees/feature",
267 branch: "feature",
268 },
269 });
270 }).pipe(Effect.provide(layerTestRandom)),
271 );
272​
273 it.effect("uses server-resolved delivery intent without fetching the full projection", () =>
274 Effect.gen(function* () {
275 const commands: OrchestrationV2Command[] = [];
276 const projectionRequests: ThreadId[] = [];
277 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
278​
279 for (const [mode, expectedType] of [
280 ["queue", "queue_after_active"],
281 ["auto", "start_immediately"],
282 ["steer", "start_immediately"],
283 ["restart", "start_immediately"],
284 ] as const) {
285 yield* startThreadTurn({
286 commandId: CommandId.make(`command-${mode}`),
287 threadId: v2ThreadId,
288 message: {
289 messageId: MessageId.make(`message-${mode}`),
290 role: "user",
291 text: mode,
292 attachments: [],
293 },
294 runtimeMode: "full-access",
295 interactionMode: "default",
296 dispatchMode: mode,
297 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
298​
299 expect(commands.at(-1)).toMatchObject({
300 type: "message.dispatch",
301 dispatchMode: { type: expectedType },
302 ...(mode === "queue" ? {} : { deliveryIntent: mode }),
303 });
304 }
305 expect(projectionRequests).toEqual([]);
306 }).pipe(Effect.provide(layerTestRandom)),
307 );
308​
309 // A dead socket reaches the caller as a protocol error, or as an interrupt when
310 // the supervisor closes the session before the protocol reports the error.
311 it.effect.each([
312 [
313 "protocol error",
314 new RpcClientError.RpcClientError({
315 reason: new RpcClientError.RpcClientDefect({
316 message: "socket closed",
317 cause: new Error("socket closed"),
318 }),
319 }),
320 ],
321 ["session close", Effect.failCause(Cause.interrupt())],
322 ] as const)("retries a message dispatch lost to a %s with the same command id", ([, loss]) =>
323 Effect.gen(function* () {
324 const commands: OrchestrationV2Command[] = [];
325 const supervisor = yield* makeSupervisor({ commands, projects: [] });
326 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
327 const firstAttemptLost = yield* Deferred.make<void>();
328 const lostClient = {
329 ...healthySession.client,
330 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
331 Effect.gen(function* () {
332 commands.push(command);
333 yield* SubscriptionRef.set(supervisor.session, Option.none());
334 yield* Deferred.succeed(firstAttemptLost, undefined);
335 return yield* loss;
336 }),
337 } as unknown as WsRpcProtocolClient;
338 yield* SubscriptionRef.set(
339 supervisor.session,
340 Option.some({ ...healthySession, client: lostClient }),
341 );
342​
343 const sendFiber = yield* startThreadTurn({
344 commandId: CommandId.make("command-lost-ack"),
345 threadId: v2ThreadId,
346 message: {
347 messageId: MessageId.make("message-lost-ack"),
348 role: "user",
349 text: "hello",
350 attachments: [],
351 },
352 runtimeMode: "full-access",
353 interactionMode: "default",
354 }).pipe(
355 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
356 Effect.forkChild,
357 );
358 yield* Deferred.await(firstAttemptLost);
359 yield* SubscriptionRef.set(supervisor.session, Option.some(healthySession));
360 const exit = yield* Fiber.await(sendFiber);
361​
362 expect(commands.map((command) => [command.type, command.commandId])).toEqual([
363 ["message.dispatch", "command-lost-ack"],
364 ["message.dispatch", "command-lost-ack"],
365 ]);
366 expect(Exit.isSuccess(exit)).toBe(true);
367 }).pipe(Effect.provide(layerTestRandom)),
368 );
369​
370 it.effect("stops resending a message whose dispatch keeps losing the socket", () =>
371 Effect.gen(function* () {
372 const commands: OrchestrationV2Command[] = [];
373 const supervisor = yield* makeSupervisor({ commands, projects: [] });
374 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
375 const dyingClient: WsRpcProtocolClient = {
376 ...healthySession.client,
377 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
378 Effect.gen(function* () {
379 commands.push(command);
380 yield* SubscriptionRef.set(
381 supervisor.session,
382 Option.some({ ...healthySession, client: dyingClient }),
383 );
384 return yield* new RpcClientError.RpcClientError({
385 reason: new RpcClientError.RpcClientDefect({
386 message: "socket closed",
387 cause: new Error("socket closed"),
388 }),
389 });
390 }),
391 } as unknown as WsRpcProtocolClient;
392 yield* SubscriptionRef.set(
393 supervisor.session,
394 Option.some({ ...healthySession, client: dyingClient }),
395 );
396​
397 const error = yield* startThreadTurn({
398 commandId: CommandId.make("command-socket-killer"),
399 threadId: v2ThreadId,
400 message: {
401 messageId: MessageId.make("message-socket-killer"),
402 role: "user",
403 text: "hello",
404 attachments: [],
405 },
406 runtimeMode: "full-access",
407 interactionMode: "default",
408 }).pipe(
409 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
410 Effect.flip,
411 );
412​
413 expect(commands.map((command) => command.commandId)).toEqual([
414 "command-socket-killer",
415 "command-socket-killer",
416 "command-socket-killer",
417 ]);
418 expect(error._tag).toBe("RpcClientError");
419 }).pipe(Effect.provide(layerTestRandom)),
420 );
421​
422 it.effect("holds a lost message through reconnect backoff until disconnect", () =>
423 Effect.gen(function* () {
424 const commands: OrchestrationV2Command[] = [];
425 const supervisor = yield* makeSupervisor({ commands, projects: [] });
426 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
427 const lostClient = {
428 ...healthySession.client,
429 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
430 Effect.gen(function* () {
431 commands.push(command);
432 yield* SubscriptionRef.set(supervisor.session, Option.none());
433 return yield* new RpcClientError.RpcClientError({
434 reason: new RpcClientError.RpcClientDefect({
435 message: "socket closed",
436 cause: new Error("socket closed"),
437 }),
438 });
439 }),
440 } as unknown as WsRpcProtocolClient;
441 const send = (resendAfterSocketLoss: boolean) =>
442 Effect.gen(function* () {
443 yield* SubscriptionRef.set(
444 supervisor.session,
445 Option.some({ ...healthySession, client: lostClient }),
446 );
447 return yield* startThreadTurn({
448 commandId: CommandId.make(`command-host-gone-${resendAfterSocketLoss}`),
449 threadId: v2ThreadId,
450 message: {
451 messageId: MessageId.make(`message-host-gone-${resendAfterSocketLoss}`),
452 role: "user",
453 text: "hello",
454 attachments: [],
455 },
456 runtimeMode: "full-access",
457 interactionMode: "default",
458 resendAfterSocketLoss,
459 }).pipe(
460 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
461 Effect.flip,
462 Effect.forkChild,
463 );
464 });
465​
466 const optedOut = yield* send(false);
467 expect((yield* Fiber.join(optedOut))._tag).toBe("RpcClientError");
468​
469 const waiting = yield* send(true);
470 yield* SubscriptionRef.set(supervisor.state, {
471 ...CONNECTED_STATE,
472 phase: "backoff" as const,
473 });
474 yield* TestClock.adjust("2 minutes");
475 expect(waiting.pollUnsafe()).toBeUndefined();
476 yield* SubscriptionRef.set(supervisor.state, AVAILABLE_CONNECTION_STATE);
477 expect((yield* Fiber.join(waiting))._tag).toBe("RpcClientError");
478 expect(commands.map((command) => command.commandId)).toEqual([
479 "command-host-gone-false",
480 "command-host-gone-true",
481 ]);
482 }).pipe(Effect.provide(layerTestRandom)),
483 );
484​
485 it.effect("Stop with no run left ends the thread's pull request watches", () =>
486 Effect.gen(function* () {
487 const link = {
488 host: "github.com",
489 repository: "pingdotgg/t3code",
490 url: "https://github.com/pingdotgg/t3code/pull/7",
491 source: "agent" as const,
492 linkedAt: "2026-10-05T00:00:00.000Z",
493 snapshot: null,
494 stack: null,
495 };
496 const watch = {
497 startedAt: "2026-10-05T00:00:00.000Z",
498 headSha: null,
499 failedChecks: [],
500 passed: false,
501 passedChecks: [],
502 remarksThrough: "2026-10-05T00:00:00.000Z",
503 remarkIds: [],
504 conflicting: false,
505 wakes: 0,
506 };
507 const projection: OrchestrationV2ThreadProjection = {
508 ...v2Projection,
509 thread: {
510 ...v2Projection.thread,
511 pullRequests: [
512 { ...link, number: 7, watch },
513 { ...link, number: 8 },
514 { ...link, number: 9, source: "stack-dismissed", watch },
515 ],
516 },
517 };
518 const commands: OrchestrationV2Command[] = [];
519 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
520​
521 yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
522 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
523 );
524​
525 expect(commands).toEqual([
526 {
527 type: "thread.pull-request.watch",
528 commandId: expect.any(String),
529 threadId: v2ThreadId,
530 host: "github.com",
531 repository: "pingdotgg/t3code",
532 number: 7,
533 watching: false,
534 },
535 ]);
536 }).pipe(Effect.provide(layerTestRandom)),
537 );
538​
539 it.effect.each(["waiting", "completed", "rolled_back"] as const)(
540 "dispatches Stop for %s runs with background commands except rollback",
541 (status) =>
542 Effect.gen(function* () {
543 const waitingRunId = RunId.make("run-waiting");
544 const projection: OrchestrationV2ThreadProjection = {
545 ...v2Projection,
546 runs: [
547 {
548 id: waitingRunId,
549 threadId: v2ThreadId,
550 ordinal: 1,
551 providerInstanceId: v2Projection.thread.providerInstanceId,
552 modelSelection: v2Projection.thread.modelSelection,
553 providerThreadId: null,
554 userMessageId: MessageId.make("message-waiting"),
555 rootNodeId: null,
556 activeAttemptId: null,
557 status,
558 requestedAt: v2Now,
559 startedAt: v2Now,
560 completedAt: null,
561 checkpointId: null,
562 contextHandoffId: null,
563 },
564 ],
565 turnItems: [
566 {
567 id: TurnItemId.make("background-command"),
568 threadId: v2ThreadId,
569 runId: waitingRunId,
570 nodeId: null,
571 providerThreadId: null,
572 providerTurnId: null,
573 nativeItemRef: null,
574 parentItemId: null,
575 ordinal: 1,
576 status: "running",
577 title: null,
578 startedAt: v2Now,
579 completedAt: null,
580 updatedAt: v2Now,
581 type: "command_execution",
582 input: "vp run dev",
583 },
584 ],
585 };
586 const commands: OrchestrationV2Command[] = [];
587 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
588​
589 const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
590 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
591 );
592​
593 expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
594 expect(commands).toEqual(
595 status === "rolled_back"
596 ? []
597 : [
598 {
599 type: "run.interrupt",
600 commandId: expect.any(String),
601 threadId: v2ThreadId,
602 runId: waitingRunId,
603 holdQueue: true,
604 },
605 ],
606 );
607 }).pipe(Effect.provide(layerTestRandom)),
608 );
609​
610 it.effect(
611 "a native subagent stop targets its owning run rather than holding the parent queue",
612 () =>
613 Effect.gen(function* () {
614 const subagentId = NodeId.make("native-subagent");
615 const runId = RunId.make("settled-owner-run");
616 const commands: OrchestrationV2Command[] = [];
617 const supervisor = yield* makeSupervisor({
618 commands,
619 projects: [],
620 projection: {
621 ...v2Projection,
622 subagents: [
623 {
624 id: subagentId,
625 threadId: v2ThreadId,
626 runId,
627 parentNodeId: NodeId.make("owner-node"),
628 origin: "provider_native",
629 createdBy: "agent",
630 driver: ProviderDriverKind.make("claudeAgent"),
631 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
632 providerThreadId: null,
633 childThreadId: ThreadId.make("native-child-thread"),
634 nativeTaskRef: null,
635 prompt: "Work",
636 title: null,
637 model: null,
638 result: null,
639 status: "running",
640 startedAt: v2Now,
641 completedAt: null,
642 updatedAt: v2Now,
643 },
644 ],
645 },
646 });
647 yield* interruptThreadTurn({
648 commandId: CommandId.make("native-stop"),
649 threadId: v2ThreadId,
650 subagentId,
651 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
652 expect(commands).toEqual([
653 {
654 type: "subagent.stop",
655 commandId: "native-stop",
656 threadId: v2ThreadId,
657 runId,
658 subagentId,
659 },
660 ]);
661 }).pipe(Effect.provide(layerTestRandom)),
662 );
663​
664 it.effect(
665 "an app-owned subagent stop asks the parent to clear an orphan, then stops the child",
666 () =>
667 Effect.gen(function* () {
668 const subagentId = NodeId.make("app-owned-subagent");
669 const runId = RunId.make("parent-run");
670 const childThreadId = ThreadId.make("app-owned-child-thread");
671 const commands: OrchestrationV2Command[] = [];
672 const supervisor = yield* makeSupervisor({
673 commands,
674 projects: [],
675 advertiseThreadStop: true,
676 projection: {
677 ...v2Projection,
678 subagents: [
679 {
680 id: subagentId,
681 threadId: v2ThreadId,
682 runId,
683 parentNodeId: NodeId.make("owner-node"),
684 origin: "app_owned",
685 createdBy: "agent",
686 driver: ProviderDriverKind.make("codex"),
687 providerInstanceId: ProviderInstanceId.make("codex"),
688 providerThreadId: null,
689 childThreadId,
690 nativeTaskRef: null,
691 prompt: "Work",
692 title: null,
693 model: null,
694 result: null,
695 status: "running",
696 startedAt: v2Now,
697 completedAt: null,
698 updatedAt: v2Now,
699 },
700 ],
701 },
702 });
703 yield* interruptThreadTurn({
704 commandId: CommandId.make("lineage-stop"),
705 threadId: v2ThreadId,
706 subagentId,
707 // A parent run must not be interrupted on the child thread.
708 runId,
709 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
710 expect(commands).toEqual([
711 {
712 type: "subagent.stop",
713 commandId: expect.any(String),
714 threadId: v2ThreadId,
715 runId,
716 subagentId,
717 },
718 { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId },
719 ]);
720 }).pipe(Effect.provide(layerTestRandom)),
721 );
722​
723 it.effect("stops a thread without relying on background work in the history window", () =>
724 Effect.gen(function* () {
725 const commands: OrchestrationV2Command[] = [];
726 const projectionRequests: ThreadId[] = [];
727 const supervisor = yield* makeSupervisor({
728 commands,
729 projects: [],
730 projectionRequests,
731 advertiseThreadStop: true,
732 });
733​
734 const result = yield* interruptThreadTurn({
735 commandId: CommandId.make("stop-outside-history-window"),
736 threadId: v2ThreadId,
737 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
738​
739 expect(result).toEqual({ sequence: 1 });
740 expect(projectionRequests).toEqual([]);
741 expect(commands).toEqual([
742 {
743 type: "thread.stop",
744 commandId: "stop-outside-history-window",
745 threadId: v2ThreadId,
746 },
747 ]);
748 }).pipe(Effect.provide(layerTestRandom)),
749 );
750});