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

commands.test.ts

564 lines19.2 KB

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