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

commands.test.ts

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