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