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