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