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