Open History to see the last commit
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 { assert, 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 Schema from "effect/Schema";
32import * as SubscriptionRef from "effect/SubscriptionRef";
33import * as TestClock from "effect/testing/TestClock";
34import { RpcClientError } from "effect/rpc";
35
36import {
37 AVAILABLE_CONNECTION_STATE,
38 PrimaryConnectionTarget,
39 type PreparedConnection,
40 type SupervisorConnectionState,
41} from "../connection/model.ts";
42import * as EnvironmentSupervisor from "../connection/supervisor.ts";
43import { isLostTransportCause } from "../rpc/client.ts";
44import * as RpcSession from "../rpc/session.ts";
45import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
46import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
47import {
48 archiveThread,
49 forkSideChat,
50 interruptThreadTurn,
51 promoteQueuedRun,
52 revertThreadCheckpoint,
53 resumeThreadQueue,
54 startThreadTurn,
55} from "./commands.ts";
56
57const layerTestRandom = Layer.succeed(
58 SecureRandom.SecureRandom,
59 SecureRandom.make((size) => new Uint8Array(size)),
60);
61
62class Refused extends Schema.TaggedError<Refused>()("Refused", {}) {}
63
64const TARGET = new PrimaryConnectionTarget({
65 environmentId: EnvironmentId.make("environment-1"),
66 label: "Test environment",
67 httpBaseUrl: "https://environment.example.test",
68 wsBaseUrl: "wss://environment.example.test",
69});
70
71const CONNECTED_STATE: SupervisorConnectionState = {
72 ...AVAILABLE_CONNECTION_STATE,
73 desired: true,
74 phase: "connected",
75};
76
77const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
78 readonly commands: OrchestrationV2Command[];
79 readonly projects: ProjectMutation[];
80 readonly launches?: OrchestrationV2ThreadLaunchInput[];
81 readonly projection?: OrchestrationV2ThreadProjection;
82 readonly projectionRequests?: ThreadId[];
83 readonly advertiseThreadStop?: boolean;
84}) {
85 const client = {
86 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
87 Effect.sync(() => {
88 input.commands.push(command);
89 return { sequence: input.commands.length };
90 }),
91 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (requestInput: {
92 readonly threadId: ThreadId;
93 }) =>
94 Effect.sync(() => {
95 input.projectionRequests?.push(requestInput.threadId);
96 return input.projection ?? v2Projection;
97 }),
98 [ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) =>
99 Effect.sync(() => {
100 input.launches?.push(launchInput);
101 return {
102 threadId: launchInput.threadId ?? v2ThreadId,
103 projection: input.projection ?? v2Projection,
104 resumed: false,
105 };
106 }),
107 [WS_METHODS.projectsMutate]: (mutation: ProjectMutation) =>
108 Effect.sync(() => {
109 input.projects.push(mutation);
110 return {
111 id: mutation.projectId,
112 title: mutation.type === "project.create" ? mutation.title : "Project",
113 workspaceRoot:
114 mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project",
115 repositoryIdentity: null,
116 faviconPath: null,
117 defaultModelSelection: null,
118 scripts: [],
119 createdAt: "2026-06-06T00:00:00.000Z",
120 updatedAt: "2026-06-06T00:00:00.000Z",
121 deletedAt: null,
122 };
123 }),
124 } as unknown as WsRpcProtocolClient;
125 const session: RpcSession.RpcSession = {
126 client,
127 initialConfig: Effect.succeed({
128 environment: {
129 capabilities: {
130 repositoryIdentity: true,
131 ...(input.advertiseThreadStop === true ? { threadStop: true } : {}),
132 },
133 },
134 } as never),
135 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
136 ready: Effect.void,
137 probe: Effect.void,
138 inboundFrames: Effect.succeed(0),
139 awaitingReply: Effect.succeed(false),
140 closed: Effect.never,
141 };
142 return EnvironmentSupervisor.EnvironmentSupervisor.of({
143 target: TARGET,
144 state: yield* SubscriptionRef.make(CONNECTED_STATE),
145 session: yield* SubscriptionRef.make(Option.some(session)),
146 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
147 connect: Effect.void,
148 disconnect: Effect.void,
149 retryNow: Effect.void,
150 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
151});
152
153describe("V2 environment commands", () => {
154 it.effect("distinguishes sending a selected queued message from resuming queue order", () =>
155 Effect.gen(function* () {
156 const commands: OrchestrationV2Command[] = [];
157 const supervisor = yield* makeSupervisor({ commands, projects: [] });
158 const threadId = ThreadId.make("thread-1");
159 yield* resumeThreadQueue({
160 commandId: CommandId.make("send-selected"),
161 threadId,
162 runId: RunId.make("selected"),
163 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
164 yield* resumeThreadQueue({
165 commandId: CommandId.make("resume-queue"),
166 threadId,
167 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
168
169 expect(commands).toEqual([
170 { type: "queued-run.start", commandId: "send-selected", threadId, runId: "selected" },
171 { type: "queue.resume", commandId: "resume-queue", threadId },
172 ]);
173 }).pipe(Effect.provide(layerTestRandom)),
174 );
175
176 it.effect("preserves caller command ids for idempotent V2 commands", () =>
177 Effect.gen(function* () {
178 const commands: OrchestrationV2Command[] = [];
179 const supervisor = yield* makeSupervisor({ commands, projects: [] });
180
181 yield* archiveThread({
182 commandId: CommandId.make("queued-command"),
183 threadId: ThreadId.make("thread-1"),
184 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
185
186 expect(commands).toEqual([
187 { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
188 ]);
189 }).pipe(Effect.provide(layerTestRandom)),
190 );
191
192 it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () =>
193 Effect.gen(function* () {
194 const scopeId = CheckpointScopeId.make("checkpoint-scope-root");
195 const repositoryScopeId = CheckpointScopeId.make("checkpoint-scope-repository");
196 const checkpointId = CheckpointId.make("checkpoint-thread-start");
197 const projection: OrchestrationV2ThreadProjection = {
198 ...v2Projection,
199 checkpoints: [
200 {
201 id: checkpointId,
202 threadId: v2ThreadId,
203 scopeId,
204 runId: null,
205 nodeId: NodeId.make("node-run-1"),
206 parentCheckpointId: null,
207 ordinalWithinScope: 0,
208 appRunOrdinal: null,
209 ref: CheckpointRef.make("refs/t3/thread-start"),
210 status: "ready",
211 files: [],
212 capturedAt: v2Now,
213 },
214 // A tracked repository's first baseline, recorded after the thread's own.
215 {
216 id: CheckpointId.make("checkpoint-repository-start"),
217 threadId: v2ThreadId,
218 scopeId: repositoryScopeId,
219 runId: null,
220 nodeId: NodeId.make("node-run-1"),
221 parentCheckpointId: null,
222 ordinalWithinScope: 0,
223 appRunOrdinal: null,
224 ref: CheckpointRef.make("refs/t3/repository-start"),
225 status: "ready",
226 files: [],
227 capturedAt: v2Now,
228 },
229 ],
230 checkpointScopes: [
231 {
232 id: repositoryScopeId,
233 threadId: v2ThreadId,
234 runId: null,
235 nodeId: NodeId.make("node-run-1"),
236 parentScopeId: scopeId,
237 providerThreadId: null,
238 kind: "manual",
239 ordinalWithinParent: 1,
240 advancesAppRunCount: false,
241 cwd: "/workspace/api",
242 label: "api",
243 repositoryPath: "/workspace/api",
244 createdAt: v2Now,
245 },
246 ],
247 };
248 const commands: OrchestrationV2Command[] = [];
249 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
250
251 yield* revertThreadCheckpoint({
252 commandId: CommandId.make("rollback-thread-start"),
253 threadId: v2ThreadId,
254 turnCount: 0,
255 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
256
257 expect(commands).toEqual([
258 {
259 type: "checkpoint.rollback",
260 commandId: "rollback-thread-start",
261 threadId: v2ThreadId,
262 scopeId,
263 checkpointId,
264 },
265 ]);
266 }).pipe(Effect.provide(layerTestRandom)),
267 );
268
269 it.effect("preserves an existing worktree and branch during first-message launch", () =>
270 Effect.gen(function* () {
271 const launches: OrchestrationV2ThreadLaunchInput[] = [];
272 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
273
274 yield* startThreadTurn({
275 commandId: CommandId.make("launch-existing-worktree"),
276 threadId: v2ThreadId,
277 message: {
278 messageId: MessageId.make("message-existing-worktree"),
279 role: "user",
280 text: "Continue here",
281 attachments: [],
282 },
283 runtimeMode: "full-access",
284 interactionMode: "default",
285 titleSeed: "Continue here",
286 bootstrap: {
287 createThread: {
288 projectId: ProjectId.make("project-1"),
289 title: "Thread",
290 modelSelection: v2Projection.thread.modelSelection,
291 runtimeMode: "full-access",
292 interactionMode: "default",
293 branch: "feature",
294 worktreePath: "/workspace/project-worktrees/feature",
295 createdAt: "2026-06-20T00:00:00.000Z",
296 },
297 },
298 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
299
300 expect(launches[0]).toMatchObject({
301 threadId: v2ThreadId,
302 title: "Continue here",
303 generateTitle: true,
304 workspaceStrategy: {
305 type: "existing_worktree",
306 worktreePath: "/workspace/project-worktrees/feature",
307 branch: "feature",
308 },
309 });
310 }).pipe(Effect.provide(layerTestRandom)),
311 );
312
313 it.effect("sends title seed and delivery intent without fetching the full projection", () =>
314 Effect.gen(function* () {
315 const commands: OrchestrationV2Command[] = [];
316 const projectionRequests: ThreadId[] = [];
317 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
318
319 for (const [mode, expectedType] of [
320 ["start", "start_immediately"],
321 ["queue", "queue_after_active"],
322 ["auto", "start_immediately"],
323 ["steer", "start_immediately"],
324 ["restart", "start_immediately"],
325 ] as const) {
326 yield* startThreadTurn({
327 commandId: CommandId.make(`command-${mode}`),
328 threadId: v2ThreadId,
329 message: {
330 messageId: MessageId.make(`message-${mode}`),
331 role: "user",
332 text: mode,
333 attachments: [],
334 },
335 runtimeMode: "full-access",
336 interactionMode: "default",
337 titleSeed: mode,
338 dispatchMode: mode,
339 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
340
341 expect(commands.at(-1)).toMatchObject({
342 type: "message.dispatch",
343 titleSeed: mode,
344 dispatchMode: { type: expectedType },
345 ...(mode === "queue" || mode === "start" ? {} : { deliveryIntent: mode }),
346 });
347 }
348 expect(projectionRequests).toEqual([]);
349 }).pipe(Effect.provide(layerTestRandom)),
350 );
351
352 it.effect(
353 "sends fallback text only on empty manual continuations for servers without native resume",
354 () =>
355 Effect.gen(function* () {
356 const commands: OrchestrationV2Command[] = [];
357 const supervisor = yield* makeSupervisor({ commands, projects: [] });
358 const resumedRunId = RunId.make("run-interrupted");
359
360 yield* startThreadTurn({
361 commandId: CommandId.make("command-resume-empty"),
362 threadId: v2ThreadId,
363 manualContinuationOfRunId: resumedRunId,
364 message: {
365 messageId: MessageId.make("message-resume-empty"),
366 role: "user",
367 text: "",
368 attachments: [],
369 },
370 runtimeMode: "full-access",
371 interactionMode: "default",
372 dispatchMode: "start",
373 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
374
375 yield* startThreadTurn({
376 commandId: CommandId.make("command-resume-text"),
377 threadId: v2ThreadId,
378 manualContinuationOfRunId: resumedRunId,
379 message: {
380 messageId: MessageId.make("message-resume-text"),
381 role: "user",
382 text: "Keep going",
383 attachments: [],
384 },
385 runtimeMode: "full-access",
386 interactionMode: "default",
387 dispatchMode: "start",
388 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
389
390 yield* startThreadTurn({
391 commandId: CommandId.make("command-start-empty"),
392 threadId: v2ThreadId,
393 message: {
394 messageId: MessageId.make("message-start-empty"),
395 role: "user",
396 text: "",
397 attachments: [],
398 },
399 runtimeMode: "full-access",
400 interactionMode: "default",
401 dispatchMode: "start",
402 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
403
404 expect(commands).toEqual([
405 expect.objectContaining({
406 type: "message.dispatch",
407 commandId: "command-resume-empty",
408 threadId: v2ThreadId,
409 manualContinuationOfRunId: resumedRunId,
410 text: "Continue where you left off.",
411 dispatchMode: { type: "start_immediately" },
412 }),
413 expect.objectContaining({
414 type: "message.dispatch",
415 commandId: "command-resume-text",
416 threadId: v2ThreadId,
417 manualContinuationOfRunId: resumedRunId,
418 text: "Keep going",
419 dispatchMode: { type: "start_immediately" },
420 }),
421 expect.objectContaining({
422 type: "message.dispatch",
423 commandId: "command-start-empty",
424 threadId: v2ThreadId,
425 text: "",
426 dispatchMode: { type: "start_immediately" },
427 }),
428 ]);
429 }).pipe(Effect.provide(layerTestRandom)),
430 );
431
432 // A dead socket reaches the caller as a protocol error, or as an interrupt when
433 // the supervisor closes the session before the protocol reports the error.
434 it.effect.each([
435 [
436 "protocol error",
437 new RpcClientError.RpcClientError({
438 reason: new RpcClientError.RpcClientDefect({
439 message: "socket closed",
440 cause: new Error("socket closed"),
441 }),
442 }),
443 ],
444 ["session close", Effect.failCause(Cause.interrupt())],
445 ] as const)("retries a message dispatch lost to a %s with the same command id", ([, loss]) =>
446 Effect.gen(function* () {
447 const commands: OrchestrationV2Command[] = [];
448 const supervisor = yield* makeSupervisor({ commands, projects: [] });
449 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
450 const firstAttemptLost = yield* Deferred.make<void>();
451 const lostClient = {
452 ...healthySession.client,
453 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
454 Effect.gen(function* () {
455 commands.push(command);
456 yield* SubscriptionRef.set(supervisor.session, Option.none());
457 yield* Deferred.succeed(firstAttemptLost, undefined);
458 return yield* loss;
459 }),
460 } as unknown as WsRpcProtocolClient;
461 yield* SubscriptionRef.set(
462 supervisor.session,
463 Option.some({ ...healthySession, client: lostClient }),
464 );
465
466 const sendFiber = yield* startThreadTurn({
467 commandId: CommandId.make("command-lost-ack"),
468 threadId: v2ThreadId,
469 message: {
470 messageId: MessageId.make("message-lost-ack"),
471 role: "user",
472 text: "hello",
473 attachments: [],
474 },
475 runtimeMode: "full-access",
476 interactionMode: "default",
477 }).pipe(
478 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
479 Effect.forkChild,
480 );
481 yield* Deferred.await(firstAttemptLost);
482 yield* SubscriptionRef.set(supervisor.session, Option.some(healthySession));
483 const exit = yield* Fiber.await(sendFiber);
484
485 expect(commands.map((command) => [command.type, command.commandId])).toEqual([
486 ["message.dispatch", "command-lost-ack"],
487 ["message.dispatch", "command-lost-ack"],
488 ]);
489 expect(Exit.isSuccess(exit)).toBe(true);
490 }).pipe(Effect.provide(layerTestRandom)),
491 );
492
493 it.effect("stops resending a message whose dispatch keeps losing the socket", () =>
494 Effect.gen(function* () {
495 const commands: OrchestrationV2Command[] = [];
496 const supervisor = yield* makeSupervisor({ commands, projects: [] });
497 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
498 const dyingClient: WsRpcProtocolClient = {
499 ...healthySession.client,
500 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
501 Effect.gen(function* () {
502 commands.push(command);
503 yield* SubscriptionRef.set(
504 supervisor.session,
505 Option.some({ ...healthySession, client: dyingClient }),
506 );
507 return yield* new RpcClientError.RpcClientError({
508 reason: new RpcClientError.RpcClientDefect({
509 message: "socket closed",
510 cause: new Error("socket closed"),
511 }),
512 });
513 }),
514 } as unknown as WsRpcProtocolClient;
515 yield* SubscriptionRef.set(
516 supervisor.session,
517 Option.some({ ...healthySession, client: dyingClient }),
518 );
519
520 const exit = yield* startThreadTurn({
521 commandId: CommandId.make("command-socket-killer"),
522 threadId: v2ThreadId,
523 message: {
524 messageId: MessageId.make("message-socket-killer"),
525 role: "user",
526 text: "hello",
527 attachments: [],
528 },
529 runtimeMode: "full-access",
530 interactionMode: "default",
531 }).pipe(
532 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
533 Effect.exit,
534 );
535
536 expect(commands.map((command) => command.commandId)).toEqual([
537 "command-socket-killer",
538 "command-socket-killer",
539 "command-socket-killer",
540 ]);
541 assert(Exit.isFailure(exit));
542 expect(Cause.squash(exit.cause)).toMatchObject({ _tag: "RpcClientError" });
543 // Callers keep the command id to resend it later rather than issuing a new command.
544 expect(isLostTransportCause(exit.cause)).toBe(true);
545 }).pipe(Effect.provide(layerTestRandom)),
546 );
547
548 it.effect("fails a message dispatch the host never answers on a live socket", () =>
549 Effect.gen(function* () {
550 const commands: OrchestrationV2Command[] = [];
551 const supervisor = yield* makeSupervisor({ commands, projects: [] });
552 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
553 const silentClient = {
554 ...healthySession.client,
555 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
556 Effect.sync(() => commands.push(command)).pipe(Effect.andThen(Effect.never)),
557 } as unknown as WsRpcProtocolClient;
558 yield* SubscriptionRef.set(
559 supervisor.session,
560 Option.some({ ...healthySession, client: silentClient }),
561 );
562
563 const sendFiber = yield* startThreadTurn({
564 commandId: CommandId.make("command-unanswered"),
565 threadId: v2ThreadId,
566 message: {
567 messageId: MessageId.make("message-unanswered"),
568 role: "user",
569 text: "hello",
570 attachments: [],
571 },
572 runtimeMode: "full-access",
573 interactionMode: "default",
574 }).pipe(
575 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
576 Effect.flip,
577 Effect.forkChild,
578 );
579 yield* TestClock.adjust("1 minute");
580
581 expect(sendFiber.pollUnsafe()).toBeDefined();
582 expect((yield* Fiber.join(sendFiber))._tag).toBe("EnvironmentRpcUnavailableError");
583 expect(commands.map((command) => command.commandId)).toEqual(["command-unanswered"]);
584 }).pipe(Effect.provide(layerTestRandom)),
585 );
586
587 it.effect("holds a lost message through reconnect backoff until disconnect", () =>
588 Effect.gen(function* () {
589 const commands: OrchestrationV2Command[] = [];
590 const supervisor = yield* makeSupervisor({ commands, projects: [] });
591 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
592 const lostClient = {
593 ...healthySession.client,
594 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
595 Effect.gen(function* () {
596 commands.push(command);
597 yield* SubscriptionRef.set(supervisor.session, Option.none());
598 return yield* new RpcClientError.RpcClientError({
599 reason: new RpcClientError.RpcClientDefect({
600 message: "socket closed",
601 cause: new Error("socket closed"),
602 }),
603 });
604 }),
605 } as unknown as WsRpcProtocolClient;
606 const send = (resendAfterSocketLoss: boolean) =>
607 Effect.gen(function* () {
608 yield* SubscriptionRef.set(
609 supervisor.session,
610 Option.some({ ...healthySession, client: lostClient }),
611 );
612 return yield* startThreadTurn({
613 commandId: CommandId.make(`command-host-gone-${resendAfterSocketLoss}`),
614 threadId: v2ThreadId,
615 message: {
616 messageId: MessageId.make(`message-host-gone-${resendAfterSocketLoss}`),
617 role: "user",
618 text: "hello",
619 attachments: [],
620 },
621 runtimeMode: "full-access",
622 interactionMode: "default",
623 resendAfterSocketLoss,
624 }).pipe(
625 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
626 Effect.flip,
627 Effect.forkChild,
628 );
629 });
630
631 const optedOut = yield* send(false);
632 expect((yield* Fiber.join(optedOut))._tag).toBe("RpcClientError");
633
634 const waiting = yield* send(true);
635 yield* SubscriptionRef.set(supervisor.state, {
636 ...CONNECTED_STATE,
637 phase: "backoff" as const,
638 });
639 yield* TestClock.adjust("2 minutes");
640 expect(waiting.pollUnsafe()).toBeUndefined();
641 yield* SubscriptionRef.set(supervisor.state, AVAILABLE_CONNECTION_STATE);
642 expect((yield* Fiber.join(waiting))._tag).toBe("RpcClientError");
643 expect(commands.map((command) => command.commandId)).toEqual([
644 "command-host-gone-false",
645 "command-host-gone-true",
646 ]);
647 }).pipe(Effect.provide(layerTestRandom)),
648 );
649
650 const turnSends = [
651 {
652 name: "new thread's first message",
653 method: ORCHESTRATION_V2_WS_METHODS.launchThread,
654 send: (commandId: CommandId) =>
655 startThreadTurn({
656 commandId,
657 threadId: v2ThreadId,
658 message: {
659 messageId: MessageId.make(commandId),
660 role: "user",
661 text: "hi",
662 attachments: [],
663 },
664 runtimeMode: "full-access",
665 interactionMode: "default",
666 bootstrap: {
667 createThread: {
668 projectId: ProjectId.make("project-1"),
669 title: "Thread",
670 modelSelection: v2Projection.thread.modelSelection,
671 runtimeMode: "full-access",
672 interactionMode: "default",
673 branch: null,
674 worktreePath: null,
675 createdAt: "2026-06-20T00:00:00.000Z",
676 },
677 },
678 }),
679 },
680 {
681 name: "queued message sent now",
682 method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
683 send: (commandId: CommandId) =>
684 resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }),
685 },
686 {
687 name: "side chat fork",
688 method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
689 send: (commandId: CommandId) =>
690 forkSideChat({
691 commandId,
692 sourceThreadId: v2ThreadId,
693 targetThreadId: ThreadId.make("side-chat"),
694 }),
695 },
696 {
697 name: "queued message steered",
698 method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
699 send: (commandId: CommandId) =>
700 promoteQueuedRun({
701 commandId,
702 threadId: v2ThreadId,
703 queuedRunId: RunId.make("queued"),
704 targetRunId: RunId.make("running"),
705 }),
706 },
707 ] as const;
708
709 const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")(
710 function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect<never, Refused>) {
711 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] });
712 const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
713 const attempts: string[] = [];
714 const firstAttemptFailed = yield* Deferred.make<void>();
715 const healthyMethod = (
716 healthySession.client as unknown as Record<
717 string,
718 (input: unknown) => Effect.Effect<unknown>
719 >
720 )[turnSend.method]!;
721 const failingClient = {
722 ...healthySession.client,
723 [turnSend.method]: (input: { readonly commandId: CommandId }) =>
724 Effect.gen(function* () {
725 attempts.push(input.commandId);
726 if (attempts.length > 1) return yield* healthyMethod(input);
727 yield* SubscriptionRef.set(supervisor.session, Option.none());
728 yield* Deferred.succeed(firstAttemptFailed, undefined);
729 return yield* failure;
730 }),
731 } as unknown as WsRpcProtocolClient;
732 yield* SubscriptionRef.set(
733 supervisor.session,
734 Option.some({ ...healthySession, client: failingClient }),
735 );
736 const sendFiber = yield* turnSend
737 .send(CommandId.make("command-turn-send"))
738 .pipe(
739 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
740 Effect.forkChild,
741 );
742 yield* Deferred.await(firstAttemptFailed);
743 yield* SubscriptionRef.set(
744 supervisor.session,
745 Option.some({ ...healthySession, client: failingClient }),
746 );
747 return { exit: yield* Fiber.await(sendFiber), attempts };
748 },
749 );
750
751 it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) =>
752 Effect.gen(function* () {
753 const { exit, attempts } = yield* sendFailingFirstAttempt(
754 turnSend,
755 Effect.failCause(Cause.interrupt()),
756 );
757
758 expect(attempts).toEqual(["command-turn-send", "command-turn-send"]);
759 expect(Exit.isSuccess(exit)).toBe(true);
760 }).pipe(Effect.provide(layerTestRandom)),
761 );
762
763 it.effect("doesn't resend a new thread's first message the server refused", () =>
764 Effect.gen(function* () {
765 const { exit, attempts } = yield* sendFailingFirstAttempt(
766 turnSends[0],
767 Effect.fail(new Refused()),
768 );
769
770 expect(attempts).toEqual(["command-turn-send"]);
771 assert(Exit.isFailure(exit));
772 expect(isLostTransportCause(exit.cause)).toBe(false);
773 }).pipe(Effect.provide(layerTestRandom)),
774 );
775
776 it.effect("Stop with no run left ends the thread's pull request watches", () =>
777 Effect.gen(function* () {
778 const link = {
779 host: "github.com",
780 repository: "pingdotgg/t3code",
781 url: "https://github.com/pingdotgg/t3code/pull/7",
782 source: "agent" as const,
783 linkedAt: "2026-10-05T00:00:00.000Z",
784 snapshot: null,
785 stack: null,
786 };
787 const watch = {
788 startedAt: "2026-10-05T00:00:00.000Z",
789 headSha: null,
790 failedChecks: [],
791 passed: false,
792 passedChecks: [],
793 remarksThrough: "2026-10-05T00:00:00.000Z",
794 remarkIds: [],
795 conflicting: false,
796 wakes: 0,
797 };
798 const projection: OrchestrationV2ThreadProjection = {
799 ...v2Projection,
800 thread: {
801 ...v2Projection.thread,
802 pullRequests: [
803 { ...link, number: 7, watch },
804 { ...link, number: 8 },
805 { ...link, number: 9, source: "stack-dismissed", watch },
806 ],
807 },
808 };
809 const commands: OrchestrationV2Command[] = [];
810 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
811
812 yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
813 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
814 );
815
816 expect(commands).toEqual([
817 {
818 type: "thread.pull-request.watch",
819 commandId: expect.any(String),
820 threadId: v2ThreadId,
821 host: "github.com",
822 repository: "pingdotgg/t3code",
823 number: 7,
824 watching: false,
825 },
826 ]);
827 }).pipe(Effect.provide(layerTestRandom)),
828 );
829
830 it.effect.each(["waiting", "completed", "rolled_back"] as const)(
831 "dispatches Stop for %s runs with background commands except rollback",
832 (status) =>
833 Effect.gen(function* () {
834 const waitingRunId = RunId.make("run-waiting");
835 const projection: OrchestrationV2ThreadProjection = {
836 ...v2Projection,
837 runs: [
838 {
839 id: waitingRunId,
840 threadId: v2ThreadId,
841 ordinal: 1,
842 providerInstanceId: v2Projection.thread.providerInstanceId,
843 modelSelection: v2Projection.thread.modelSelection,
844 providerThreadId: null,
845 userMessageId: MessageId.make("message-waiting"),
846 rootNodeId: null,
847 activeAttemptId: null,
848 status,
849 requestedAt: v2Now,
850 startedAt: v2Now,
851 completedAt: null,
852 checkpointId: null,
853 contextHandoffId: null,
854 },
855 ],
856 turnItems: [
857 {
858 id: TurnItemId.make("background-command"),
859 threadId: v2ThreadId,
860 runId: waitingRunId,
861 nodeId: null,
862 providerThreadId: null,
863 providerTurnId: null,
864 nativeItemRef: null,
865 parentItemId: null,
866 ordinal: 1,
867 status: "running",
868 title: null,
869 startedAt: v2Now,
870 completedAt: null,
871 updatedAt: v2Now,
872 type: "command_execution",
873 input: "vp run dev",
874 },
875 ],
876 };
877 const commands: OrchestrationV2Command[] = [];
878 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
879
880 const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
881 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
882 );
883
884 expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
885 expect(commands).toEqual(
886 status === "rolled_back"
887 ? []
888 : [
889 {
890 type: "run.interrupt",
891 commandId: expect.any(String),
892 threadId: v2ThreadId,
893 runId: waitingRunId,
894 holdQueue: true,
895 },
896 ],
897 );
898 }).pipe(Effect.provide(layerTestRandom)),
899 );
900
901 it.effect(
902 "a native subagent stop targets its owning run rather than holding the parent queue",
903 () =>
904 Effect.gen(function* () {
905 const subagentId = NodeId.make("native-subagent");
906 const runId = RunId.make("settled-owner-run");
907 const commands: OrchestrationV2Command[] = [];
908 const supervisor = yield* makeSupervisor({
909 commands,
910 projects: [],
911 projection: {
912 ...v2Projection,
913 subagents: [
914 {
915 id: subagentId,
916 threadId: v2ThreadId,
917 runId,
918 parentNodeId: NodeId.make("owner-node"),
919 origin: "provider_native",
920 createdBy: "agent",
921 driver: ProviderDriverKind.make("claudeAgent"),
922 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
923 providerThreadId: null,
924 childThreadId: ThreadId.make("native-child-thread"),
925 nativeTaskRef: null,
926 prompt: "Work",
927 title: null,
928 model: null,
929 result: null,
930 status: "running",
931 startedAt: v2Now,
932 completedAt: null,
933 updatedAt: v2Now,
934 },
935 ],
936 },
937 });
938 yield* interruptThreadTurn({
939 commandId: CommandId.make("native-stop"),
940 threadId: v2ThreadId,
941 subagentId,
942 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
943 expect(commands).toEqual([
944 {
945 type: "subagent.stop",
946 commandId: "native-stop",
947 threadId: v2ThreadId,
948 runId,
949 subagentId,
950 },
951 ]);
952 }).pipe(Effect.provide(layerTestRandom)),
953 );
954
955 it.effect(
956 "an app-owned subagent stop asks the parent to clear an orphan, then stops the child",
957 () =>
958 Effect.gen(function* () {
959 const subagentId = NodeId.make("app-owned-subagent");
960 const runId = RunId.make("parent-run");
961 const childThreadId = ThreadId.make("app-owned-child-thread");
962 const commands: OrchestrationV2Command[] = [];
963 const supervisor = yield* makeSupervisor({
964 commands,
965 projects: [],
966 advertiseThreadStop: true,
967 projection: {
968 ...v2Projection,
969 subagents: [
970 {
971 id: subagentId,
972 threadId: v2ThreadId,
973 runId,
974 parentNodeId: NodeId.make("owner-node"),
975 origin: "app_owned",
976 createdBy: "agent",
977 driver: ProviderDriverKind.make("codex"),
978 providerInstanceId: ProviderInstanceId.make("codex"),
979 providerThreadId: null,
980 childThreadId,
981 nativeTaskRef: null,
982 prompt: "Work",
983 title: null,
984 model: null,
985 result: null,
986 status: "running",
987 startedAt: v2Now,
988 completedAt: null,
989 updatedAt: v2Now,
990 },
991 ],
992 },
993 });
994 yield* interruptThreadTurn({
995 commandId: CommandId.make("lineage-stop"),
996 threadId: v2ThreadId,
997 subagentId,
998 // A parent run must not be interrupted on the child thread.
999 runId,
1000 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
1001 expect(commands).toEqual([
1002 {
1003 type: "subagent.stop",
1004 commandId: expect.any(String),
1005 threadId: v2ThreadId,
1006 runId,
1007 subagentId,
1008 },
1009 { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId },
1010 ]);
1011 }).pipe(Effect.provide(layerTestRandom)),
1012 );
1013
1014 it.effect("stops a thread without relying on background work in the history window", () =>
1015 Effect.gen(function* () {
1016 const commands: OrchestrationV2Command[] = [];
1017 const projectionRequests: ThreadId[] = [];
1018 const supervisor = yield* makeSupervisor({
1019 commands,
1020 projects: [],
1021 projectionRequests,
1022 advertiseThreadStop: true,
1023 });
1024
1025 const result = yield* interruptThreadTurn({
1026 commandId: CommandId.make("stop-outside-history-window"),
1027 threadId: v2ThreadId,
1028 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
1029
1030 expect(result).toEqual({ sequence: 1 });
1031 expect(projectionRequests).toEqual([]);
1032 expect(commands).toEqual([
1033 {
1034 type: "thread.stop",
1035 commandId: "stop-outside-history-window",
1036 threadId: v2ThreadId,
1037 },
1038 ]);
1039 }).pipe(Effect.provide(layerTestRandom)),
1040 );
1041});