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