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 ProjectId,
11 ProviderInstanceId,
12 ProviderDriverKind,
13 RunId,
14 ThreadId,
15 TurnItemId,
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 SecureRandom from "effect/crypto/SecureRandom";
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 interruptThreadTurn,
41 revertThreadCheckpoint,
42 resumeThreadQueue,
43 startThreadTurn,
44} from "./commands.ts";
45
46const layerTestRandom = Layer.succeed(
47 SecureRandom.SecureRandom,
48 SecureRandom.make((size) => new Uint8Array(size)),
49);
50
51const TARGET = new PrimaryConnectionTarget({
52 environmentId: EnvironmentId.make("environment-1"),
53 label: "Test environment",
54 httpBaseUrl: "https://environment.example.test",
55 wsBaseUrl: "wss://environment.example.test",
56});
57
58const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
59 readonly commands: OrchestrationV2Command[];
60 readonly projects: ProjectMutation[];
61 readonly launches?: OrchestrationV2ThreadLaunchInput[];
62 readonly projection?: OrchestrationV2ThreadProjection;
63 readonly projectionRequests?: ThreadId[];
64 readonly advertiseThreadStop?: boolean;
65}) {
66 const client = {
67 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
68 Effect.sync(() => {
69 input.commands.push(command);
70 return { sequence: input.commands.length };
71 }),
72 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (requestInput: {
73 readonly threadId: ThreadId;
74 }) =>
75 Effect.sync(() => {
76 input.projectionRequests?.push(requestInput.threadId);
77 return input.projection ?? v2Projection;
78 }),
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.succeed({
109 environment: {
110 capabilities: {
111 repositoryIdentity: true,
112 ...(input.advertiseThreadStop === true ? { threadStop: true } : {}),
113 },
114 },
115 } as never),
116 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
117 ready: Effect.void,
118 probe: Effect.void,
119 inboundFrames: Effect.succeed(0),
120 closed: Effect.never,
121 };
122 return EnvironmentSupervisor.EnvironmentSupervisor.of({
123 target: TARGET,
124 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
125 session: yield* SubscriptionRef.make(Option.some(session)),
126 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
127 connect: Effect.void,
128 disconnect: Effect.void,
129 retryNow: Effect.void,
130 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
131});
132
133describe("V2 environment commands", () => {
134 it.effect("distinguishes sending a selected queued message from resuming queue order", () =>
135 Effect.gen(function* () {
136 const commands: OrchestrationV2Command[] = [];
137 const supervisor = yield* makeSupervisor({ commands, projects: [] });
138 const threadId = ThreadId.make("thread-1");
139 yield* resumeThreadQueue({
140 commandId: CommandId.make("send-selected"),
141 threadId,
142 runId: RunId.make("selected"),
143 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
144 yield* resumeThreadQueue({
145 commandId: CommandId.make("resume-queue"),
146 threadId,
147 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
148
149 expect(commands).toEqual([
150 { type: "queued-run.start", commandId: "send-selected", threadId, runId: "selected" },
151 { type: "queue.resume", commandId: "resume-queue", threadId },
152 ]);
153 }).pipe(Effect.provide(layerTestRandom)),
154 );
155
156 it.effect("preserves caller command ids for idempotent V2 commands", () =>
157 Effect.gen(function* () {
158 const commands: OrchestrationV2Command[] = [];
159 const supervisor = yield* makeSupervisor({ commands, projects: [] });
160
161 yield* archiveThread({
162 commandId: CommandId.make("queued-command"),
163 threadId: ThreadId.make("thread-1"),
164 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
165
166 expect(commands).toEqual([
167 { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
168 ]);
169 }).pipe(Effect.provide(layerTestRandom)),
170 );
171
172 it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () =>
173 Effect.gen(function* () {
174 const scopeId = CheckpointScopeId.make("checkpoint-scope-root");
175 const checkpointId = CheckpointId.make("checkpoint-thread-start");
176 const projection: OrchestrationV2ThreadProjection = {
177 ...v2Projection,
178 checkpoints: [
179 {
180 id: checkpointId,
181 threadId: v2ThreadId,
182 scopeId,
183 runId: null,
184 nodeId: NodeId.make("node-run-1"),
185 parentCheckpointId: null,
186 ordinalWithinScope: 0,
187 appRunOrdinal: null,
188 ref: CheckpointRef.make("refs/t3/thread-start"),
189 status: "ready",
190 files: [],
191 capturedAt: v2Now,
192 },
193 ],
194 };
195 const commands: OrchestrationV2Command[] = [];
196 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
197
198 yield* revertThreadCheckpoint({
199 commandId: CommandId.make("rollback-thread-start"),
200 threadId: v2ThreadId,
201 turnCount: 0,
202 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
203
204 expect(commands).toEqual([
205 {
206 type: "checkpoint.rollback",
207 commandId: "rollback-thread-start",
208 threadId: v2ThreadId,
209 scopeId,
210 checkpointId,
211 },
212 ]);
213 }).pipe(Effect.provide(layerTestRandom)),
214 );
215
216 it.effect("preserves an existing worktree and branch during first-message launch", () =>
217 Effect.gen(function* () {
218 const launches: OrchestrationV2ThreadLaunchInput[] = [];
219 const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
220
221 yield* startThreadTurn({
222 commandId: CommandId.make("launch-existing-worktree"),
223 threadId: v2ThreadId,
224 message: {
225 messageId: MessageId.make("message-existing-worktree"),
226 role: "user",
227 text: "Continue here",
228 attachments: [],
229 },
230 runtimeMode: "full-access",
231 interactionMode: "default",
232 titleSeed: "Continue here",
233 bootstrap: {
234 createThread: {
235 projectId: ProjectId.make("project-1"),
236 title: "Thread",
237 modelSelection: v2Projection.thread.modelSelection,
238 runtimeMode: "full-access",
239 interactionMode: "default",
240 branch: "feature",
241 worktreePath: "/workspace/project-worktrees/feature",
242 createdAt: "2026-06-20T00:00:00.000Z",
243 },
244 },
245 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
246
247 expect(launches[0]).toMatchObject({
248 threadId: v2ThreadId,
249 title: "Continue here",
250 generateTitle: true,
251 workspaceStrategy: {
252 type: "existing_worktree",
253 worktreePath: "/workspace/project-worktrees/feature",
254 branch: "feature",
255 },
256 });
257 }).pipe(Effect.provide(layerTestRandom)),
258 );
259
260 it.effect("uses server-resolved delivery intent without fetching the full projection", () =>
261 Effect.gen(function* () {
262 const commands: OrchestrationV2Command[] = [];
263 const projectionRequests: ThreadId[] = [];
264 const supervisor = yield* makeSupervisor({ commands, projects: [], projectionRequests });
265
266 for (const [mode, expectedType] of [
267 ["queue", "queue_after_active"],
268 ["auto", "start_immediately"],
269 ["steer", "start_immediately"],
270 ["restart", "start_immediately"],
271 ] as const) {
272 yield* startThreadTurn({
273 commandId: CommandId.make(`command-${mode}`),
274 threadId: v2ThreadId,
275 message: {
276 messageId: MessageId.make(`message-${mode}`),
277 role: "user",
278 text: mode,
279 attachments: [],
280 },
281 runtimeMode: "full-access",
282 interactionMode: "default",
283 dispatchMode: mode,
284 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
285
286 expect(commands.at(-1)).toMatchObject({
287 type: "message.dispatch",
288 dispatchMode: { type: expectedType },
289 ...(mode === "queue" ? {} : { deliveryIntent: mode }),
290 });
291 }
292 expect(projectionRequests).toEqual([]);
293 }).pipe(Effect.provide(layerTestRandom)),
294 );
295
296 it.effect("Stop with no run left ends the thread's pull request watches", () =>
297 Effect.gen(function* () {
298 const link = {
299 host: "github.com",
300 repository: "pingdotgg/t3code",
301 url: "https://github.com/pingdotgg/t3code/pull/7",
302 source: "agent" as const,
303 linkedAt: "2026-10-05T00:00:00.000Z",
304 snapshot: null,
305 stack: null,
306 };
307 const watch = {
308 startedAt: "2026-10-05T00:00:00.000Z",
309 headSha: null,
310 failedChecks: [],
311 passed: false,
312 passedChecks: [],
313 remarksThrough: "2026-10-05T00:00:00.000Z",
314 remarkIds: [],
315 conflicting: false,
316 wakes: 0,
317 };
318 const projection: OrchestrationV2ThreadProjection = {
319 ...v2Projection,
320 thread: {
321 ...v2Projection.thread,
322 pullRequests: [
323 { ...link, number: 7, watch },
324 { ...link, number: 8 },
325 { ...link, number: 9, source: "stack-dismissed", watch },
326 ],
327 },
328 };
329 const commands: OrchestrationV2Command[] = [];
330 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
331
332 yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
333 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
334 );
335
336 expect(commands).toEqual([
337 {
338 type: "thread.pull-request.watch",
339 commandId: expect.any(String),
340 threadId: v2ThreadId,
341 host: "github.com",
342 repository: "pingdotgg/t3code",
343 number: 7,
344 watching: false,
345 },
346 ]);
347 }).pipe(Effect.provide(layerTestRandom)),
348 );
349
350 it.effect.each(["waiting", "completed", "rolled_back"] as const)(
351 "dispatches Stop for %s runs with background commands except rollback",
352 (status) =>
353 Effect.gen(function* () {
354 const waitingRunId = RunId.make("run-waiting");
355 const projection: OrchestrationV2ThreadProjection = {
356 ...v2Projection,
357 runs: [
358 {
359 id: waitingRunId,
360 threadId: v2ThreadId,
361 ordinal: 1,
362 providerInstanceId: v2Projection.thread.providerInstanceId,
363 modelSelection: v2Projection.thread.modelSelection,
364 providerThreadId: null,
365 userMessageId: MessageId.make("message-waiting"),
366 rootNodeId: null,
367 activeAttemptId: null,
368 status,
369 requestedAt: v2Now,
370 startedAt: v2Now,
371 completedAt: null,
372 checkpointId: null,
373 contextHandoffId: null,
374 },
375 ],
376 turnItems: [
377 {
378 id: TurnItemId.make("background-command"),
379 threadId: v2ThreadId,
380 runId: waitingRunId,
381 nodeId: null,
382 providerThreadId: null,
383 providerTurnId: null,
384 nativeItemRef: null,
385 parentItemId: null,
386 ordinal: 1,
387 status: "running",
388 title: null,
389 startedAt: v2Now,
390 completedAt: null,
391 updatedAt: v2Now,
392 type: "command_execution",
393 input: "vp run dev",
394 },
395 ],
396 };
397 const commands: OrchestrationV2Command[] = [];
398 const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
399
400 const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
401 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
402 );
403
404 expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
405 expect(commands).toEqual(
406 status === "rolled_back"
407 ? []
408 : [
409 {
410 type: "run.interrupt",
411 commandId: expect.any(String),
412 threadId: v2ThreadId,
413 runId: waitingRunId,
414 holdQueue: true,
415 },
416 ],
417 );
418 }).pipe(Effect.provide(layerTestRandom)),
419 );
420
421 it.effect(
422 "a native subagent stop targets its owning run rather than holding the parent queue",
423 () =>
424 Effect.gen(function* () {
425 const subagentId = NodeId.make("native-subagent");
426 const runId = RunId.make("settled-owner-run");
427 const commands: OrchestrationV2Command[] = [];
428 const supervisor = yield* makeSupervisor({
429 commands,
430 projects: [],
431 projection: {
432 ...v2Projection,
433 subagents: [
434 {
435 id: subagentId,
436 threadId: v2ThreadId,
437 runId,
438 parentNodeId: NodeId.make("owner-node"),
439 origin: "provider_native",
440 createdBy: "agent",
441 driver: ProviderDriverKind.make("claudeAgent"),
442 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
443 providerThreadId: null,
444 childThreadId: ThreadId.make("native-child-thread"),
445 nativeTaskRef: null,
446 prompt: "Work",
447 title: null,
448 model: null,
449 result: null,
450 status: "running",
451 startedAt: v2Now,
452 completedAt: null,
453 updatedAt: v2Now,
454 },
455 ],
456 },
457 });
458 yield* interruptThreadTurn({
459 commandId: CommandId.make("native-stop"),
460 threadId: v2ThreadId,
461 subagentId,
462 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
463 expect(commands).toEqual([
464 {
465 type: "subagent.stop",
466 commandId: "native-stop",
467 threadId: v2ThreadId,
468 runId,
469 subagentId,
470 },
471 ]);
472 }).pipe(Effect.provide(layerTestRandom)),
473 );
474
475 it.effect(
476 "an app-owned subagent stop asks the parent to clear an orphan, then stops the child",
477 () =>
478 Effect.gen(function* () {
479 const subagentId = NodeId.make("app-owned-subagent");
480 const runId = RunId.make("parent-run");
481 const childThreadId = ThreadId.make("app-owned-child-thread");
482 const commands: OrchestrationV2Command[] = [];
483 const supervisor = yield* makeSupervisor({
484 commands,
485 projects: [],
486 advertiseThreadStop: true,
487 projection: {
488 ...v2Projection,
489 subagents: [
490 {
491 id: subagentId,
492 threadId: v2ThreadId,
493 runId,
494 parentNodeId: NodeId.make("owner-node"),
495 origin: "app_owned",
496 createdBy: "agent",
497 driver: ProviderDriverKind.make("codex"),
498 providerInstanceId: ProviderInstanceId.make("codex"),
499 providerThreadId: null,
500 childThreadId,
501 nativeTaskRef: null,
502 prompt: "Work",
503 title: null,
504 model: null,
505 result: null,
506 status: "running",
507 startedAt: v2Now,
508 completedAt: null,
509 updatedAt: v2Now,
510 },
511 ],
512 },
513 });
514 yield* interruptThreadTurn({
515 commandId: CommandId.make("lineage-stop"),
516 threadId: v2ThreadId,
517 subagentId,
518 // A parent run must not be interrupted on the child thread.
519 runId,
520 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
521 expect(commands).toEqual([
522 {
523 type: "subagent.stop",
524 commandId: expect.any(String),
525 threadId: v2ThreadId,
526 runId,
527 subagentId,
528 },
529 { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId },
530 ]);
531 }).pipe(Effect.provide(layerTestRandom)),
532 );
533
534 it.effect("stops a thread without relying on background work in the history window", () =>
535 Effect.gen(function* () {
536 const commands: OrchestrationV2Command[] = [];
537 const projectionRequests: ThreadId[] = [];
538 const supervisor = yield* makeSupervisor({
539 commands,
540 projects: [],
541 projectionRequests,
542 advertiseThreadStop: true,
543 });
544
545 const result = yield* interruptThreadTurn({
546 commandId: CommandId.make("stop-outside-history-window"),
547 threadId: v2ThreadId,
548 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
549
550 expect(result).toEqual({ sequence: 1 });
551 expect(projectionRequests).toEqual([]);
552 expect(commands).toEqual([
553 {
554 type: "thread.stop",
555 commandId: "stop-outside-history-window",
556 threadId: v2ThreadId,
557 },
558 ]);
559 }).pipe(Effect.provide(layerTestRandom)),
560 );
561});