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

commands.test.ts

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