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 PlanId,
11 ProjectId,
12 ProviderInstanceId,
13 ProviderDriverKind,
14 RunId,
15 RuntimeRequestId,
16 ThreadId,
17 TurnItemId,
18 WS_METHODS,
19 type OrchestrationV2Command,
20 type OrchestrationV2ThreadLaunchInput,
21 type OrchestrationV2ThreadProjection,
22 type ProjectMutation,
23} from "@t3tools/contracts";
24import { describe, expect, it } from "@effect/vitest";
25import * as Crypto from "effect/Crypto";
26import * as Effect from "effect/Effect";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as SubscriptionRef from "effect/SubscriptionRef";
30
31import {
32 AVAILABLE_CONNECTION_STATE,
33 PrimaryConnectionTarget,
34 type PreparedConnection,
35} from "../connection/model.ts";
36import * as EnvironmentSupervisor from "../connection/supervisor.ts";
37import * as RpcSession from "../rpc/session.ts";
38import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
39import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
40import {
41 archiveThread,
42 cancelQueuedRun,
43 createProject,
44 dismissThreadUserInput,
45 editQueuedRun,
46 forkThreadFromRun,
47 interruptThreadTurn,
48 mergeThreadBack,
49 promoteQueuedRun,
50 reorderActiveThread,
51 reorderQueuedRun,
52 revertThreadCheckpoint,
53 settleThread,
54 startThreadTurn,
55 unsettleThread,
56 updateProject,
57 updateThreadMetadata,
58} from "./commands.ts";
59
60const layerTestCrypto = Layer.succeed(
61 Crypto.Crypto,
62 Crypto.make({
63 randomBytes: (size) => new Uint8Array(size),
64 digest: (_algorithm, data) => Effect.succeed(data),
65 }),
66);
67
68const TARGET = new PrimaryConnectionTarget({
69 environmentId: EnvironmentId.make("environment-1"),
70 label: "Test environment",
71 httpBaseUrl: "https://environment.example.test",
72 wsBaseUrl: "wss://environment.example.test",
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 advertiseServerResolvedCommandContext?: 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.advertiseServerResolvedCommandContext === false
130 ? {}
131 : { serverResolvedCommandContext: true }),
132 },
133 },
134 } as never),
135 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
136 ready: Effect.void,
137 probe: Effect.void,
138 closed: Effect.never,
139 };
140 return EnvironmentSupervisor.EnvironmentSupervisor.of({
141 target: TARGET,
142 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
143 session: yield* SubscriptionRef.make(Option.some(session)),
144 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
145 connect: Effect.void,
146 disconnect: Effect.void,
147 retryNow: Effect.void,
148 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
149});
150
151describe("V2 environment commands", () => {
152 it.effect("routes projects through the event-sourced project transport", () =>
153 Effect.gen(function* () {
154 const projects: ProjectMutation[] = [];
155 const supervisor = yield* makeSupervisor({ commands: [], projects });
156
157 yield* createProject({
158 projectId: ProjectId.make("project-1"),
159 title: "Project",
160 workspaceRoot: "/workspace/project",
161 createWorkspaceRootIfMissing: true,
162 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
163
164 expect(projects).toEqual([
165 {
166 type: "project.create",
167 commandId: "00000000-0000-4000-8000-000000000000",
168 projectId: "project-1",
169 title: "Project",
170 workspaceRoot: "/workspace/project",
171 createWorkspaceRootIfMissing: true,
172 },
173 ]);
174 }).pipe(Effect.provide(layerTestCrypto)),
175 );
176
177 it.effect("persists and clears project presentation and environment settings", () =>
178 Effect.gen(function* () {
179 const projects: ProjectMutation[] = [];
180 const supervisor = yield* makeSupervisor({ commands: [], projects });
181 const projectId = ProjectId.make("project-1");
182 const projectIcon = { kind: "emoji", emoji: "🌲" } as const;
183 yield* updateProject({
184 projectId,
185 autoPull: true,
186 projectIcon,
187 faviconPath: "/workspace/project/icon.png",
188 defaultThreadEnvMode: "worktree",
189 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
190 yield* updateProject({
191 projectId,
192 autoPull: false,
193 projectIcon: null,
194 faviconPath: null,
195 defaultThreadEnvMode: null,
196 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
197
198 expect(projects).toEqual([
199 {
200 type: "project.update",
201 commandId: "00000000-0000-4000-8000-000000000000",
202 projectId,
203 autoPull: true,
204 projectIcon,
205 faviconPath: "/workspace/project/icon.png",
206 defaultThreadEnvMode: "worktree",
207 },
208 {
209 type: "project.update",
210 commandId: "00000000-0000-4000-8000-000000000000",
211 projectId,
212 autoPull: false,
213 projectIcon: null,
214 faviconPath: null,
215 defaultThreadEnvMode: null,
216 },
217 ]);
218 }).pipe(Effect.provide(layerTestCrypto)),
219 );
220
221 it.effect("preserves caller command ids for idempotent V2 commands", () =>
222 Effect.gen(function* () {
223 const commands: OrchestrationV2Command[] = [];
224 const supervisor = yield* makeSupervisor({ commands, projects: [] });
225
226 yield* archiveThread({
227 commandId: CommandId.make("queued-command"),
228 threadId: ThreadId.make("thread-1"),
229 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
230
231 expect(commands).toEqual([
232 { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
233 ]);
234 }).pipe(Effect.provide(layerTestCrypto)),
235 );
236
237 it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () =>
238 Effect.gen(function* () {
239 const scopeId = CheckpointScopeId.make("checkpoint-scope-root");
240 const checkpointId = CheckpointId.make("checkpoint-thread-start");
241 const projection: OrchestrationV2ThreadProjection = {
242 ...v2Projection,
243 checkpoints: [
244 {
245 id: checkpointId,
246 threadId: v2ThreadId,
247 scopeId,
248 runId: null,
249 nodeId: NodeId.make("node-run-1"),
250 parentCheckpointId: null,
251 ordinalWithinScope: 0,
252 appRunOrdinal: null,
253 ref: CheckpointRef.make("refs/t3/thread-start"),
254 status: "ready",
255 files: [],
256 capturedAt: v2Now,
257 },
258 ],
259 };
260 const commands: OrchestrationV2Command[] = [];
261 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
262
263 yield* revertThreadCheckpoint({
264 commandId: CommandId.make("rollback-thread-start"),
265 threadId: v2ThreadId,
266 turnCount: 0,
267 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
268
269 expect(commands).toEqual([
270 {
271 type: "checkpoint.rollback",
272 commandId: "rollback-thread-start",
273 threadId: v2ThreadId,
274 scopeId,
275 checkpointId,
276 },
277 ]);
278 }).pipe(Effect.provide(layerTestCrypto)),
279 );
280
281 it.effect("preserves plan implementation provenance on V2 runs", () =>
282 Effect.gen(function* () {
283 const commands: OrchestrationV2Command[] = [];
284 const supervisor = yield* makeSupervisor({ commands, projects: [] });
285
286 yield* startThreadTurn({
287 commandId: CommandId.make("implement-plan"),
288 threadId: v2ThreadId,
289 message: {
290 messageId: MessageId.make("message-implementation"),
291 role: "user",
292 text: "Implement the plan",
293 attachments: [],
294 },
295 modelSelection: {
296 instanceId: ProviderInstanceId.make("codex"),
297 model: "gpt-5.4",
298 },
299 runtimeMode: "full-access",
300 interactionMode: "default",
301 titleSeed: "Implement the plan",
302 sourceProposedPlan: {
303 threadId: ThreadId.make("thread-plan"),
304 planId: PlanId.make("plan-1"),
305 },
306 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
307
308 expect(commands).toHaveLength(1);
309 expect(commands[0]).toMatchObject({
310 type: "message.dispatch",
311 commandId: "implement-plan",
312 threadId: v2ThreadId,
313 titleSeed: "Implement the plan",
314 sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" },
315 deliveryIntent: "auto",
316 dispatchMode: { type: "start_immediately" },
317 });
318 }).pipe(Effect.provide(layerTestCrypto)),
319 );
320
321 it.effect("preserves an existing worktree and branch during first-message launch", () =>
322 Effect.gen(function* () {
323 const launches: OrchestrationV2ThreadLaunchInput[] = [];
324 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
325
326 yield* startThreadTurn({
327 commandId: CommandId.make("launch-existing-worktree"),
328 threadId: v2ThreadId,
329 message: {
330 messageId: MessageId.make("message-existing-worktree"),
331 role: "user",
332 text: "Continue here",
333 attachments: [],
334 },
335 runtimeMode: "full-access",
336 interactionMode: "default",
337 titleSeed: "Continue here",
338 bootstrap: {
339 createThread: {
340 projectId: ProjectId.make("project-1"),
341 title: "Thread",
342 modelSelection: v2Projection.thread.modelSelection,
343 runtimeMode: "full-access",
344 interactionMode: "default",
345 branch: "feature",
346 worktreePath: "/workspace/project-worktrees/feature",
347 createdAt: "2026-06-20T00:00:00.000Z",
348 },
349 },
350 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
351
352 expect(launches[0]).toMatchObject({
353 threadId: v2ThreadId,
354 title: "Continue here",
355 generateTitle: true,
356 workspaceStrategy: {
357 type: "existing_worktree",
358 worktreePath: "/workspace/project-worktrees/feature",
359 branch: "feature",
360 },
361 });
362 }).pipe(Effect.provide(layerTestCrypto)),
363 );
364
365 it.effect("provisions an origin-based worktree for an existing empty thread", () =>
366 Effect.gen(function* () {
367 const launches: OrchestrationV2ThreadLaunchInput[] = [];
368 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
369
370 yield* startThreadTurn({
371 commandId: CommandId.make("launch-existing-thread-worktree"),
372 threadId: v2ThreadId,
373 message: {
374 messageId: MessageId.make("message-existing-thread-worktree"),
375 role: "user",
376 text: "Move to a worktree",
377 attachments: [],
378 },
379 runtimeMode: "full-access",
380 interactionMode: "default",
381 bootstrap: {
382 prepareWorktree: {
383 projectCwd: "/workspace/project",
384 baseBranch: "main",
385 branch: "feature",
386 startFromOrigin: true,
387 },
388 },
389 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
390
391 expect(launches[0]).toMatchObject({
392 threadId: v2ThreadId,
393 reuseExistingThread: true,
394 projectId: v2Projection.thread.projectId,
395 workspaceStrategy: {
396 type: "worktree",
397 baseRef: "main",
398 branch: "feature",
399 startFromOrigin: true,
400 },
401 });
402 }).pipe(Effect.provide(layerTestCrypto)),
403 );
404
405 it.effect("uses server-resolved delivery intent without fetching the full projection", () =>
406 Effect.gen(function* () {
407 const commands: OrchestrationV2Command[] = [];
408 const projectionRequests: ThreadId[] = [];
409 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
410
411 for (const [mode, expectedType] of [
412 ["queue", "queue_after_active"],
413 ["auto", "start_immediately"],
414 ["steer", "start_immediately"],
415 ["restart", "start_immediately"],
416 ] as const) {
417 yield* startThreadTurn({
418 commandId: CommandId.make(`command-${mode}`),
419 threadId: v2ThreadId,
420 message: {
421 messageId: MessageId.make(`message-${mode}`),
422 role: "user",
423 text: mode,
424 attachments: [],
425 },
426 runtimeMode: "full-access",
427 interactionMode: "default",
428 dispatchMode: mode,
429 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
430
431 expect(commands.at(-1)).toMatchObject({
432 type: "message.dispatch",
433 dispatchMode: { type: expectedType },
434 ...(mode === "queue" ? {} : { deliveryIntent: mode }),
435 });
436 }
437 expect(projectionRequests).toEqual([]);
438 }).pipe(Effect.provide(layerTestCrypto)),
439 );
440
441 it.effect("retains projection-shaped delivery for servers without command context support", () =>
442 Effect.gen(function* () {
443 const activeRunId = RunId.make("legacy-active-run");
444 const projection: OrchestrationV2ThreadProjection = {
445 ...v2Projection,
446 runs: [
447 {
448 id: activeRunId,
449 threadId: v2ThreadId,
450 ordinal: 1,
451 providerInstanceId: v2Projection.thread.providerInstanceId,
452 modelSelection: v2Projection.thread.modelSelection,
453 providerThreadId: null,
454 userMessageId: MessageId.make("legacy-active-message"),
455 rootNodeId: null,
456 activeAttemptId: null,
457 status: "running",
458 requestedAt: v2Now,
459 startedAt: v2Now,
460 completedAt: null,
461 checkpointId: null,
462 contextHandoffId: null,
463 },
464 ],
465 };
466 const commands: OrchestrationV2Command[] = [];
467 const projectionRequests: ThreadId[] = [];
468 const supervisor = yield* makeSupervisor({
469 commands,
470 projects: [],
471 projection,
472 projectionRequests,
473 advertiseServerResolvedCommandContext: false,
474 });
475
476 for (const [mode, expectedMode] of [
477 ["auto", { type: "queue_after_active" }],
478 ["queue", { type: "queue_after_active" }],
479 ["steer", { type: "steer_active", targetRunId: activeRunId }],
480 ["restart", { type: "restart_active", targetRunId: activeRunId }],
481 ] as const) {
482 yield* startThreadTurn({
483 commandId: CommandId.make(`legacy-command-${mode}`),
484 threadId: v2ThreadId,
485 message: {
486 messageId: MessageId.make(`legacy-message-${mode}`),
487 role: "user",
488 text: mode,
489 attachments: [],
490 },
491 runtimeMode: "full-access",
492 interactionMode: "default",
493 dispatchMode: mode,
494 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
495
496 expect(commands.at(-1)).toMatchObject({
497 type: "message.dispatch",
498 dispatchMode: expectedMode,
499 });
500 expect(commands.at(-1)).not.toHaveProperty("deliveryIntent");
501 }
502 expect(projectionRequests).toEqual([v2ThreadId, v2ThreadId, v2ThreadId, v2ThreadId]);
503 }).pipe(Effect.provide(layerTestCrypto)),
504 );
505
506 it.effect("Stop with no run left ends the thread's pull request watches", () =>
507 Effect.gen(function* () {
508 const link = {
509 host: "github.com",
510 repository: "pingdotgg/t3code",
511 url: "https://github.com/pingdotgg/t3code/pull/7",
512 source: "agent" as const,
513 linkedAt: "2026-10-05T00:00:00.000Z",
514 snapshot: null,
515 stack: null,
516 };
517 const watch = {
518 startedAt: "2026-10-05T00:00:00.000Z",
519 headSha: null,
520 failedChecks: [],
521 passed: false,
522 passedChecks: [],
523 remarksThrough: "2026-10-05T00:00:00.000Z",
524 remarkIds: [],
525 conflicting: false,
526 wakes: 0,
527 };
528 const projection: OrchestrationV2ThreadProjection = {
529 ...v2Projection,
530 thread: {
531 ...v2Projection.thread,
532 pullRequests: [
533 { ...link, number: 7, watch },
534 { ...link, number: 8 },
535 { ...link, number: 9, source: "stack-dismissed", watch },
536 ],
537 },
538 };
539 const commands: OrchestrationV2Command[] = [];
540 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
541
542 yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
543 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
544 );
545
546 expect(commands).toEqual([
547 {
548 type: "thread.pull-request.watch",
549 commandId: expect.any(String),
550 threadId: v2ThreadId,
551 host: "github.com",
552 repository: "pingdotgg/t3code",
553 number: 7,
554 watching: false,
555 },
556 ]);
557 }).pipe(Effect.provide(layerTestCrypto)),
558 );
559
560 it.effect.each([
561 "waiting",
562 "completed",
563 "failed",
564 "interrupted",
565 "cancelled",
566 "rolled_back",
567 ] as const)("dispatches Stop for %s runs with background commands except rollback", (status) =>
568 Effect.gen(function* () {
569 const waitingRunId = RunId.make("run-waiting");
570 const projection: OrchestrationV2ThreadProjection = {
571 ...v2Projection,
572 runs: [
573 {
574 id: waitingRunId,
575 threadId: v2ThreadId,
576 ordinal: 1,
577 providerInstanceId: v2Projection.thread.providerInstanceId,
578 modelSelection: v2Projection.thread.modelSelection,
579 providerThreadId: null,
580 userMessageId: MessageId.make("message-waiting"),
581 rootNodeId: null,
582 activeAttemptId: null,
583 status,
584 requestedAt: v2Now,
585 startedAt: v2Now,
586 completedAt: null,
587 checkpointId: null,
588 contextHandoffId: null,
589 },
590 ],
591 turnItems: [
592 {
593 id: TurnItemId.make("background-command"),
594 threadId: v2ThreadId,
595 runId: waitingRunId,
596 nodeId: null,
597 providerThreadId: null,
598 providerTurnId: null,
599 nativeItemRef: null,
600 parentItemId: null,
601 ordinal: 1,
602 status: "running",
603 title: null,
604 startedAt: v2Now,
605 completedAt: null,
606 updatedAt: v2Now,
607 type: "command_execution",
608 input: "vp run dev",
609 },
610 ],
611 };
612 const commands: OrchestrationV2Command[] = [];
613 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
614
615 const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
616 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
617 );
618
619 expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
620 expect(commands).toEqual(
621 status === "rolled_back"
622 ? []
623 : [
624 {
625 type: "run.interrupt",
626 commandId: expect.any(String),
627 threadId: v2ThreadId,
628 runId: waitingRunId,
629 holdQueue: true,
630 },
631 ],
632 );
633 }).pipe(Effect.provide(layerTestCrypto)),
634 );
635
636 it.effect(
637 "dispatches V2-native relationship and queue commands without compatibility shaping",
638 () =>
639 Effect.gen(function* () {
640 const commands: OrchestrationV2Command[] = [];
641 const supervisor = yield* makeSupervisor({ commands, projects: [] });
642 const provide = Effect.provideService(
643 EnvironmentSupervisor.EnvironmentSupervisor,
644 supervisor,
645 );
646
647 yield* forkThreadFromRun({
648 commandId: CommandId.make("fork"),
649 sourceThreadId: v2ThreadId,
650 targetThreadId: ThreadId.make("thread-fork"),
651 runId: RunId.make("run-1"),
652 }).pipe(provide);
653 yield* mergeThreadBack({
654 commandId: CommandId.make("merge"),
655 sourceThreadId: ThreadId.make("thread-fork"),
656 targetThreadId: v2ThreadId,
657 runId: RunId.make("run-2"),
658 }).pipe(provide);
659 yield* reorderQueuedRun({
660 commandId: CommandId.make("reorder"),
661 threadId: v2ThreadId,
662 runId: RunId.make("run-3"),
663 beforeRunId: RunId.make("run-4"),
664 }).pipe(provide);
665 yield* promoteQueuedRun({
666 commandId: CommandId.make("promote"),
667 threadId: v2ThreadId,
668 queuedRunId: RunId.make("run-3"),
669 targetRunId: RunId.make("run-active"),
670 }).pipe(provide);
671 yield* cancelQueuedRun({
672 commandId: CommandId.make("cancel"),
673 threadId: v2ThreadId,
674 runId: RunId.make("run-3"),
675 }).pipe(provide);
676 yield* editQueuedRun({
677 commandId: CommandId.make("edit"),
678 threadId: v2ThreadId,
679 runId: RunId.make("run-3"),
680 text: "updated queued text",
681 }).pipe(provide);
682 yield* editQueuedRun({
683 commandId: CommandId.make("edit-attachments"),
684 threadId: v2ThreadId,
685 runId: RunId.make("run-3"),
686 text: "updated queued text with attachments",
687 edit: {
688 messageId: MessageId.make("message-3"),
689 attachments: [
690 {
691 type: "image",
692 id: "attachment-kept",
693 name: "kept.png",
694 mimeType: "image/png",
695 sizeBytes: 64,
696 },
697 ],
698 },
699 }).pipe(provide);
700
701 expect(commands).toMatchObject([
702 { type: "thread.fork", sourcePoint: { type: "run", runId: "run-1" } },
703 { type: "thread.merge_back", sourcePoint: { type: "run", runId: "run-2" } },
704 { type: "queued-run.reorder", runId: "run-3", beforeRunId: "run-4" },
705 {
706 type: "queued-message.promote-to-steer",
707 queuedRunId: "run-3",
708 targetRunId: "run-active",
709 },
710 { type: "queued-run.cancel", runId: "run-3" },
711 { type: "queued-run.edit", runId: "run-3", text: "updated queued text" },
712 {
713 type: "queued-run.edit",
714 runId: "run-3",
715 text: "updated queued text with attachments",
716 attachments: [{ id: "attachment-kept" }],
717 },
718 ]);
719 // A text-only edit must not send an attachments replacement list.
720 expect(commands[5]).not.toHaveProperty("attachments");
721 }).pipe(Effect.provide(layerTestCrypto)),
722 );
723
724 it.effect("delegates model selection to the server without fetching the full projection", () =>
725 Effect.gen(function* () {
726 const commands: OrchestrationV2Command[] = [];
727 const projectionRequests: ThreadId[] = [];
728 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
729
730 yield* updateThreadMetadata({
731 commandId: CommandId.make("same-provider"),
732 threadId: v2ThreadId,
733 modelSelection: {
734 instanceId: ProviderInstanceId.make("codex"),
735 model: "another-model",
736 },
737 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
738
739 yield* updateThreadMetadata({
740 commandId: CommandId.make("switch-provider"),
741 threadId: v2ThreadId,
742 modelSelection: {
743 instanceId: ProviderInstanceId.make("claude"),
744 model: "claude-sonnet-4-6",
745 },
746 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
747
748 expect(commands).toEqual([
749 {
750 type: "thread.model-selection.set",
751 commandId: "same-provider",
752 threadId: v2ThreadId,
753 modelSelection: { instanceId: "codex", model: "another-model" },
754 },
755 {
756 type: "thread.model-selection.set",
757 commandId: "switch-provider",
758 threadId: v2ThreadId,
759 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
760 },
761 ]);
762 expect(projectionRequests).toEqual([]);
763 }).pipe(Effect.provide(layerTestCrypto)),
764 );
765
766 it.effect("retains provider-switch shaping for servers without command context support", () =>
767 Effect.gen(function* () {
768 const commands: OrchestrationV2Command[] = [];
769 const projectionRequests: ThreadId[] = [];
770 const supervisor = yield* makeSupervisor({
771 commands,
772 projects: [],
773 projectionRequests,
774 advertiseServerResolvedCommandContext: false,
775 });
776
777 yield* updateThreadMetadata({
778 commandId: CommandId.make("legacy-switch-provider"),
779 threadId: v2ThreadId,
780 modelSelection: {
781 instanceId: ProviderInstanceId.make("claude"),
782 model: "claude-sonnet-4-6",
783 },
784 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
785
786 expect(projectionRequests).toEqual([v2ThreadId]);
787 expect(commands).toEqual([
788 {
789 type: "provider.switch",
790 commandId: "legacy-switch-provider",
791 threadId: v2ThreadId,
792 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
793 },
794 ]);
795 }).pipe(Effect.provide(layerTestCrypto)),
796 );
797
798 it.effect.each([true, false])(
799 "rolls back an identified checkpoint without fetching the full projection, restoreFiles=%s",
800 (restoreFiles) =>
801 Effect.gen(function* () {
802 const commands: OrchestrationV2Command[] = [];
803 const projectionRequests: ThreadId[] = [];
804 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
805
806 yield* revertThreadCheckpoint({
807 commandId: CommandId.make("rollback-known-checkpoint"),
808 threadId: v2ThreadId,
809 checkpointId: CheckpointId.make("checkpoint-known"),
810 scopeId: CheckpointScopeId.make("scope-known"),
811 restoreFiles,
812 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
813
814 expect(projectionRequests).toEqual([]);
815 expect(commands).toEqual([
816 {
817 type: "checkpoint.rollback",
818 commandId: "rollback-known-checkpoint",
819 threadId: v2ThreadId,
820 checkpointId: "checkpoint-known",
821 scopeId: "scope-known",
822 restoreFiles,
823 },
824 ]);
825 }).pipe(Effect.provide(layerTestCrypto)),
826 );
827
828 it.effect("validates identified checkpoints locally for older servers", () =>
829 Effect.gen(function* () {
830 const checkpointId = CheckpointId.make("legacy-checkpoint");
831 const scopeId = CheckpointScopeId.make("legacy-checkpoint-scope");
832 for (const status of ["ready", "missing", "error", "stale", null] as const) {
833 const commands: OrchestrationV2Command[] = [];
834 const projectionRequests: ThreadId[] = [];
835 const supervisor = yield* makeSupervisor({
836 commands,
837 projects: [],
838 projectionRequests,
839 advertiseServerResolvedCommandContext: false,
840 projection: {
841 ...v2Projection,
842 checkpoints:
843 status === null
844 ? []
845 : [
846 {
847 id: checkpointId,
848 threadId: v2ThreadId,
849 scopeId,
850 runId: null,
851 nodeId: NodeId.make("legacy-checkpoint-node"),
852 parentCheckpointId: null,
853 ordinalWithinScope: 0,
854 appRunOrdinal: null,
855 ref: CheckpointRef.make("refs/t3/legacy-checkpoint"),
856 status,
857 files: [],
858 capturedAt: v2Now,
859 },
860 ],
861 },
862 });
863 const rollback = revertThreadCheckpoint({
864 commandId: CommandId.make(`legacy-rollback-${status}`),
865 threadId: v2ThreadId,
866 checkpointId,
867 scopeId,
868 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
869
870 if (status === "ready") {
871 yield* rollback;
872 expect(commands).toEqual([
873 {
874 type: "checkpoint.rollback",
875 commandId: "legacy-rollback-ready",
876 threadId: v2ThreadId,
877 checkpointId,
878 scopeId,
879 },
880 ]);
881 } else {
882 const error = yield* rollback.pipe(Effect.flip);
883 expect(error._tag).toBe("OrchestrationV2CheckpointUnavailableError");
884 expect(commands).toEqual([]);
885 }
886 expect(projectionRequests).toEqual([v2ThreadId]);
887 }
888 }).pipe(Effect.provide(layerTestCrypto)),
889 );
890
891 it.effect("dispatches settle and unsettle commands without timestamps", () =>
892 Effect.gen(function* () {
893 const dispatched: OrchestrationV2Command[] = [];
894 const supervisor = yield* makeSupervisor({ commands: dispatched, projects: [] });
895
896 yield* settleThread({
897 commandId: CommandId.make("settle-command"),
898 threadId: ThreadId.make("thread-1"),
899 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
900 yield* unsettleThread({
901 commandId: CommandId.make("unsettle-command"),
902 threadId: ThreadId.make("thread-1"),
903 reason: "user",
904 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
905
906 expect(dispatched).toEqual([
907 {
908 type: "thread.settle",
909 commandId: "settle-command",
910 threadId: "thread-1",
911 },
912 {
913 type: "thread.unsettle",
914 commandId: "unsettle-command",
915 threadId: "thread-1",
916 reason: "user",
917 },
918 ]);
919 }).pipe(Effect.provide(layerTestCrypto)),
920 );
921
922 it.effect("sends an active order key without changing activity timestamps", () =>
923 Effect.gen(function* () {
924 const dispatched: OrchestrationV2Command[] = [];
925 const supervisor = yield* makeSupervisor({ commands: dispatched, projects: [] });
926 yield* reorderActiveThread({
927 commandId: CommandId.make("reorder-command"),
928 threadId: ThreadId.make("thread-1"),
929 orderKey: "mf",
930 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
931 expect(dispatched).toEqual([
932 {
933 type: "thread.active.reorder",
934 commandId: "reorder-command",
935 threadId: "thread-1",
936 orderKey: "mf",
937 },
938 ]);
939 }).pipe(Effect.provide(layerTestCrypto)),
940 );
941
942 it.effect("dismisses a pending user-input request", () =>
943 Effect.gen(function* () {
944 const commands: OrchestrationV2Command[] = [];
945 const supervisor = yield* makeSupervisor({ commands, projects: [] });
946
947 yield* dismissThreadUserInput({
948 commandId: CommandId.make("dismiss-command"),
949 threadId: v2ThreadId,
950 requestId: RuntimeRequestId.make("request-1"),
951 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
952
953 expect(commands).toEqual([
954 {
955 type: "thread.user-input.dismiss",
956 commandId: "dismiss-command",
957 threadId: v2ThreadId,
958 requestId: "request-1",
959 },
960 ]);
961 }).pipe(Effect.provide(layerTestCrypto)),
962 );
963
964 it.effect("dispatches an explicit idle start without fetching the full projection", () =>
965 Effect.gen(function* () {
966 const commands: OrchestrationV2Command[] = [];
967 const projectionRequests: ThreadId[] = [];
968 const supervisor = yield* makeSupervisor({
969 commands,
970 projects: [],
971 projectionRequests,
972 });
973
974 yield* startThreadTurn({
975 commandId: CommandId.make("direct-start"),
976 threadId: v2ThreadId,
977 message: {
978 messageId: MessageId.make("direct-start-message"),
979 role: "user",
980 text: "continue",
981 attachments: [],
982 },
983 runtimeMode: "full-access",
984 interactionMode: "default",
985 dispatchMode: "start",
986 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
987
988 expect(projectionRequests).toEqual([]);
989 expect(commands).toMatchObject([
990 {
991 type: "message.dispatch",
992 threadId: v2ThreadId,
993 dispatchMode: { type: "start_immediately" },
994 },
995 ]);
996 }).pipe(Effect.provide(layerTestCrypto)),
997 );
998
999 it.effect(
1000 "a native subagent stop targets its owning run rather than holding the parent queue",
1001 () =>
1002 Effect.gen(function* () {
1003 const subagentId = NodeId.make("native-subagent");
1004 const runId = RunId.make("settled-owner-run");
1005 const commands: OrchestrationV2Command[] = [];
1006 const supervisor = yield* makeSupervisor({
1007 commands,
1008 projects: [],
1009 projection: {
1010 ...v2Projection,
1011 subagents: [
1012 {
1013 id: subagentId,
1014 threadId: v2ThreadId,
1015 runId,
1016 parentNodeId: NodeId.make("owner-node"),
1017 origin: "provider_native",
1018 createdBy: "agent",
1019 driver: ProviderDriverKind.make("claudeAgent"),
1020 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
1021 providerThreadId: null,
1022 childThreadId: ThreadId.make("native-child-thread"),
1023 nativeTaskRef: null,
1024 prompt: "Work",
1025 title: null,
1026 model: null,
1027 result: null,
1028 status: "running",
1029 startedAt: v2Now,
1030 completedAt: null,
1031 updatedAt: v2Now,
1032 },
1033 ],
1034 },
1035 });
1036 yield* interruptThreadTurn({
1037 commandId: CommandId.make("native-stop"),
1038 threadId: v2ThreadId,
1039 subagentId,
1040 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
1041 expect(commands).toEqual([
1042 {
1043 type: "subagent.stop",
1044 commandId: "native-stop",
1045 threadId: v2ThreadId,
1046 runId,
1047 subagentId,
1048 },
1049 ]);
1050 }).pipe(Effect.provide(layerTestCrypto)),
1051 );
1052
1053 it.effect("interrupts a known run without fetching the full projection", () =>
1054 Effect.gen(function* () {
1055 const commands: OrchestrationV2Command[] = [];
1056 const projectionRequests: ThreadId[] = [];
1057 const supervisor = yield* makeSupervisor({
1058 commands,
1059 projects: [],
1060 projectionRequests,
1061 });
1062
1063 yield* interruptThreadTurn({
1064 commandId: CommandId.make("direct-interrupt"),
1065 threadId: v2ThreadId,
1066 runId: RunId.make("active-run"),
1067 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
1068
1069 expect(projectionRequests).toEqual([]);
1070 expect(commands).toEqual([
1071 {
1072 type: "run.interrupt",
1073 commandId: "direct-interrupt",
1074 threadId: v2ThreadId,
1075 runId: "active-run",
1076 holdQueue: true,
1077 },
1078 ]);
1079 }).pipe(Effect.provide(layerTestCrypto)),
1080 );
1081});