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

commands.test.ts

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