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

commands.test.ts

902 lines32.1 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 repositoryScopeId = CheckpointScopeId.make("checkpoint-scope-repository");
189 const checkpointId = CheckpointId.make("checkpoint-thread-start");
190 const projection: OrchestrationV2ThreadProjection = {
191 ...v2Projection,
192 checkpoints: [
193 {
194 id: checkpointId,
195 threadId: v2ThreadId,
196 scopeId,
197 runId: null,
198 nodeId: NodeId.make("node-run-1"),
199 parentCheckpointId: null,
200 ordinalWithinScope: 0,
201 appRunOrdinal: null,
202 ref: CheckpointRef.make("refs/t3/thread-start"),
203 status: "ready",
204 files: [],
205 capturedAt: v2Now,
206 },
207 // A tracked repository's first baseline, recorded after the thread's own.
208 {
209 id: CheckpointId.make("checkpoint-repository-start"),
210 threadId: v2ThreadId,
211 scopeId: repositoryScopeId,
212 runId: null,
213 nodeId: NodeId.make("node-run-1"),
214 parentCheckpointId: null,
215 ordinalWithinScope: 0,
216 appRunOrdinal: null,
217 ref: CheckpointRef.make("refs/t3/repository-start"),
218 status: "ready",
219 files: [],
220 capturedAt: v2Now,
221 },
222 ],
223 checkpointScopes: [
224 {
225 id: repositoryScopeId,
226 threadId: v2ThreadId,
227 runId: null,
228 nodeId: NodeId.make("node-run-1"),
229 parentScopeId: scopeId,
230 providerThreadId: null,
231 kind: "manual",
232 ordinalWithinParent: 1,
233 advancesAppRunCount: false,
234 cwd: "/workspace/api",
235 label: "api",
236 repositoryPath: "/workspace/api",
237 createdAt: v2Now,
238 },
239 ],
240 };
241 const commands: OrchestrationV2Command[] = [];
242 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
243​
244 yield* revertThreadCheckpoint({
245 commandId: CommandId.make("rollback-thread-start"),
246 threadId: v2ThreadId,
247 turnCount: 0,
248 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
249​
250 expect(commands).toEqual([
251 {
252 type: "checkpoint.rollback",
253 commandId: "rollback-thread-start",
254 threadId: v2ThreadId,
255 scopeId,
256 checkpointId,
257 },
258 ]);
259 }).pipe(Effect.provide(layerTestRandom)),
260 );
261​
262 it.effect("preserves an existing worktree and branch during first-message launch", () =>
263 Effect.gen(function* () {
264 const launches: OrchestrationV2ThreadLaunchInput[] = [];
265 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
266​
267 yield* startThreadTurn({
268 commandId: CommandId.make("launch-existing-worktree"),
269 threadId: v2ThreadId,
270 message: {
271 messageId: MessageId.make("message-existing-worktree"),
272 role: "user",
273 text: "Continue here",
274 attachments: [],
275 },
276 runtimeMode: "full-access",
277 interactionMode: "default",
278 titleSeed: "Continue here",
279 bootstrap: {
280 createThread: {
281 projectId: ProjectId.make("project-1"),
282 title: "Thread",
283 modelSelection: v2Projection.thread.modelSelection,
284 runtimeMode: "full-access",
285 interactionMode: "default",
286 branch: "feature",
287 worktreePath: "/workspace/project-worktrees/feature",
288 createdAt: "2026-06-20T00:00:00.000Z",
289 },
290 },
291 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
292​
293 expect(launches[0]).toMatchObject({
294 threadId: v2ThreadId,
295 title: "Continue here",
296 generateTitle: true,
297 workspaceStrategy: {
298 type: "existing_worktree",
299 worktreePath: "/workspace/project-worktrees/feature",
300 branch: "feature",
301 },
302 });
303 }).pipe(Effect.provide(layerTestRandom)),
304 );
305​
306 it.effect("uses server-resolved delivery intent without fetching the full projection", () =>
307 Effect.gen(function* () {
308 const commands: OrchestrationV2Command[] = [];
309 const projectionRequests: ThreadId[] = [];
310 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
311​
312 for (const [mode, expectedType] of [
313 ["queue", "queue_after_active"],
314 ["auto", "start_immediately"],
315 ["steer", "start_immediately"],
316 ["restart", "start_immediately"],
317 ] as const) {
318 yield* startThreadTurn({
319 commandId: CommandId.make(`command-${mode}`),
320 threadId: v2ThreadId,
321 message: {
322 messageId: MessageId.make(`message-${mode}`),
323 role: "user",
324 text: mode,
325 attachments: [],
326 },
327 runtimeMode: "full-access",
328 interactionMode: "default",
329 dispatchMode: mode,
330 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
331​
332 expect(commands.at(-1)).toMatchObject({
333 type: "message.dispatch",
334 dispatchMode: { type: expectedType },
335 ...(mode === "queue" ? {} : { deliveryIntent: mode }),
336 });
337 }
338 expect(projectionRequests).toEqual([]);
339 }).pipe(Effect.provide(layerTestRandom)),
340 );
341​
342 it.effect(
343 "sends fallback text only on empty manual continuations for servers without native resume",
344 () =>
345 Effect.gen(function* () {
346 const commands: OrchestrationV2Command[] = [];
347 const supervisor = yield* makeSupervisor({ commands, projects: [] });
348 const resumedRunId = RunId.make("run-interrupted");
349​
350 yield* startThreadTurn({
351 commandId: CommandId.make("command-resume-empty"),
352 threadId: v2ThreadId,
353 manualContinuationOfRunId: resumedRunId,
354 message: {
355 messageId: MessageId.make("message-resume-empty"),
356 role: "user",
357 text: "",
358 attachments: [],
359 },
360 runtimeMode: "full-access",
361 interactionMode: "default",
362 dispatchMode: "start",
363 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
364​
365 yield* startThreadTurn({
366 commandId: CommandId.make("command-resume-text"),
367 threadId: v2ThreadId,
368 manualContinuationOfRunId: resumedRunId,
369 message: {
370 messageId: MessageId.make("message-resume-text"),
371 role: "user",
372 text: "Keep going",
373 attachments: [],
374 },
375 runtimeMode: "full-access",
376 interactionMode: "default",
377 dispatchMode: "start",
378 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
379​
380 yield* startThreadTurn({
381 commandId: CommandId.make("command-start-empty"),
382 threadId: v2ThreadId,
383 message: {
384 messageId: MessageId.make("message-start-empty"),
385 role: "user",
386 text: "",
387 attachments: [],
388 },
389 runtimeMode: "full-access",
390 interactionMode: "default",
391 dispatchMode: "start",
392 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
393​
394 expect(commands).toEqual([
395 expect.objectContaining({
396 type: "message.dispatch",
397 commandId: "command-resume-empty",
398 threadId: v2ThreadId,
399 manualContinuationOfRunId: resumedRunId,
400 text: "Continue where you left off.",
401 dispatchMode: { type: "start_immediately" },
402 }),
403 expect.objectContaining({
404 type: "message.dispatch",
405 commandId: "command-resume-text",
406 threadId: v2ThreadId,
407 manualContinuationOfRunId: resumedRunId,
408 text: "Keep going",
409 dispatchMode: { type: "start_immediately" },
410 }),
411 expect.objectContaining({
412 type: "message.dispatch",
413 commandId: "command-start-empty",
414 threadId: v2ThreadId,
415 text: "",
416 dispatchMode: { type: "start_immediately" },
417 }),
418 ]);
419 }).pipe(Effect.provide(layerTestRandom)),
420 );
421​
422 // A dead socket reaches the caller as a protocol error, or as an interrupt when
423 // the supervisor closes the session before the protocol reports the error.
424 it.effect.each([
425 [
426 "protocol error",
427 new RpcClientError.RpcClientError({
428 reason: new RpcClientError.RpcClientDefect({
429 message: "socket closed",
430 cause: new Error("socket closed"),
431 }),
432 }),
433 ],
434 ["session close", Effect.failCause(Cause.interrupt())],
435 ] as const)("retries a message dispatch lost to a %s with the same command id", ([, loss]) =>
436 Effect.gen(function* () {
437 const commands: OrchestrationV2Command[] = [];
438 const supervisor = yield* makeSupervisor({ commands, projects: [] });
439 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
440 const firstAttemptLost = yield* Deferred.make<void>();
441 const lostClient = {
442 ...healthySession.client,
443 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
444 Effect.gen(function* () {
445 commands.push(command);
446 yield* SubscriptionRef.set(supervisor.session, Option.none());
447 yield* Deferred.succeed(firstAttemptLost, undefined);
448 return yield* loss;
449 }),
450 } as unknown as WsRpcProtocolClient;
451 yield* SubscriptionRef.set(
452 supervisor.session,
453 Option.some({ ...healthySession, client: lostClient }),
454 );
455​
456 const sendFiber = yield* startThreadTurn({
457 commandId: CommandId.make("command-lost-ack"),
458 threadId: v2ThreadId,
459 message: {
460 messageId: MessageId.make("message-lost-ack"),
461 role: "user",
462 text: "hello",
463 attachments: [],
464 },
465 runtimeMode: "full-access",
466 interactionMode: "default",
467 }).pipe(
468 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
469 Effect.forkChild,
470 );
471 yield* Deferred.await(firstAttemptLost);
472 yield* SubscriptionRef.set(supervisor.session, Option.some(healthySession));
473 const exit = yield* Fiber.await(sendFiber);
474​
475 expect(commands.map((command) => [command.type, command.commandId])).toEqual([
476 ["message.dispatch", "command-lost-ack"],
477 ["message.dispatch", "command-lost-ack"],
478 ]);
479 expect(Exit.isSuccess(exit)).toBe(true);
480 }).pipe(Effect.provide(layerTestRandom)),
481 );
482​
483 it.effect("stops resending a message whose dispatch keeps losing the socket", () =>
484 Effect.gen(function* () {
485 const commands: OrchestrationV2Command[] = [];
486 const supervisor = yield* makeSupervisor({ commands, projects: [] });
487 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
488 const dyingClient: WsRpcProtocolClient = {
489 ...healthySession.client,
490 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
491 Effect.gen(function* () {
492 commands.push(command);
493 yield* SubscriptionRef.set(
494 supervisor.session,
495 Option.some({ ...healthySession, client: dyingClient }),
496 );
497 return yield* new RpcClientError.RpcClientError({
498 reason: new RpcClientError.RpcClientDefect({
499 message: "socket closed",
500 cause: new Error("socket closed"),
501 }),
502 });
503 }),
504 } as unknown as WsRpcProtocolClient;
505 yield* SubscriptionRef.set(
506 supervisor.session,
507 Option.some({ ...healthySession, client: dyingClient }),
508 );
509​
510 const error = yield* startThreadTurn({
511 commandId: CommandId.make("command-socket-killer"),
512 threadId: v2ThreadId,
513 message: {
514 messageId: MessageId.make("message-socket-killer"),
515 role: "user",
516 text: "hello",
517 attachments: [],
518 },
519 runtimeMode: "full-access",
520 interactionMode: "default",
521 }).pipe(
522 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
523 Effect.flip,
524 );
525​
526 expect(commands.map((command) => command.commandId)).toEqual([
527 "command-socket-killer",
528 "command-socket-killer",
529 "command-socket-killer",
530 ]);
531 expect(error._tag).toBe("RpcClientError");
532 }).pipe(Effect.provide(layerTestRandom)),
533 );
534​
535 it.effect("fails a message dispatch the host never answers on a live socket", () =>
536 Effect.gen(function* () {
537 const commands: OrchestrationV2Command[] = [];
538 const supervisor = yield* makeSupervisor({ commands, projects: [] });
539 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
540 const silentClient = {
541 ...healthySession.client,
542 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
543 Effect.sync(() => commands.push(command)).pipe(Effect.andThen(Effect.never)),
544 } as unknown as WsRpcProtocolClient;
545 yield* SubscriptionRef.set(
546 supervisor.session,
547 Option.some({ ...healthySession, client: silentClient }),
548 );
549​
550 const sendFiber = yield* startThreadTurn({
551 commandId: CommandId.make("command-unanswered"),
552 threadId: v2ThreadId,
553 message: {
554 messageId: MessageId.make("message-unanswered"),
555 role: "user",
556 text: "hello",
557 attachments: [],
558 },
559 runtimeMode: "full-access",
560 interactionMode: "default",
561 }).pipe(
562 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
563 Effect.flip,
564 Effect.forkChild,
565 );
566 yield* TestClock.adjust("1 minute");
567​
568 expect(sendFiber.pollUnsafe()).toBeDefined();
569 expect((yield* Fiber.join(sendFiber))._tag).toBe("EnvironmentRpcUnavailableError");
570 expect(commands.map((command) => command.commandId)).toEqual(["command-unanswered"]);
571 }).pipe(Effect.provide(layerTestRandom)),
572 );
573​
574 it.effect("holds a lost message through reconnect backoff until disconnect", () =>
575 Effect.gen(function* () {
576 const commands: OrchestrationV2Command[] = [];
577 const supervisor = yield* makeSupervisor({ commands, projects: [] });
578 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
579 const lostClient = {
580 ...healthySession.client,
581 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
582 Effect.gen(function* () {
583 commands.push(command);
584 yield* SubscriptionRef.set(supervisor.session, Option.none());
585 return yield* new RpcClientError.RpcClientError({
586 reason: new RpcClientError.RpcClientDefect({
587 message: "socket closed",
588 cause: new Error("socket closed"),
589 }),
590 });
591 }),
592 } as unknown as WsRpcProtocolClient;
593 const send = (resendAfterSocketLoss: boolean) =>
594 Effect.gen(function* () {
595 yield* SubscriptionRef.set(
596 supervisor.session,
597 Option.some({ ...healthySession, client: lostClient }),
598 );
599 return yield* startThreadTurn({
600 commandId: CommandId.make(`command-host-gone-${resendAfterSocketLoss}`),
601 threadId: v2ThreadId,
602 message: {
603 messageId: MessageId.make(`message-host-gone-${resendAfterSocketLoss}`),
604 role: "user",
605 text: "hello",
606 attachments: [],
607 },
608 runtimeMode: "full-access",
609 interactionMode: "default",
610 resendAfterSocketLoss,
611 }).pipe(
612 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
613 Effect.flip,
614 Effect.forkChild,
615 );
616 });
617​
618 const optedOut = yield* send(false);
619 expect((yield* Fiber.join(optedOut))._tag).toBe("RpcClientError");
620​
621 const waiting = yield* send(true);
622 yield* SubscriptionRef.set(supervisor.state, {
623 ...CONNECTED_STATE,
624 phase: "backoff" as const,
625 });
626 yield* TestClock.adjust("2 minutes");
627 expect(waiting.pollUnsafe()).toBeUndefined();
628 yield* SubscriptionRef.set(supervisor.state, AVAILABLE_CONNECTION_STATE);
629 expect((yield* Fiber.join(waiting))._tag).toBe("RpcClientError");
630 expect(commands.map((command) => command.commandId)).toEqual([
631 "command-host-gone-false",
632 "command-host-gone-true",
633 ]);
634 }).pipe(Effect.provide(layerTestRandom)),
635 );
636​
637 it.effect("Stop with no run left ends the thread's pull request watches", () =>
638 Effect.gen(function* () {
639 const link = {
640 host: "github.com",
641 repository: "pingdotgg/t3code",
642 url: "https://github.com/pingdotgg/t3code/pull/7",
643 source: "agent" as const,
644 linkedAt: "2026-10-05T00:00:00.000Z",
645 snapshot: null,
646 stack: null,
647 };
648 const watch = {
649 startedAt: "2026-10-05T00:00:00.000Z",
650 headSha: null,
651 failedChecks: [],
652 passed: false,
653 passedChecks: [],
654 remarksThrough: "2026-10-05T00:00:00.000Z",
655 remarkIds: [],
656 conflicting: false,
657 wakes: 0,
658 };
659 const projection: OrchestrationV2ThreadProjection = {
660 ...v2Projection,
661 thread: {
662 ...v2Projection.thread,
663 pullRequests: [
664 { ...link, number: 7, watch },
665 { ...link, number: 8 },
666 { ...link, number: 9, source: "stack-dismissed", watch },
667 ],
668 },
669 };
670 const commands: OrchestrationV2Command[] = [];
671 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
672​
673 yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
674 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
675 );
676​
677 expect(commands).toEqual([
678 {
679 type: "thread.pull-request.watch",
680 commandId: expect.any(String),
681 threadId: v2ThreadId,
682 host: "github.com",
683 repository: "pingdotgg/t3code",
684 number: 7,
685 watching: false,
686 },
687 ]);
688 }).pipe(Effect.provide(layerTestRandom)),
689 );
690​
691 it.effect.each(["waiting", "completed", "rolled_back"] as const)(
692 "dispatches Stop for %s runs with background commands except rollback",
693 (status) =>
694 Effect.gen(function* () {
695 const waitingRunId = RunId.make("run-waiting");
696 const projection: OrchestrationV2ThreadProjection = {
697 ...v2Projection,
698 runs: [
699 {
700 id: waitingRunId,
701 threadId: v2ThreadId,
702 ordinal: 1,
703 providerInstanceId: v2Projection.thread.providerInstanceId,
704 modelSelection: v2Projection.thread.modelSelection,
705 providerThreadId: null,
706 userMessageId: MessageId.make("message-waiting"),
707 rootNodeId: null,
708 activeAttemptId: null,
709 status,
710 requestedAt: v2Now,
711 startedAt: v2Now,
712 completedAt: null,
713 checkpointId: null,
714 contextHandoffId: null,
715 },
716 ],
717 turnItems: [
718 {
719 id: TurnItemId.make("background-command"),
720 threadId: v2ThreadId,
721 runId: waitingRunId,
722 nodeId: null,
723 providerThreadId: null,
724 providerTurnId: null,
725 nativeItemRef: null,
726 parentItemId: null,
727 ordinal: 1,
728 status: "running",
729 title: null,
730 startedAt: v2Now,
731 completedAt: null,
732 updatedAt: v2Now,
733 type: "command_execution",
734 input: "vp run dev",
735 },
736 ],
737 };
738 const commands: OrchestrationV2Command[] = [];
739 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
740​
741 const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
742 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
743 );
744​
745 expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
746 expect(commands).toEqual(
747 status === "rolled_back"
748 ? []
749 : [
750 {
751 type: "run.interrupt",
752 commandId: expect.any(String),
753 threadId: v2ThreadId,
754 runId: waitingRunId,
755 holdQueue: true,
756 },
757 ],
758 );
759 }).pipe(Effect.provide(layerTestRandom)),
760 );
761​
762 it.effect(
763 "a native subagent stop targets its owning run rather than holding the parent queue",
764 () =>
765 Effect.gen(function* () {
766 const subagentId = NodeId.make("native-subagent");
767 const runId = RunId.make("settled-owner-run");
768 const commands: OrchestrationV2Command[] = [];
769 const supervisor = yield* makeSupervisor({
770 commands,
771 projects: [],
772 projection: {
773 ...v2Projection,
774 subagents: [
775 {
776 id: subagentId,
777 threadId: v2ThreadId,
778 runId,
779 parentNodeId: NodeId.make("owner-node"),
780 origin: "provider_native",
781 createdBy: "agent",
782 driver: ProviderDriverKind.make("claudeAgent"),
783 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
784 providerThreadId: null,
785 childThreadId: ThreadId.make("native-child-thread"),
786 nativeTaskRef: null,
787 prompt: "Work",
788 title: null,
789 model: null,
790 result: null,
791 status: "running",
792 startedAt: v2Now,
793 completedAt: null,
794 updatedAt: v2Now,
795 },
796 ],
797 },
798 });
799 yield* interruptThreadTurn({
800 commandId: CommandId.make("native-stop"),
801 threadId: v2ThreadId,
802 subagentId,
803 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
804 expect(commands).toEqual([
805 {
806 type: "subagent.stop",
807 commandId: "native-stop",
808 threadId: v2ThreadId,
809 runId,
810 subagentId,
811 },
812 ]);
813 }).pipe(Effect.provide(layerTestRandom)),
814 );
815​
816 it.effect(
817 "an app-owned subagent stop asks the parent to clear an orphan, then stops the child",
818 () =>
819 Effect.gen(function* () {
820 const subagentId = NodeId.make("app-owned-subagent");
821 const runId = RunId.make("parent-run");
822 const childThreadId = ThreadId.make("app-owned-child-thread");
823 const commands: OrchestrationV2Command[] = [];
824 const supervisor = yield* makeSupervisor({
825 commands,
826 projects: [],
827 advertiseThreadStop: true,
828 projection: {
829 ...v2Projection,
830 subagents: [
831 {
832 id: subagentId,
833 threadId: v2ThreadId,
834 runId,
835 parentNodeId: NodeId.make("owner-node"),
836 origin: "app_owned",
837 createdBy: "agent",
838 driver: ProviderDriverKind.make("codex"),
839 providerInstanceId: ProviderInstanceId.make("codex"),
840 providerThreadId: null,
841 childThreadId,
842 nativeTaskRef: null,
843 prompt: "Work",
844 title: null,
845 model: null,
846 result: null,
847 status: "running",
848 startedAt: v2Now,
849 completedAt: null,
850 updatedAt: v2Now,
851 },
852 ],
853 },
854 });
855 yield* interruptThreadTurn({
856 commandId: CommandId.make("lineage-stop"),
857 threadId: v2ThreadId,
858 subagentId,
859 // A parent run must not be interrupted on the child thread.
860 runId,
861 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
862 expect(commands).toEqual([
863 {
864 type: "subagent.stop",
865 commandId: expect.any(String),
866 threadId: v2ThreadId,
867 runId,
868 subagentId,
869 },
870 { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId },
871 ]);
872 }).pipe(Effect.provide(layerTestRandom)),
873 );
874​
875 it.effect("stops a thread without relying on background work in the history window", () =>
876 Effect.gen(function* () {
877 const commands: OrchestrationV2Command[] = [];
878 const projectionRequests: ThreadId[] = [];
879 const supervisor = yield* makeSupervisor({
880 commands,
881 projects: [],
882 projectionRequests,
883 advertiseThreadStop: true,
884 });
885​
886 const result = yield* interruptThreadTurn({
887 commandId: CommandId.make("stop-outside-history-window"),
888 threadId: v2ThreadId,
889 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
890​
891 expect(result).toEqual({ sequence: 1 });
892 expect(projectionRequests).toEqual([]);
893 expect(commands).toEqual([
894 {
895 type: "thread.stop",
896 commandId: "stop-outside-history-window",
897 threadId: v2ThreadId,
898 },
899 ]);
900 }).pipe(Effect.provide(layerTestRandom)),
901 );
902});