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