Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

commands.test.ts

972 lines33.5 KB

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 },
576 ],
577 );
578 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
579 );
580 }
581​
582 it.effect(
583 "dispatches V2-native relationship and queue commands without compatibility shaping",
584 () =>
585 Effect.gen(function* () {
586 const commands: OrchestrationV2Command[] = [];
587 const supervisor = yield* makeSupervisor({ commands, projects: [] });
588 const provide = Effect.provideService(
589 EnvironmentSupervisor.EnvironmentSupervisor,
590 supervisor,
591 );
592​
593 yield* forkThreadFromRun({
594 commandId: CommandId.make("fork"),
595 sourceThreadId: v2ThreadId,
596 targetThreadId: ThreadId.make("thread-fork"),
597 runId: RunId.make("run-1"),
598 }).pipe(provide);
599 yield* mergeThreadBack({
600 commandId: CommandId.make("merge"),
601 sourceThreadId: ThreadId.make("thread-fork"),
602 targetThreadId: v2ThreadId,
603 runId: RunId.make("run-2"),
604 }).pipe(provide);
605 yield* reorderQueuedRun({
606 commandId: CommandId.make("reorder"),
607 threadId: v2ThreadId,
608 runId: RunId.make("run-3"),
609 beforeRunId: RunId.make("run-4"),
610 }).pipe(provide);
611 yield* promoteQueuedRun({
612 commandId: CommandId.make("promote"),
613 threadId: v2ThreadId,
614 queuedRunId: RunId.make("run-3"),
615 targetRunId: RunId.make("run-active"),
616 }).pipe(provide);
617 yield* cancelQueuedRun({
618 commandId: CommandId.make("cancel"),
619 threadId: v2ThreadId,
620 runId: RunId.make("run-3"),
621 }).pipe(provide);
622 yield* editQueuedRun({
623 commandId: CommandId.make("edit"),
624 threadId: v2ThreadId,
625 runId: RunId.make("run-3"),
626 text: "updated queued text",
627 }).pipe(provide);
628 yield* editQueuedRun({
629 commandId: CommandId.make("edit-attachments"),
630 threadId: v2ThreadId,
631 runId: RunId.make("run-3"),
632 text: "updated queued text with attachments",
633 edit: {
634 messageId: MessageId.make("message-3"),
635 attachments: [
636 {
637 type: "image",
638 id: "attachment-kept",
639 name: "kept.png",
640 mimeType: "image/png",
641 sizeBytes: 64,
642 },
643 ],
644 },
645 }).pipe(provide);
646​
647 expect(commands).toMatchObject([
648 { type: "thread.fork", sourcePoint: { type: "run", runId: "run-1" } },
649 { type: "thread.merge_back", sourcePoint: { type: "run", runId: "run-2" } },
650 { type: "queued-run.reorder", runId: "run-3", beforeRunId: "run-4" },
651 {
652 type: "queued-message.promote-to-steer",
653 queuedRunId: "run-3",
654 targetRunId: "run-active",
655 },
656 { type: "queued-run.cancel", runId: "run-3" },
657 { type: "queued-run.edit", runId: "run-3", text: "updated queued text" },
658 {
659 type: "queued-run.edit",
660 runId: "run-3",
661 text: "updated queued text with attachments",
662 attachments: [{ id: "attachment-kept" }],
663 },
664 ]);
665 // A text-only edit must not send an attachments replacement list.
666 expect(commands[5]).not.toHaveProperty("attachments");
667 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
668 );
669​
670 it.effect("delegates model selection to the server without fetching the full projection", () =>
671 Effect.gen(function* () {
672 const commands: OrchestrationV2Command[] = [];
673 const projectionRequests: ThreadId[] = [];
674 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
675​
676 yield* updateThreadMetadata({
677 commandId: CommandId.make("same-provider"),
678 threadId: v2ThreadId,
679 modelSelection: {
680 instanceId: ProviderInstanceId.make("codex"),
681 model: "another-model",
682 },
683 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
684​
685 yield* updateThreadMetadata({
686 commandId: CommandId.make("switch-provider"),
687 threadId: v2ThreadId,
688 modelSelection: {
689 instanceId: ProviderInstanceId.make("claude"),
690 model: "claude-sonnet-4-6",
691 },
692 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
693​
694 expect(commands).toEqual([
695 {
696 type: "thread.model-selection.set",
697 commandId: "same-provider",
698 threadId: v2ThreadId,
699 modelSelection: { instanceId: "codex", model: "another-model" },
700 },
701 {
702 type: "thread.model-selection.set",
703 commandId: "switch-provider",
704 threadId: v2ThreadId,
705 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
706 },
707 ]);
708 expect(projectionRequests).toEqual([]);
709 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
710 );
711​
712 it.effect("retains provider-switch shaping for servers without command context support", () =>
713 Effect.gen(function* () {
714 const commands: OrchestrationV2Command[] = [];
715 const projectionRequests: ThreadId[] = [];
716 const supervisor = yield* makeSupervisor({
717 commands,
718 projects: [],
719 projectionRequests,
720 advertiseServerResolvedCommandContext: false,
721 });
722​
723 yield* updateThreadMetadata({
724 commandId: CommandId.make("legacy-switch-provider"),
725 threadId: v2ThreadId,
726 modelSelection: {
727 instanceId: ProviderInstanceId.make("claude"),
728 model: "claude-sonnet-4-6",
729 },
730 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
731​
732 expect(projectionRequests).toEqual([v2ThreadId]);
733 expect(commands).toEqual([
734 {
735 type: "provider.switch",
736 commandId: "legacy-switch-provider",
737 threadId: v2ThreadId,
738 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
739 },
740 ]);
741 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
742 );
743​
744 it.effect.each([true, false])(
745 "rolls back an identified checkpoint without fetching the full projection, restoreFiles=%s",
746 (restoreFiles) =>
747 Effect.gen(function* () {
748 const commands: OrchestrationV2Command[] = [];
749 const projectionRequests: ThreadId[] = [];
750 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
751​
752 yield* revertThreadCheckpoint({
753 commandId: CommandId.make("rollback-known-checkpoint"),
754 threadId: v2ThreadId,
755 checkpointId: CheckpointId.make("checkpoint-known"),
756 scopeId: CheckpointScopeId.make("scope-known"),
757 restoreFiles,
758 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
759​
760 expect(projectionRequests).toEqual([]);
761 expect(commands).toEqual([
762 {
763 type: "checkpoint.rollback",
764 commandId: "rollback-known-checkpoint",
765 threadId: v2ThreadId,
766 checkpointId: "checkpoint-known",
767 scopeId: "scope-known",
768 restoreFiles,
769 },
770 ]);
771 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
772 );
773​
774 it.effect("validates identified checkpoints locally for older servers", () =>
775 Effect.gen(function* () {
776 const checkpointId = CheckpointId.make("legacy-checkpoint");
777 const scopeId = CheckpointScopeId.make("legacy-checkpoint-scope");
778 for (const status of ["ready", "missing", "error", "stale", null] as const) {
779 const commands: OrchestrationV2Command[] = [];
780 const projectionRequests: ThreadId[] = [];
781 const supervisor = yield* makeSupervisor({
782 commands,
783 projects: [],
784 projectionRequests,
785 advertiseServerResolvedCommandContext: false,
786 projection: {
787 ...v2Projection,
788 checkpoints:
789 status === null
790 ? []
791 : [
792 {
793 id: checkpointId,
794 threadId: v2ThreadId,
795 scopeId,
796 runId: null,
797 nodeId: NodeId.make("legacy-checkpoint-node"),
798 parentCheckpointId: null,
799 ordinalWithinScope: 0,
800 appRunOrdinal: null,
801 ref: CheckpointRef.make("refs/t3/legacy-checkpoint"),
802 status,
803 files: [],
804 capturedAt: v2Now,
805 },
806 ],
807 },
808 });
809 const rollback = revertThreadCheckpoint({
810 commandId: CommandId.make(`legacy-rollback-${status}`),
811 threadId: v2ThreadId,
812 checkpointId,
813 scopeId,
814 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
815​
816 if (status === "ready") {
817 yield* rollback;
818 expect(commands).toEqual([
819 {
820 type: "checkpoint.rollback",
821 commandId: "legacy-rollback-ready",
822 threadId: v2ThreadId,
823 checkpointId,
824 scopeId,
825 },
826 ]);
827 } else {
828 const error = yield* rollback.pipe(Effect.flip);
829 expect(error._tag).toBe("OrchestrationV2CheckpointUnavailableError");
830 expect(commands).toEqual([]);
831 }
832 expect(projectionRequests).toEqual([v2ThreadId]);
833 }
834 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
835 );
836​
837 it.effect("dispatches settle and unsettle commands without timestamps", () =>
838 Effect.gen(function* () {
839 const dispatched: OrchestrationV2Command[] = [];
840 const supervisor = yield* makeSupervisor({ commands: dispatched, projects: [] });
841​
842 yield* settleThread({
843 commandId: CommandId.make("settle-command"),
844 threadId: ThreadId.make("thread-1"),
845 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
846 yield* unsettleThread({
847 commandId: CommandId.make("unsettle-command"),
848 threadId: ThreadId.make("thread-1"),
849 reason: "user",
850 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
851​
852 expect(dispatched).toEqual([
853 {
854 type: "thread.settle",
855 commandId: "settle-command",
856 threadId: "thread-1",
857 },
858 {
859 type: "thread.unsettle",
860 commandId: "unsettle-command",
861 threadId: "thread-1",
862 reason: "user",
863 },
864 ]);
865 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
866 );
867​
868 it.effect("sends an active order key without changing activity timestamps", () =>
869 Effect.gen(function* () {
870 const dispatched: OrchestrationV2Command[] = [];
871 const supervisor = yield* makeSupervisor({ commands: dispatched, projects: [] });
872 yield* reorderActiveThread({
873 commandId: CommandId.make("reorder-command"),
874 threadId: ThreadId.make("thread-1"),
875 orderKey: "mf",
876 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
877 expect(dispatched).toEqual([
878 {
879 type: "thread.active.reorder",
880 commandId: "reorder-command",
881 threadId: "thread-1",
882 orderKey: "mf",
883 },
884 ]);
885 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
886 );
887​
888 it.effect("dismisses a pending user-input request", () =>
889 Effect.gen(function* () {
890 const commands: OrchestrationV2Command[] = [];
891 const supervisor = yield* makeSupervisor({ commands, projects: [] });
892​
893 yield* dismissThreadUserInput({
894 commandId: CommandId.make("dismiss-command"),
895 threadId: v2ThreadId,
896 requestId: RuntimeRequestId.make("request-1"),
897 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
898​
899 expect(commands).toEqual([
900 {
901 type: "thread.user-input.dismiss",
902 commandId: "dismiss-command",
903 threadId: v2ThreadId,
904 requestId: "request-1",
905 },
906 ]);
907 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
908 );
909​
910 it.effect("dispatches an explicit idle start without fetching the full projection", () =>
911 Effect.gen(function* () {
912 const commands: OrchestrationV2Command[] = [];
913 const projectionRequests: ThreadId[] = [];
914 const supervisor = yield* makeSupervisor({
915 commands,
916 projects: [],
917 projectionRequests,
918 });
919​
920 yield* startThreadTurn({
921 commandId: CommandId.make("direct-start"),
922 threadId: v2ThreadId,
923 message: {
924 messageId: MessageId.make("direct-start-message"),
925 role: "user",
926 text: "continue",
927 attachments: [],
928 },
929 runtimeMode: "full-access",
930 interactionMode: "default",
931 dispatchMode: "start",
932 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
933​
934 expect(projectionRequests).toEqual([]);
935 expect(commands).toMatchObject([
936 {
937 type: "message.dispatch",
938 threadId: v2ThreadId,
939 dispatchMode: { type: "start_immediately" },
940 },
941 ]);
942 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
943 );
944​
945 it.effect("interrupts a known run without fetching the full projection", () =>
946 Effect.gen(function* () {
947 const commands: OrchestrationV2Command[] = [];
948 const projectionRequests: ThreadId[] = [];
949 const supervisor = yield* makeSupervisor({
950 commands,
951 projects: [],
952 projectionRequests,
953 });
954​
955 yield* interruptThreadTurn({
956 commandId: CommandId.make("direct-interrupt"),
957 threadId: v2ThreadId,
958 runId: RunId.make("active-run"),
959 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
960​
961 expect(projectionRequests).toEqual([]);
962 expect(commands).toEqual([
963 {
964 type: "run.interrupt",
965 commandId: "direct-interrupt",
966 threadId: v2ThreadId,
967 runId: "active-run",
968 },
969 ]);
970 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
971 );
972});