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 expect(commands[5]).not.toHaveProperty("attachments");
720 }).pipe(Effect.provide(layerTestCrypto)),
721 );
722
723 it.effect("delegates model selection to the server without fetching the full projection", () =>
724 Effect.gen(function* () {
725 const commands: OrchestrationV2Command[] = [];
726 const projectionRequests: ThreadId[] = [];
727 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
728
729 yield* updateThreadMetadata({
730 commandId: CommandId.make("same-provider"),
731 threadId: v2ThreadId,
732 modelSelection: {
733 instanceId: ProviderInstanceId.make("codex"),
734 model: "another-model",
735 },
736 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
737
738 yield* updateThreadMetadata({
739 commandId: CommandId.make("switch-provider"),
740 threadId: v2ThreadId,
741 modelSelection: {
742 instanceId: ProviderInstanceId.make("claude"),
743 model: "claude-sonnet-4-6",
744 },
745 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
746
747 expect(commands).toEqual([
748 {
749 type: "thread.model-selection.set",
750 commandId: "same-provider",
751 threadId: v2ThreadId,
752 modelSelection: { instanceId: "codex", model: "another-model" },
753 },
754 {
755 type: "thread.model-selection.set",
756 commandId: "switch-provider",
757 threadId: v2ThreadId,
758 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
759 },
760 ]);
761 expect(projectionRequests).toEqual([]);
762 }).pipe(Effect.provide(layerTestCrypto)),
763 );
764
765 it.effect("retains provider-switch shaping for servers without command context support", () =>
766 Effect.gen(function* () {
767 const commands: OrchestrationV2Command[] = [];
768 const projectionRequests: ThreadId[] = [];
769 const supervisor = yield* makeSupervisor({
770 commands,
771 projects: [],
772 projectionRequests,
773 advertiseServerResolvedCommandContext: false,
774 });
775
776 yield* updateThreadMetadata({
777 commandId: CommandId.make("legacy-switch-provider"),
778 threadId: v2ThreadId,
779 modelSelection: {
780 instanceId: ProviderInstanceId.make("claude"),
781 model: "claude-sonnet-4-6",
782 },
783 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
784
785 expect(projectionRequests).toEqual([v2ThreadId]);
786 expect(commands).toEqual([
787 {
788 type: "provider.switch",
789 commandId: "legacy-switch-provider",
790 threadId: v2ThreadId,
791 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
792 },
793 ]);
794 }).pipe(Effect.provide(layerTestCrypto)),
795 );
796
797 it.effect.each([true, false])(
798 "rolls back an identified checkpoint without fetching the full projection, restoreFiles=%s",
799 (restoreFiles) =>
800 Effect.gen(function* () {
801 const commands: OrchestrationV2Command[] = [];
802 const projectionRequests: ThreadId[] = [];
803 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
804
805 yield* revertThreadCheckpoint({
806 commandId: CommandId.make("rollback-known-checkpoint"),
807 threadId: v2ThreadId,
808 checkpointId: CheckpointId.make("checkpoint-known"),
809 scopeId: CheckpointScopeId.make("scope-known"),
810 restoreFiles,
811 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
812
813 expect(projectionRequests).toEqual([]);
814 expect(commands).toEqual([
815 {
816 type: "checkpoint.rollback",
817 commandId: "rollback-known-checkpoint",
818 threadId: v2ThreadId,
819 checkpointId: "checkpoint-known",
820 scopeId: "scope-known",
821 restoreFiles,
822 },
823 ]);
824 }).pipe(Effect.provide(layerTestCrypto)),
825 );
826
827 it.effect("validates identified checkpoints locally for older servers", () =>
828 Effect.gen(function* () {
829 const checkpointId = CheckpointId.make("legacy-checkpoint");
830 const scopeId = CheckpointScopeId.make("legacy-checkpoint-scope");
831 for (const status of ["ready", "missing", "error", "stale", null] as const) {
832 const commands: OrchestrationV2Command[] = [];
833 const projectionRequests: ThreadId[] = [];
834 const supervisor = yield* makeSupervisor({
835 commands,
836 projects: [],
837 projectionRequests,
838 advertiseServerResolvedCommandContext: false,
839 projection: {
840 ...v2Projection,
841 checkpoints:
842 status === null
843 ? []
844 : [
845 {
846 id: checkpointId,
847 threadId: v2ThreadId,
848 scopeId,
849 runId: null,
850 nodeId: NodeId.make("legacy-checkpoint-node"),
851 parentCheckpointId: null,
852 ordinalWithinScope: 0,
853 appRunOrdinal: null,
854 ref: CheckpointRef.make("refs/t3/legacy-checkpoint"),
855 status,
856 files: [],
857 capturedAt: v2Now,
858 },
859 ],
860 },
861 });
862 const rollback = revertThreadCheckpoint({
863 commandId: CommandId.make(`legacy-rollback-${status}`),
864 threadId: v2ThreadId,
865 checkpointId,
866 scopeId,
867 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
868
869 if (status === "ready") {
870 yield* rollback;
871 expect(commands).toEqual([
872 {
873 type: "checkpoint.rollback",
874 commandId: "legacy-rollback-ready",
875 threadId: v2ThreadId,
876 checkpointId,
877 scopeId,
878 },
879 ]);
880 } else {
881 const error = yield* rollback.pipe(Effect.flip);
882 expect(error._tag).toBe("OrchestrationV2CheckpointUnavailableError");
883 expect(commands).toEqual([]);
884 }
885 expect(projectionRequests).toEqual([v2ThreadId]);
886 }
887 }).pipe(Effect.provide(layerTestCrypto)),
888 );
889
890 it.effect("dispatches settle and unsettle commands without timestamps", () =>
891 Effect.gen(function* () {
892 const dispatched: OrchestrationV2Command[] = [];
893 const supervisor = yield* makeSupervisor({ commands: dispatched, projects: [] });
894
895 yield* settleThread({
896 commandId: CommandId.make("settle-command"),
897 threadId: ThreadId.make("thread-1"),
898 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
899 yield* unsettleThread({
900 commandId: CommandId.make("unsettle-command"),
901 threadId: ThreadId.make("thread-1"),
902 reason: "user",
903 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
904
905 expect(dispatched).toEqual([
906 {
907 type: "thread.settle",
908 commandId: "settle-command",
909 threadId: "thread-1",
910 },
911 {
912 type: "thread.unsettle",
913 commandId: "unsettle-command",
914 threadId: "thread-1",
915 reason: "user",
916 },
917 ]);
918 }).pipe(Effect.provide(layerTestCrypto)),
919 );
920
921 it.effect("sends an active order key without changing activity timestamps", () =>
922 Effect.gen(function* () {
923 const dispatched: OrchestrationV2Command[] = [];
924 const supervisor = yield* makeSupervisor({ commands: dispatched, projects: [] });
925 yield* reorderActiveThread({
926 commandId: CommandId.make("reorder-command"),
927 threadId: ThreadId.make("thread-1"),
928 orderKey: "mf",
929 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
930 expect(dispatched).toEqual([
931 {
932 type: "thread.active.reorder",
933 commandId: "reorder-command",
934 threadId: "thread-1",
935 orderKey: "mf",
936 },
937 ]);
938 }).pipe(Effect.provide(layerTestCrypto)),
939 );
940
941 it.effect("dismisses a pending user-input request", () =>
942 Effect.gen(function* () {
943 const commands: OrchestrationV2Command[] = [];
944 const supervisor = yield* makeSupervisor({ commands, projects: [] });
945
946 yield* dismissThreadUserInput({
947 commandId: CommandId.make("dismiss-command"),
948 threadId: v2ThreadId,
949 requestId: RuntimeRequestId.make("request-1"),
950 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
951
952 expect(commands).toEqual([
953 {
954 type: "thread.user-input.dismiss",
955 commandId: "dismiss-command",
956 threadId: v2ThreadId,
957 requestId: "request-1",
958 },
959 ]);
960 }).pipe(Effect.provide(layerTestCrypto)),
961 );
962
963 it.effect("dispatches an explicit idle start without fetching the full projection", () =>
964 Effect.gen(function* () {
965 const commands: OrchestrationV2Command[] = [];
966 const projectionRequests: ThreadId[] = [];
967 const supervisor = yield* makeSupervisor({
968 commands,
969 projects: [],
970 projectionRequests,
971 });
972
973 yield* startThreadTurn({
974 commandId: CommandId.make("direct-start"),
975 threadId: v2ThreadId,
976 message: {
977 messageId: MessageId.make("direct-start-message"),
978 role: "user",
979 text: "continue",
980 attachments: [],
981 },
982 runtimeMode: "full-access",
983 interactionMode: "default",
984 dispatchMode: "start",
985 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
986
987 expect(projectionRequests).toEqual([]);
988 expect(commands).toMatchObject([
989 {
990 type: "message.dispatch",
991 threadId: v2ThreadId,
992 dispatchMode: { type: "start_immediately" },
993 },
994 ]);
995 }).pipe(Effect.provide(layerTestCrypto)),
996 );
997
998 it.effect(
999 "a native subagent stop targets its owning run rather than holding the parent queue",
1000 () =>
1001 Effect.gen(function* () {
1002 const subagentId = NodeId.make("native-subagent");
1003 const runId = RunId.make("settled-owner-run");
1004 const commands: OrchestrationV2Command[] = [];
1005 const supervisor = yield* makeSupervisor({
1006 commands,
1007 projects: [],
1008 projection: {
1009 ...v2Projection,
1010 subagents: [
1011 {
1012 id: subagentId,
1013 threadId: v2ThreadId,
1014 runId,
1015 parentNodeId: NodeId.make("owner-node"),
1016 origin: "provider_native",
1017 createdBy: "agent",
1018 driver: ProviderDriverKind.make("claudeAgent"),
1019 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
1020 providerThreadId: null,
1021 childThreadId: ThreadId.make("native-child-thread"),
1022 nativeTaskRef: null,
1023 prompt: "Work",
1024 title: null,
1025 model: null,
1026 result: null,
1027 status: "running",
1028 startedAt: v2Now,
1029 completedAt: null,
1030 updatedAt: v2Now,
1031 },
1032 ],
1033 },
1034 });
1035 yield* interruptThreadTurn({
1036 commandId: CommandId.make("native-stop"),
1037 threadId: v2ThreadId,
1038 subagentId,
1039 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
1040 expect(commands).toEqual([
1041 {
1042 type: "subagent.stop",
1043 commandId: "native-stop",
1044 threadId: v2ThreadId,
1045 runId,
1046 subagentId,
1047 },
1048 ]);
1049 }).pipe(Effect.provide(layerTestCrypto)),
1050 );
1051
1052 it.effect("interrupts a known run without fetching the full projection", () =>
1053 Effect.gen(function* () {
1054 const commands: OrchestrationV2Command[] = [];
1055 const projectionRequests: ThreadId[] = [];
1056 const supervisor = yield* makeSupervisor({
1057 commands,
1058 projects: [],
1059 projectionRequests,
1060 });
1061
1062 yield* interruptThreadTurn({
1063 commandId: CommandId.make("direct-interrupt"),
1064 threadId: v2ThreadId,
1065 runId: RunId.make("active-run"),
1066 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
1067
1068 expect(projectionRequests).toEqual([]);
1069 expect(commands).toEqual([
1070 {
1071 type: "run.interrupt",
1072 commandId: "direct-interrupt",
1073 threadId: v2ThreadId,
1074 runId: "active-run",
1075 holdQueue: true,
1076 },
1077 ]);
1078 }).pipe(Effect.provide(layerTestCrypto)),
1079 );
1080});