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 ThreadId,
15 WS_METHODS,
16 type OrchestrationV2Command,
17 type OrchestrationV2ThreadLaunchInput,
18 type OrchestrationV2ThreadProjection,
19 type ProjectMutation,
20} from "@t3tools/contracts";
21import { describe, expect, it } from "@effect/vitest";
22import * as Crypto from "effect/Crypto";
23import * as DateTime from "effect/DateTime";
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 createProject,
41 forkThreadFromRun,
42 mergeThreadBack,
43 promoteQueuedRun,
44 reorderQueuedRun,
45 revertThreadCheckpoint,
46 startThreadTurn,
47 updateThreadMetadata,
48} from "./commands.ts";
49
50const TEST_CRYPTO_LAYER = Layer.succeed(
51 Crypto.Crypto,
52 Crypto.make({
53 randomBytes: (size) => new Uint8Array(size),
54 digest: (_algorithm, data) => Effect.succeed(data),
55 }),
56);
57
58const TARGET = new PrimaryConnectionTarget({
59 environmentId: EnvironmentId.make("environment-1"),
60 label: "Test environment",
61 httpBaseUrl: "https://environment.example.test",
62 wsBaseUrl: "wss://environment.example.test",
63});
64
65const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
66 readonly commands: OrchestrationV2Command[];
67 readonly projects: ProjectMutation[];
68 readonly launches?: OrchestrationV2ThreadLaunchInput[];
69 readonly projection?: OrchestrationV2ThreadProjection;
70}) {
71 const client = {
72 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
73 Effect.sync(() => {
74 input.commands.push(command);
75 return { sequence: input.commands.length };
76 }),
77 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: () =>
78 Effect.succeed(input.projection ?? v2Projection),
79 [ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) =>
80 Effect.sync(() => {
81 input.launches?.push(launchInput);
82 return {
83 threadId: launchInput.threadId ?? v2ThreadId,
84 projection: input.projection ?? v2Projection,
85 resumed: false,
86 };
87 }),
88 [WS_METHODS.projectsMutate]: (mutation: ProjectMutation) =>
89 Effect.sync(() => {
90 input.projects.push(mutation);
91 return {
92 id: mutation.projectId,
93 title: mutation.type === "project.create" ? mutation.title : "Project",
94 workspaceRoot:
95 mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project",
96 repositoryIdentity: null,
97 faviconPath: null,
98 defaultModelSelection: null,
99 scripts: [],
100 createdAt: "2026-06-06T00:00:00.000Z",
101 updatedAt: "2026-06-06T00:00:00.000Z",
102 deletedAt: null,
103 };
104 }),
105 } as unknown as WsRpcProtocolClient;
106 const session: RpcSession.RpcSession = {
107 client,
108 initialConfig: Effect.never,
109 ready: Effect.void,
110 probe: Effect.void,
111 closed: Effect.never,
112 };
113 return EnvironmentSupervisor.EnvironmentSupervisor.of({
114 target: TARGET,
115 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
116 session: yield* SubscriptionRef.make(Option.some(session)),
117 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
118 connect: Effect.void,
119 disconnect: Effect.void,
120 retryNow: Effect.void,
121 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
122});
123
124describe("V2 environment commands", () => {
125 it.effect("routes projects through the event-sourced project transport", () =>
126 Effect.gen(function* () {
127 const projects: ProjectMutation[] = [];
128 const supervisor = yield* makeSupervisor({ commands: [], projects });
129
130 yield* createProject({
131 projectId: ProjectId.make("project-1"),
132 title: "Project",
133 workspaceRoot: "/workspace/project",
134 createWorkspaceRootIfMissing: true,
135 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
136
137 expect(projects).toEqual([
138 {
139 type: "project.create",
140 commandId: "00000000-0000-4000-8000-000000000000",
141 projectId: "project-1",
142 title: "Project",
143 workspaceRoot: "/workspace/project",
144 createWorkspaceRootIfMissing: true,
145 },
146 ]);
147 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
148 );
149
150 it.effect("preserves caller command ids for idempotent V2 commands", () =>
151 Effect.gen(function* () {
152 const commands: OrchestrationV2Command[] = [];
153 const supervisor = yield* makeSupervisor({ commands, projects: [] });
154
155 yield* archiveThread({
156 commandId: CommandId.make("queued-command"),
157 threadId: ThreadId.make("thread-1"),
158 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
159
160 expect(commands).toEqual([
161 { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
162 ]);
163 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
164 );
165
166 it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () =>
167 Effect.gen(function* () {
168 const scopeId = CheckpointScopeId.make("checkpoint-scope-root");
169 const checkpointId = CheckpointId.make("checkpoint-thread-start");
170 const projection: OrchestrationV2ThreadProjection = {
171 ...v2Projection,
172 checkpoints: [
173 {
174 id: checkpointId,
175 threadId: v2ThreadId,
176 scopeId,
177 runId: null,
178 nodeId: NodeId.make("node-run-1"),
179 parentCheckpointId: null,
180 ordinalWithinScope: 0,
181 appRunOrdinal: null,
182 ref: CheckpointRef.make("refs/t3/thread-start"),
183 status: "ready",
184 files: [],
185 capturedAt: v2Now,
186 },
187 ],
188 };
189 const commands: OrchestrationV2Command[] = [];
190 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
191
192 yield* revertThreadCheckpoint({
193 commandId: CommandId.make("rollback-thread-start"),
194 threadId: v2ThreadId,
195 turnCount: 0,
196 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
197
198 expect(commands).toEqual([
199 {
200 type: "checkpoint.rollback",
201 commandId: "rollback-thread-start",
202 threadId: v2ThreadId,
203 scopeId,
204 checkpointId,
205 },
206 ]);
207 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
208 );
209
210 it.effect("preserves plan implementation provenance on V2 runs", () =>
211 Effect.gen(function* () {
212 const commands: OrchestrationV2Command[] = [];
213 const supervisor = yield* makeSupervisor({ commands, projects: [] });
214
215 yield* startThreadTurn({
216 commandId: CommandId.make("implement-plan"),
217 threadId: v2ThreadId,
218 message: {
219 messageId: MessageId.make("message-implementation"),
220 role: "user",
221 text: "Implement the plan",
222 attachments: [],
223 },
224 modelSelection: {
225 instanceId: ProviderInstanceId.make("codex"),
226 model: "gpt-5.4",
227 },
228 runtimeMode: "full-access",
229 interactionMode: "default",
230 sourceProposedPlan: {
231 threadId: ThreadId.make("thread-plan"),
232 planId: PlanId.make("plan-1"),
233 },
234 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
235
236 expect(commands).toHaveLength(1);
237 expect(commands[0]).toMatchObject({
238 type: "message.dispatch",
239 commandId: "implement-plan",
240 threadId: v2ThreadId,
241 sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" },
242 dispatchMode: { type: "start_immediately" },
243 });
244 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
245 );
246
247 it.effect("preserves an existing worktree and branch during first-message launch", () =>
248 Effect.gen(function* () {
249 const launches: OrchestrationV2ThreadLaunchInput[] = [];
250 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
251
252 yield* startThreadTurn({
253 commandId: CommandId.make("launch-existing-worktree"),
254 threadId: v2ThreadId,
255 message: {
256 messageId: MessageId.make("message-existing-worktree"),
257 role: "user",
258 text: "Continue here",
259 attachments: [],
260 },
261 runtimeMode: "full-access",
262 interactionMode: "default",
263 bootstrap: {
264 createThread: {
265 projectId: ProjectId.make("project-1"),
266 title: "Thread",
267 modelSelection: v2Projection.thread.modelSelection,
268 runtimeMode: "full-access",
269 interactionMode: "default",
270 branch: "feature",
271 worktreePath: "/workspace/project-worktrees/feature",
272 createdAt: "2026-06-20T00:00:00.000Z",
273 },
274 },
275 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
276
277 expect(launches[0]).toMatchObject({
278 threadId: v2ThreadId,
279 workspaceStrategy: {
280 type: "existing_worktree",
281 worktreePath: "/workspace/project-worktrees/feature",
282 branch: "feature",
283 },
284 });
285 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
286 );
287
288 it.effect("provisions an origin-based worktree for an existing empty thread", () =>
289 Effect.gen(function* () {
290 const launches: OrchestrationV2ThreadLaunchInput[] = [];
291 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
292
293 yield* startThreadTurn({
294 commandId: CommandId.make("launch-existing-thread-worktree"),
295 threadId: v2ThreadId,
296 message: {
297 messageId: MessageId.make("message-existing-thread-worktree"),
298 role: "user",
299 text: "Move to a worktree",
300 attachments: [],
301 },
302 runtimeMode: "full-access",
303 interactionMode: "default",
304 bootstrap: {
305 prepareWorktree: {
306 projectCwd: "/workspace/project",
307 baseBranch: "main",
308 branch: "feature",
309 startFromOrigin: true,
310 },
311 },
312 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
313
314 expect(launches[0]).toMatchObject({
315 threadId: v2ThreadId,
316 reuseExistingThread: true,
317 projectId: v2Projection.thread.projectId,
318 workspaceStrategy: {
319 type: "worktree",
320 baseRef: "main",
321 branch: "feature",
322 startFromOrigin: true,
323 },
324 });
325 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
326 );
327
328 it.effect("maps explicit active-run delivery modes to V2 dispatch semantics", () =>
329 Effect.gen(function* () {
330 const activeRunId = RunId.make("run-active");
331 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
332 const projection: OrchestrationV2ThreadProjection = {
333 ...v2Projection,
334 runs: [
335 {
336 id: activeRunId,
337 threadId: v2ThreadId,
338 ordinal: 1,
339 providerInstanceId: v2Projection.thread.providerInstanceId,
340 modelSelection: v2Projection.thread.modelSelection,
341 providerThreadId: null,
342 userMessageId: MessageId.make("message-active"),
343 rootNodeId: null,
344 activeAttemptId: null,
345 status: "running",
346 requestedAt: now,
347 startedAt: now,
348 completedAt: null,
349 checkpointId: null,
350 contextHandoffId: null,
351 },
352 ],
353 };
354 const commands: OrchestrationV2Command[] = [];
355 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
356
357 for (const [mode, expectedType] of [
358 ["queue", "queue_after_active"],
359 ["steer", "steer_active"],
360 ["restart", "restart_active"],
361 ] as const) {
362 yield* startThreadTurn({
363 commandId: CommandId.make(`command-${mode}`),
364 threadId: v2ThreadId,
365 message: {
366 messageId: MessageId.make(`message-${mode}`),
367 role: "user",
368 text: mode,
369 attachments: [],
370 },
371 runtimeMode: "full-access",
372 interactionMode: "default",
373 dispatchMode: mode,
374 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
375
376 expect(commands.at(-1)).toMatchObject({
377 type: "message.dispatch",
378 dispatchMode: {
379 type: expectedType,
380 ...(mode === "queue" ? {} : { targetRunId: activeRunId }),
381 },
382 });
383 }
384 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
385 );
386
387 it.effect(
388 "dispatches V2-native relationship and queue commands without compatibility shaping",
389 () =>
390 Effect.gen(function* () {
391 const commands: OrchestrationV2Command[] = [];
392 const supervisor = yield* makeSupervisor({ commands, projects: [] });
393 const provide = Effect.provideService(
394 EnvironmentSupervisor.EnvironmentSupervisor,
395 supervisor,
396 );
397
398 yield* forkThreadFromRun({
399 commandId: CommandId.make("fork"),
400 sourceThreadId: v2ThreadId,
401 targetThreadId: ThreadId.make("thread-fork"),
402 runId: RunId.make("run-1"),
403 }).pipe(provide);
404 yield* mergeThreadBack({
405 commandId: CommandId.make("merge"),
406 sourceThreadId: ThreadId.make("thread-fork"),
407 targetThreadId: v2ThreadId,
408 runId: RunId.make("run-2"),
409 }).pipe(provide);
410 yield* reorderQueuedRun({
411 commandId: CommandId.make("reorder"),
412 threadId: v2ThreadId,
413 runId: RunId.make("run-3"),
414 beforeRunId: RunId.make("run-4"),
415 }).pipe(provide);
416 yield* promoteQueuedRun({
417 commandId: CommandId.make("promote"),
418 threadId: v2ThreadId,
419 queuedRunId: RunId.make("run-3"),
420 targetRunId: RunId.make("run-active"),
421 }).pipe(provide);
422
423 expect(commands).toMatchObject([
424 { type: "thread.fork", sourcePoint: { type: "run", runId: "run-1" } },
425 { type: "thread.merge_back", sourcePoint: { type: "run", runId: "run-2" } },
426 { type: "queued-run.reorder", runId: "run-3", beforeRunId: "run-4" },
427 {
428 type: "queued-message.promote-to-steer",
429 queuedRunId: "run-3",
430 targetRunId: "run-active",
431 },
432 ]);
433 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
434 );
435
436 it.effect("uses provider.switch when model selection changes provider instance", () =>
437 Effect.gen(function* () {
438 const commands: OrchestrationV2Command[] = [];
439 const supervisor = yield* makeSupervisor({ commands, projects: [] });
440
441 yield* updateThreadMetadata({
442 commandId: CommandId.make("switch-provider"),
443 threadId: v2ThreadId,
444 modelSelection: {
445 instanceId: ProviderInstanceId.make("claude"),
446 model: "claude-sonnet-4-6",
447 },
448 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
449
450 expect(commands).toEqual([
451 {
452 type: "provider.switch",
453 commandId: "switch-provider",
454 threadId: v2ThreadId,
455 modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },
456 },
457 ]);
458 }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
459 );
460});