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

OpenCode2OrchestratorV2.integration.test.ts

1,181 lines46.9 KB

1/**
2 * OpenCode 2 through the whole orchestrator, against a replayed HTTP server:
3 * the transcript fixes the order of every request the adapter sends, so a
4 * request the orchestrator never lets it make fails the run.
5 */
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, describe, it } from "@effect/vitest";
8import {
9 CommandId,
10 MessageId,
11 type ModelSelection,
12 type OrchestrationV2Command,
13 type OrchestrationV2Run,
14 ProjectId,
15 type ProviderInteractionMode,
16 ProviderInstanceId,
17 type ProviderReplayEntry,
18 type RuntimeMode,
19 ThreadId,
20} from "@t3tools/contracts";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as FileSystem from "effect/FileSystem";
24import * as Path from "effect/Path";
25​
26import {
27 OPENCODE2_HTTP_PROTOCOL,
28 OpenCode2OrchestratorReplayHarness,
29} from "./Adapters/OpenCode2AdapterV2.testkit.ts";
30import { OPENCODE_PROVIDER } from "./Adapters/OpenCodeAdapterV2.ts";
31import { provideDeterministicTestRuntime } from "./testkit/DeterministicRuntime.ts";
32import type { OrchestratorV2ScenarioStep } from "./testkit/OrchestratorScenario.ts";
33import { runOrchestratorV2ProviderReplayScenario } from "./testkit/ProviderReplayHarness.ts";
34import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
35import {
36 decodeProviderReplayNdjson,
37 readProviderReplayTranscript,
38} from "./testkit/ReplayTranscriptNdjson.ts";
39import * as IdAllocator from "./IdAllocator.ts";
40​
41const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
42/** Held until the scenario releases it, so the turn is still running meanwhile. */
43const FIRST_TURN_END = "first-turn-end";
44/** Held until the scenario releases it, so a follow-up is running when its stream drops. */
45const BACKGROUND_HOLD = "background-hold";
46/** The parent session of the recorded background run. */
47const BACKGROUND_PARENT = "ses_f1485cda4ffeXuc6GjAU9vDiRb";
48/** Its background subagent's session. */
49const BACKGROUND_CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
50const BACKGROUND_PROMPT =
51 "Use the subagent tool with background enabled to delegate to the general subagent with the prompt: 'Run the shell command `sleep 20` with the bash tool and then reply exactly CHILD_OK.' As soon as it is launched, reply exactly PARENT_OK and end your turn without waiting for it.";
52const instanceId = ProviderInstanceId.make("opencode");
53const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
54const mimo: ModelSelection = { instanceId, model: "opencode/mimo-v2.6-flash-free" };
55const nemotron: ModelSelection = { instanceId, model: "opencode/nemotron-3.5-lightning-free" };
56​
57const out = (type: string, input?: unknown): ProviderReplayEntry => ({
58 type: "expect_outbound",
59 frame: input === undefined ? { type } : { type, input },
60});
61const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
62 type: "emit_inbound",
63 frame: { type: "sdk.response", operation, data },
64});
65const event = (type: string, data: Record<string, unknown>): ProviderReplayEntry => ({
66 type: "emit_inbound",
67 frame: {
68 type: "sdk.event",
69 event: { id: `evt_${type.replaceAll(".", "")}`, created: 1, type, data },
70 },
71});
72const labelled = (entry: ProviderReplayEntry, label: string): ProviderReplayEntry =>
73 entry.type === "runtime_exit" ? entry : { ...entry, label };
74/**
75 * T3's own rules after a mode's: every thread's T3 MCP server is denied, and
76 * then this thread's own is allowed again (last match wins).
77 */
78const mcpRules = (name: string) => [
79 { action: "t3-code-*", resource: "*", effect: "deny" },
80 { action: `t3-code-thread_${name}_*`, resource: "*", effect: "allow" },
81];
82const FULL_ACCESS = [{ action: "*", resource: "*", effect: "allow" }];
83/** Full access for the thread named `name`. */
84const t3Rules = (name: string) => [...FULL_ACCESS, ...mcpRules(name)];
85/** Paths the build and plan agents allow for themselves, as 2.0.18 lists them. */
86const BUILD_PATHS = [
87 {
88 action: "external_directory",
89 resource: "/home/.local/share/opencode/tool-output/*",
90 effect: "allow",
91 },
92];
93const PLAN_PATHS = [
94 ...BUILD_PATHS,
95 { action: "edit", resource: "/home/.opencode/plan/*", effect: "allow" },
96 { action: "external_directory", resource: "/home/.opencode/plan/*", effect: "allow" },
97];
98const agentInfo = (id: string, description: string, permissions: ReadonlyArray<unknown>) => ({
99 id,
100 name: id === "plan" ? "Plan" : "Build",
101 request: { settings: {}, headers: {}, body: {} },
102 description,
103 mode: "primary",
104 hidden: false,
105 permissions,
106});
107/** `/api/agent` trimmed to the two agents a T3 session runs. */
108const agentList = (directory: string) => ({
109 location: { directory },
110 data: [
111 agentInfo("build", "The default agent.", [
112 { action: "*", resource: "*", effect: "allow" },
113 { action: "external_directory", resource: "*", effect: "ask" },
114 ...BUILD_PATHS,
115 ]),
116 agentInfo("plan", "Read-only agent for planning.", [
117 { action: "*", resource: "*", effect: "allow" },
118 { action: "external_directory", resource: "*", effect: "ask" },
119 ...BUILD_PATHS,
120 { action: "edit", resource: "*", effect: "deny" },
121 ...PLAN_PATHS.slice(BUILD_PATHS.length),
122 ]),
123 ],
124});
125/** A session this runtime loads again (after a detach) waits on nothing. */
126const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
127 out("permission.list", { sessionID: SESSION }),
128 reply("permission.list", { data: [] }),
129 out("session.form.list", { sessionID: SESSION }),
130 reply("session.form.list", { data: [] }),
131];
132const supervisedRules = (name: string) => [
133 { action: "shell", resource: "*", effect: "ask" },
134 { action: "edit", resource: "*", effect: "ask" },
135 { action: "external_directory", resource: "*", effect: "ask" },
136 ...BUILD_PATHS,
137 ...mcpRules(name),
138];
139const autoEditRules = (name: string) => [
140 { action: "shell", resource: "*", effect: "ask" },
141 { action: "edit", resource: "*", effect: "allow" },
142 { action: "external_directory", resource: "*", effect: "ask" },
143 ...BUILD_PATHS,
144 ...mcpRules(name),
145];
146/** Plan mode on Full access: edits are denied except the plan agent's own plan files. */
147const planRules = (name: string) => [
148 { action: "*", resource: "*", effect: "allow" },
149 { action: "edit", resource: "*", effect: "deny" },
150 ...PLAN_PATHS,
151 ...mcpRules(name),
152];
153​
154const sessionInfo = (directory: string, permissions: ReadonlyArray<unknown>) => ({
155 data: {
156 id: SESSION,
157 projectID: "global",
158 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
159 cost: 0,
160 tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
161 time: { created: 1790656601394, updated: 1790656601394 },
162 location: { directory },
163 permissions,
164 },
165});
166/** T3's instructions entry, written before a thread's first prompt and whenever it changes. */
167const instructionsWritten: ReadonlyArray<ProviderReplayEntry> = [
168 out("session.instructions.entry.put", { sessionID: SESSION, key: "t3-code", value: "<any>" }),
169 reply("session.instructions.entry.put", null),
170];
171/** One prompt the server accepts and answers with `text`. */
172const answeredPrompt = (text: string): ReadonlyArray<ProviderReplayEntry> => [
173 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
174 reply("session.prompt", {
175 data: {
176 id: `msg_user_${text}`,
177 sessionID: SESSION,
178 time: { created: 1790656601410 },
179 type: "user",
180 payload: { text: "<prompt>" },
181 delivery: "steer",
182 },
183 }),
184 event("session.text.ended", {
185 sessionID: SESSION,
186 assistantMessageID: `msg_assistant_${text}`,
187 ordinal: 0,
188 text,
189 }),
190 event("session.execution.succeeded", { sessionID: SESSION }),
191];
192/** The model list read the first time a thread runs in `directory`. */
193const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
194 out("model.list", { "location[directory]": directory }),
195 reply("model.list", {
196 location: { directory },
197 data: [
198 catalogModel("big-pickle", "Big Pickle"),
199 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
200 ],
201 }),
202];
203/** A `/api/model` entry as 2.0.18 lists it; a known window means no re-read after a turn. */
204const catalogModel = (id: string, name: string) => ({
205 id,
206 modelID: id,
207 providerID: "opencode",
208 family: id,
209 name,
210 compatibility: { reasoningField: "reasoning_content" },
211 package: "@opencode/ai/providers/openai-compatible",
212 settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
213 capabilities: { tools: true, input: ["text"], output: ["text"] },
214 variants: [],
215 time: { released: 1760659200000 },
216 cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
217 status: "active",
218 enabled: true,
219 limit: { context: 200000, input: 160000, output: 32000 },
220});
221const createdSession = (
222 directory: string,
223 name: string,
224 permissions: ReadonlyArray<unknown> = t3Rules(name),
225 // Only a mode that narrows Full access reads the agents' own path rules.
226 narrows = false,
227): ReadonlyArray<ProviderReplayEntry> => [
228 out("event.subscribe"),
229 out("model.list", "<any>"),
230 reply("model.list", {
231 location: { directory },
232 data: [
233 catalogModel("big-pickle", "Big Pickle"),
234 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
235 ],
236 }),
237 ...(narrows ? [out("agent.list", "<any>"), reply("agent.list", agentList(directory))] : []),
238 out("session.create", { location: { directory }, model: "<any>", permissions }),
239 reply("session.create", sessionInfo(directory, permissions)),
240];
241​
242/** A recording with its scrubbed `<work>` directory replaced by `directory`. */
243const withDirectory = <T>(value: T, directory: string): T => {
244 const replace = (entry: unknown): unknown =>
245 entry === "<work>"
246 ? directory
247 : Array.isArray(entry)
248 ? entry.map(replace)
249 : typeof entry === "object" && entry !== null
250 ? Object.fromEntries(Object.entries(entry).map(([key, inner]) => [key, replace(inner)]))
251 : entry;
252 return replace(value) as T;
253};
254​
255const threadCommands = (input: {
256 readonly name: string;
257 readonly worktreePath: string;
258 readonly runtimeMode?: RuntimeMode;
259 readonly interactionMode?: ProviderInteractionMode;
260}) => {
261 const threadId = ThreadId.make(`thread:${input.name}`);
262 const command = (key: string) => CommandId.make(`command:${input.name}:${key}`);
263 return {
264 threadId,
265 create: {
266 type: "thread.create",
267 createdBy: "user",
268 creationSource: "web",
269 commandId: command("create"),
270 threadId,
271 projectId: ProjectId.make(`project:${input.name}`),
272 title: input.name,
273 modelSelection: bigPickle,
274 runtimeMode: input.runtimeMode ?? "full-access",
275 interactionMode: input.interactionMode ?? "default",
276 branch: null,
277 worktreePath: input.worktreePath,
278 } satisfies OrchestrationV2Command,
279 message: (key: string, modelSelection: ModelSelection = bigPickle, text?: string) =>
280 ({
281 type: "message.dispatch",
282 createdBy: "user",
283 creationSource: "web",
284 commandId: command(key),
285 threadId,
286 messageId: MessageId.make(`message:${input.name}:${key}`),
287 text: text ?? `Reply with exactly: ${key}`,
288 attachments: [],
289 modelSelection,
290 dispatchMode: { type: "start_immediately" },
291 }) satisfies OrchestrationV2Command,
292 interactionMode: (key: string, interactionMode: "default" | "plan") =>
293 ({
294 type: "thread.interaction-mode.set",
295 commandId: command(key),
296 threadId,
297 interactionMode,
298 }) satisfies OrchestrationV2Command,
299 command,
300 };
301};
302​
303/** Runs `commands` in order, letting the thread go idle after each message. */
304const runScenario = (input: {
305 readonly name: string;
306 readonly threadId: ThreadId;
307 readonly entries: ReadonlyArray<ProviderReplayEntry>;
308 readonly commands: ReadonlyArray<OrchestrationV2Command>;
309}) =>
310 Effect.gen(function* () {
311 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
312 provider: OPENCODE_PROVIDER,
313 protocol: OPENCODE2_HTTP_PROTOCOL,
314 version: "2.0.18",
315 scenario: input.name,
316 entries: input.entries,
317 });
318 const steps = input.commands.flatMap((command): Array<OrchestratorV2ScenarioStep> => [
319 { type: "dispatch", command },
320 { type: "advance_clock", duration: "1 millis" },
321 ...(command.type === "message.dispatch"
322 ? [{ type: "await_thread_idle" as const, threadId: input.threadId }]
323 : []),
324 ]);
325 const result = yield* runOrchestratorV2ProviderReplayScenario(
326 { name: input.name, transcript, commands: input.commands, steps },
327 OpenCode2OrchestratorReplayHarness,
328 ).pipe(provideDeterministicTestRuntime);
329 const projection = result.projections.get(input.threadId);
330 assert.isDefined(projection);
331 return projection;
332 });
333​
334describe("OpenCode 2 through the orchestrator", () => {
335 it.effect.each(["message", "thread settings"] as const)(
336 "switches the session's model before the next prompt when changed from the %s",
337 (via) =>
338 Effect.gen(function* () {
339 const name = `opencode2-model-switch-${via.replace(" ", "-")}`;
340 const cwd = yield* checkpointWorkspace(name);
341 const thread = threadCommands({ name, worktreePath: cwd });
342 const projection = yield* runScenario({
343 name,
344 threadId: thread.threadId,
345 entries: [
346 ...createdSession(cwd, name),
347 ...instructionsWritten,
348 ...answeredPrompt("FIRST"),
349 // The next turn resumes the session at its new selection.
350 out("session.get", { sessionID: SESSION }),
351 reply("session.get", sessionInfo(cwd, t3Rules(name))),
352 out("session.switchModel", {
353 sessionID: SESSION,
354 model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
355 }),
356 reply("session.switchModel", null),
357 // The instructions name the model, so they are written again.
358 ...instructionsWritten,
359 ...answeredPrompt("SECOND"),
360 ],
361 commands: [
362 thread.create,
363 thread.message("first"),
364 ...(via === "thread settings"
365 ? [
366 {
367 type: "thread.model-selection.set",
368 commandId: thread.command("model"),
369 threadId: thread.threadId,
370 modelSelection: mimo,
371 } satisfies OrchestrationV2Command,
372 ]
373 : []),
374 thread.message("second", mimo),
375 ],
376 });
377 assert.deepEqual(
378 projection.runs.map((run) => [run.status, run.modelSelection.model]),
379 [
380 ["completed", bigPickle.model],
381 ["completed", mimo.model],
382 ],
383 );
384 // One native session carried both turns.
385 assert.lengthOf(projection.providerThreads, 1);
386 }).pipe(Effect.scoped),
387 );
388​
389 it.effect("moves the session to the thread's new worktree before the next prompt", () =>
390 Effect.gen(function* () {
391 const name = "opencode2-worktree-move";
392 const before = yield* checkpointWorkspace(`${name}-before`);
393 const after = yield* checkpointWorkspace(`${name}-after`);
394 const thread = threadCommands({ name, worktreePath: before });
395 const projection = yield* runScenario({
396 name,
397 threadId: thread.threadId,
398 entries: [
399 ...createdSession(before, name),
400 ...instructionsWritten,
401 ...answeredPrompt("FIRST"),
402 ...directoryModels(after),
403 out("session.get", { sessionID: SESSION }),
404 reply("session.get", sessionInfo(before, t3Rules(name))),
405 // The worktree change detached the thread, so its session is loaded afresh.
406 ...noOpenRequests,
407 out("session.move", { sessionID: SESSION, directory: after }),
408 reply("session.move", null),
409 // The moved thread reopens its session, which writes the entry again.
410 ...instructionsWritten,
411 ...answeredPrompt("SECOND"),
412 ],
413 commands: [
414 thread.create,
415 thread.message("first"),
416 {
417 type: "thread.metadata.update",
418 commandId: thread.command("worktree"),
419 threadId: thread.threadId,
420 worktreePath: after,
421 },
422 thread.message("second"),
423 ],
424 });
425 assert.deepEqual(
426 projection.runs.map((run) => run.status),
427 ["completed", "completed"],
428 );
429 assert.lengthOf(projection.providerThreads, 1);
430 }).pipe(Effect.scoped),
431 );
432​
433 it.effect("gives a session made with older rules T3's rules before its next prompt", () =>
434 Effect.gen(function* () {
435 const name = "opencode2-resume-rules";
436 const before = yield* checkpointWorkspace(`${name}-before`);
437 const after = yield* checkpointWorkspace(`${name}-after`);
438 const thread = threadCommands({ name, worktreePath: before });
439 const projection = yield* runScenario({
440 name,
441 threadId: thread.threadId,
442 entries: [
443 ...createdSession(before, name),
444 ...instructionsWritten,
445 ...answeredPrompt("FIRST"),
446 ...directoryModels(after),
447 // Reopened after a worktree change, the session reports the rules an
448 // older build gave it, which denied subagents; they are replaced
449 // before anything runs.
450 out("session.get", { sessionID: SESSION }),
451 reply(
452 "session.get",
453 sessionInfo(before, [
454 { action: "*", resource: "*", effect: "allow" },
455 { action: "subagent", resource: "*", effect: "deny" },
456 ]),
457 ),
458 ...noOpenRequests,
459 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
460 reply("session.update", null),
461 out("session.move", { sessionID: SESSION, directory: after }),
462 reply("session.move", null),
463 ...instructionsWritten,
464 ...answeredPrompt("SECOND"),
465 ],
466 commands: [
467 thread.create,
468 thread.message("first"),
469 {
470 type: "thread.metadata.update",
471 commandId: thread.command("worktree"),
472 threadId: thread.threadId,
473 worktreePath: after,
474 },
475 thread.message("second"),
476 ],
477 });
478 assert.deepEqual(
479 projection.runs.map((run) => run.status),
480 ["completed", "completed"],
481 );
482 }).pipe(Effect.scoped),
483 );
484​
485 it.effect(
486 "creates a Supervised thread's session with rules that ask before shell and edits",
487 () =>
488 Effect.gen(function* () {
489 const name = "opencode2-supervised-rules";
490 const cwd = yield* checkpointWorkspace(name);
491 const thread = threadCommands({
492 name,
493 worktreePath: cwd,
494 runtimeMode: "approval-required",
495 });
496 const projection = yield* runScenario({
497 name,
498 threadId: thread.threadId,
499 entries: [
500 ...createdSession(cwd, name, supervisedRules(name), true),
501 ...instructionsWritten,
502 ...answeredPrompt("FIRST"),
503 ],
504 commands: [thread.create, thread.message("first")],
505 });
506 assert.deepEqual(
507 projection.runs.map((run) => run.status),
508 ["completed"],
509 );
510 }).pipe(Effect.scoped),
511 );
512​
513 it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
514 Effect.gen(function* () {
515 const name = "opencode2-mode-change";
516 const cwd = yield* checkpointWorkspace(name);
517 const thread = threadCommands({ name, worktreePath: cwd });
518 const setMode = (key: string, runtimeMode: RuntimeMode) =>
519 ({
520 type: "thread.runtime-mode.set",
521 commandId: thread.command(key),
522 threadId: thread.threadId,
523 runtimeMode,
524 }) satisfies OrchestrationV2Command;
525 const projection = yield* runScenario({
526 name,
527 threadId: thread.threadId,
528 entries: [
529 ...createdSession(cwd, name),
530 ...instructionsWritten,
531 ...answeredPrompt("FIRST"),
532 // A mode change detaches nothing: the same session is resumed with the new rules.
533 out("session.get", { sessionID: SESSION }),
534 reply("session.get", sessionInfo(cwd, t3Rules(name))),
535 out("agent.list", "<any>"),
536 reply("agent.list", agentList(cwd)),
537 out("session.update", { sessionID: SESSION, permissions: autoEditRules(name) }),
538 reply("session.update", null),
539 ...answeredPrompt("SECOND"),
540 // Back to Full access: the narrowing rules go.
541 out("session.get", { sessionID: SESSION }),
542 reply("session.get", sessionInfo(cwd, autoEditRules(name))),
543 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
544 reply("session.update", null),
545 ...answeredPrompt("THIRD"),
546 ],
547 commands: [
548 thread.create,
549 thread.message("first"),
550 setMode("auto-edit", "auto-accept-edits"),
551 thread.message("second"),
552 setMode("full", "full-access"),
553 thread.message("third"),
554 ],
555 });
556 assert.deepEqual(
557 projection.runs.map((run) => run.status),
558 ["completed", "completed", "completed"],
559 );
560 assert.lengthOf(projection.providerThreads, 1);
561 }).pipe(Effect.scoped),
562 );
563​
564 it.effect("denies edits outside the plan directory in plan mode and lifts it after", () =>
565 Effect.gen(function* () {
566 const name = "opencode2-plan-rules";
567 const cwd = yield* checkpointWorkspace(name);
568 const thread = threadCommands({ name, worktreePath: cwd, interactionMode: "plan" });
569 const projection = yield* runScenario({
570 name,
571 threadId: thread.threadId,
572 entries: [
573 ...createdSession(cwd, name, planRules(name), true),
574 // Plan mode is also OpenCode's plan agent, switched before the prompt.
575 out("session.switchAgent", { sessionID: SESSION, agent: "plan" }),
576 reply("session.switchAgent", null),
577 ...instructionsWritten,
578 ...answeredPrompt("PLANNED"),
579 out("session.get", { sessionID: SESSION }),
580 reply("session.get", sessionInfo(cwd, planRules(name))),
581 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
582 reply("session.update", null),
583 out("session.switchAgent", { sessionID: SESSION, agent: "build" }),
584 reply("session.switchAgent", null),
585 ...answeredPrompt("BUILT"),
586 ],
587 commands: [
588 thread.create,
589 thread.message("plan"),
590 {
591 type: "thread.interaction-mode.set",
592 commandId: thread.command("default"),
593 threadId: thread.threadId,
594 interactionMode: "default",
595 },
596 thread.message("build"),
597 ],
598 });
599 assert.deepEqual(
600 projection.runs.map((run) => run.status),
601 ["completed", "completed"],
602 );
603 }).pipe(Effect.scoped),
604 );
605​
606 it.effect("forks from an earlier turn before the next turn's user message", () =>
607 Effect.gen(function* () {
608 const name = "opencode2-fork";
609 const cwd = yield* checkpointWorkspace(name);
610 const recorded = yield* readProviderReplayTranscript(
611 new URL("./testkit/fixtures/opencode2_fork/opencode_transcript.ndjson", import.meta.url),
612 );
613 // The recording scrubbed its directory to `<work>`; the fork it answers
614 // runs where its source does, which is this test's workspace.
615 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript(
616 withDirectory(recorded, cwd),
617 );
618 const source = threadCommands({ name, worktreePath: cwd });
619 const target = ThreadId.make(`thread:${name}:target`);
620 const [one, two] = [source.message("one"), source.message("two")];
621 const commands: ReadonlyArray<OrchestrationV2Command> = [
622 source.create,
623 one,
624 two,
625 {
626 type: "thread.fork",
627 createdBy: "user",
628 creationSource: "web",
629 commandId: source.command("fork"),
630 sourceThreadId: source.threadId,
631 targetThreadId: target,
632 sourcePoint: {
633 type: "run",
634 runId: (yield* IdAllocator.IdAllocatorV2).derive.run({
635 threadId: source.threadId,
636 ordinal: 1,
637 }),
638 },
639 },
640 {
641 ...source.message("repeat"),
642 threadId: target,
643 messageId: MessageId.make(`message:${name}:repeat`),
644 },
645 ];
646 const steps: Array<OrchestratorV2ScenarioStep> = commands.flatMap((command) => [
647 { type: "dispatch" as const, command },
648 { type: "advance_clock" as const, duration: "1 millis" as const },
649 ...(command.type === "message.dispatch"
650 ? [{ type: "await_thread_idle" as const, threadId: command.threadId }]
651 : []),
652 ]);
653 const result = yield* runOrchestratorV2ProviderReplayScenario(
654 { name, transcript, commands, steps, projectionThreadIds: [source.threadId, target] },
655 OpenCode2OrchestratorReplayHarness,
656 ).pipe(provideDeterministicTestRuntime);
657 const forked = result.projections.get(target);
658 assert.isDefined(forked);
659 assert.equal(forked.contextTransfers[0]?.resolution?.strategy, "native_fork");
660 assert.equal(
661 forked.providerThreads[0]?.nativeThreadRef?.nativeId,
662 recorded.metadata?.["forkedNativeSessionId"],
663 );
664 // The fork keeps the first turn and drops the second: the model answers
665 // from the first alone, and T3 shows the inherited turn but not the other.
666 assert.deepEqual(
667 forked.runs.map((run) => run.status),
668 ["completed"],
669 );
670 const visible = forked.visibleTurnItems.flatMap((row) =>
671 row.item.type === "assistant_message" ? [row.item.text] : [],
672 );
673 assert.deepEqual(visible, ["ONE", "ONE"]);
674 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
675 );
676​
677 it.effect("never sends OpenCode a queued message that was cancelled", () =>
678 Effect.gen(function* () {
679 const name = "opencode2-queued-cancel";
680 const cwd = yield* checkpointWorkspace(name);
681 const thread = threadCommands({ name, worktreePath: cwd });
682 const queued = (key: string): OrchestrationV2Command => ({
683 ...thread.message(key),
684 dispatchMode: { type: "queue_after_active" },
685 });
686 const ids = yield* IdAllocator.IdAllocatorV2;
687 const run = (ordinal: number) => ids.derive.run({ threadId: thread.threadId, ordinal });
688 // The first turn is held open until the queue has been changed: its end
689 // is the last event, after the cancel.
690 const [first, second, third] = [thread.message("first"), queued("second"), queued("third")];
691 const cancel: OrchestrationV2Command = {
692 type: "queued-run.cancel",
693 commandId: thread.command("cancel"),
694 threadId: thread.threadId,
695 runId: run(2),
696 };
697 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
698 provider: OPENCODE_PROVIDER,
699 protocol: OPENCODE2_HTTP_PROTOCOL,
700 version: "2.0.18",
701 scenario: name,
702 entries: [
703 ...createdSession(cwd, name),
704 ...instructionsWritten,
705 out("session.prompt", { sessionID: SESSION, id: "<any>", text: "<any>" }),
706 reply("session.prompt", {
707 data: {
708 id: "msg_user_FIRST",
709 sessionID: SESSION,
710 time: { created: 1 },
711 type: "user",
712 payload: { text: "<prompt>" },
713 delivery: "steer",
714 },
715 }),
716 // Only the third message reaches OpenCode, as the next turn.
717 ...answeredPrompt("THIRD"),
718 ],
719 });
720 const steps: Array<OrchestratorV2ScenarioStep> = [
721 { type: "dispatch", command: thread.create },
722 { type: "advance_clock", duration: "1 millis" },
723 { type: "dispatch", command: first, await: false, key: "first" },
724 { type: "await_run_steerable", threadId: thread.threadId, runId: run(1) },
725 { type: "dispatch", command: second },
726 { type: "dispatch", command: third },
727 { type: "dispatch", command: cancel },
728 { type: "await_run_status", threadId: thread.threadId, runId: run(2), status: "cancelled" },
729 { type: "release_replay_gate", label: FIRST_TURN_END },
730 { type: "await", key: "first" },
731 { type: "await_thread_idle", threadId: thread.threadId },
732 ];
733 const result = yield* runOrchestratorV2ProviderReplayScenario(
734 {
735 name,
736 transcript: {
737 ...transcript,
738 entries: [
739 ...transcript.entries.slice(0, -4),
740 labelled(
741 event("session.execution.succeeded", { sessionID: SESSION }),
742 FIRST_TURN_END,
743 ),
744 ...transcript.entries.slice(-4),
745 ],
746 },
747 commands: [thread.create, first, second, third, cancel],
748 steps,
749 },
750 OpenCode2OrchestratorReplayHarness,
751 ).pipe(provideDeterministicTestRuntime);
752 const projection = result.projections.get(thread.threadId);
753 assert.isDefined(projection);
754 assert.deepEqual(
755 projection.runs.map((candidate) => candidate.status),
756 ["completed", "cancelled", "completed"],
757 );
758 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
759 );
760​
761 /**
762 * The recorded background run (`opencode2_background`): the parent's turn
763 * ends while its subagent runs, then the subagent's report wakes the parent
764 * and T3 opens a continuation run for that follow-up. `reconnect` replaces
765 * the recording from `cut` on with a stream drop, a restarted stream and
766 * what the server answers then.
767 */
768 const backgroundReconnect = Effect.fn("backgroundReconnect")(function* (input: {
769 readonly name: string;
770 readonly cut: string;
771 readonly hold?: string;
772 readonly reconnect: (parent: string) => ReadonlyArray<ProviderReplayEntry>;
773 readonly steps: (
774 thread: ReturnType<typeof threadCommands>,
775 run: (ordinal: number) => OrchestrationV2Run["id"],
776 ) => ReadonlyArray<OrchestratorV2ScenarioStep>;
777 readonly commands: (
778 thread: ReturnType<typeof threadCommands>,
779 ) => ReadonlyArray<OrchestrationV2Command>;
780 }) {
781 const cwd = yield* checkpointWorkspace(input.name);
782 const recorded = yield* readProviderReplayTranscript(
783 new URL(
784 "./testkit/fixtures/opencode2_background/opencode_transcript.ndjson",
785 import.meta.url,
786 ),
787 );
788 const cut = recorded.entries.findIndex(
789 (entry) => entry.type !== "runtime_exit" && entry.label === input.cut,
790 );
791 assert.isAtLeast(cut, 0);
792 const kept = recorded.entries
793 .slice(0, cut)
794 .map((entry) =>
795 entry.type !== "runtime_exit" && entry.label === input.hold
796 ? labelled(entry, BACKGROUND_HOLD)
797 : entry,
798 );
799 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
800 ...recorded,
801 scenario: input.name,
802 entries: [
803 ...kept,
804 { type: "runtime_exit", status: "success" },
805 ...input.reconnect(BACKGROUND_PARENT),
806 ],
807 });
808 const thread = threadCommands({ name: input.name, worktreePath: cwd });
809 const ids = yield* IdAllocator.IdAllocatorV2;
810 const run = (ordinal: number) => ids.derive.run({ threadId: thread.threadId, ordinal });
811 const result = yield* runOrchestratorV2ProviderReplayScenario(
812 {
813 name: input.name,
814 transcript,
815 commands: input.commands(thread),
816 steps: input.steps(thread, run),
817 },
818 OpenCode2OrchestratorReplayHarness,
819 // Opens the continuation run a follow-up asks for, as the server does.
820 { runContinuationWorker: true },
821 ).pipe(provideDeterministicTestRuntime);
822 const projection = result.projections.get(thread.threadId);
823 assert.isDefined(projection);
824 return { result, projection };
825 });
826​
827 it.effect("backfills a follow-up whose stream dropped mid-run and ends it completed", () =>
828 Effect.gen(function* () {
829 const { result, projection } = yield* backgroundReconnect({
830 name: "opencode2-follow-up-reconnect",
831 // The follow-up streams its reply; then the stream drops before the
832 // execution's end.
833 cut: "session.step.streamed.5",
834 hold: "session.text.ended.3",
835 reconnect: (parent) => [
836 out("event.subscribe"),
837 out("session.active"),
838 reply("session.active", { data: {} }),
839 // The follow-up's history since the report it answers, newest first.
840 out("message.list", { sessionID: parent, order: "desc", limit: "50" }),
841 reply("message.list", {
842 data: [
843 {
844 id: "msg_0eb7a99c0001idleFollowUp00",
845 time: { created: 5 },
846 type: "idle",
847 outcome: "succeeded",
848 },
849 {
850 id: "msg_0eb7a96bb00170K1f1HJUeBNwF",
851 time: { created: 4 },
852 type: "assistant",
853 agent: "build",
854 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
855 content: [
856 {
857 type: "text",
858 text: "The background subagent finished and returned `CHILD_OK`.",
859 },
860 ],
861 finish: "stop",
862 },
863 {
864 id: "msg_0eb7a3aee0015KmTB8XkMDW8iy",
865 time: { created: 3 },
866 type: "synthetic",
867 text: "<subagent>CHILD_OK</subagent>",
868 },
869 {
870 id: "msg_0eb7a3e3c001idleParentTurn0",
871 time: { created: 2 },
872 type: "idle",
873 outcome: "succeeded",
874 },
875 ],
876 cursor: {},
877 }),
878 ],
879 commands: (thread) => [
880 thread.create,
881 thread.message("start", bigPickle, BACKGROUND_PROMPT),
882 ],
883 steps: (thread, run) => [
884 { type: "dispatch", command: thread.create },
885 { type: "advance_clock", duration: "1 millis" },
886 // A continuation run starts while the thread is busy, so this does not wait.
887 {
888 type: "dispatch",
889 command: thread.message("start", bigPickle, BACKGROUND_PROMPT),
890 await: false,
891 key: "start",
892 },
893 { type: "advance_clock", duration: "1 millis" },
894 // The follow-up's continuation turn has taken its execution when the
895 // stream drops: the held reply end is the next event.
896 { type: "await_run_steerable", threadId: thread.threadId, runId: run(2) },
897 { type: "release_replay_gate", label: BACKGROUND_HOLD },
898 {
899 type: "await_run_status",
900 threadId: thread.threadId,
901 runId: run(2),
902 status: "completed",
903 },
904 { type: "await", key: "start" },
905 { type: "await_thread_idle", threadId: thread.threadId },
906 ],
907 });
908 assert.deepEqual(
909 projection.runs.map((candidate) => candidate.status),
910 ["completed", "completed"],
911 );
912 const followUp = projection.runs[1];
913 assert.deepEqual(
914 projection.turnItems.flatMap((item) =>
915 item.runId === followUp?.id && item.type === "assistant_message" ? [item.text] : [],
916 ),
917 ["The background subagent finished and returned `CHILD_OK`."],
918 );
919 const shell = result.shellSnapshot.threads.find((row) => row.id === projection.thread.id);
920 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
921 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
922 );
923​
924 it.effect(
925 "settles a background subagent whose end was lost with the stream, and takes the next turn",
926 () =>
927 Effect.gen(function* () {
928 const { result, projection } = yield* backgroundReconnect({
929 name: "opencode2-background-lost",
930 // The subagent runs; the stream drops before its end, its report and
931 // the follow-up it started, none of which is read back.
932 cut: "session.step.started.3",
933 reconnect: (parent) => [
934 out("event.subscribe"),
935 // Nothing runs any more: the subagent and the follow-up both ended.
936 out("session.active"),
937 reply("session.active", { data: {} }),
938 // The subagent's turn was running, so its history since its prompt
939 // is read back: its end, as the recording's later events had it.
940 out("message.list", { sessionID: BACKGROUND_CHILD, order: "desc", limit: "50" }),
941 reply("message.list", {
942 data: [
943 {
944 id: "msg_0eb7a99b0001idleChildTurn0",
945 time: { created: 4 },
946 type: "idle",
947 outcome: "succeeded",
948 },
949 {
950 id: "msg_0eb7a916c001NRJQJ5gwIT0QnU",
951 time: { created: 3 },
952 type: "assistant",
953 agent: "general",
954 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
955 content: [{ type: "text", text: "CHILD_OK" }],
956 finish: "stop",
957 },
958 {
959 id: "msg_0eb7a3aea001Lw1Pav5d4akfEg",
960 time: { created: 2 },
961 type: "user",
962 text: "Run the shell command `sleep 20` with the bash tool and then reply exactly CHILD_OK.",
963 },
964 ],
965 cursor: {},
966 }),
967 out("session.prompt", { sessionID: parent, id: "<any>", text: "<any>" }),
968 reply("session.prompt", {
969 data: {
970 id: "msg_next",
971 sessionID: parent,
972 time: { created: 9 },
973 type: "user",
974 payload: { text: "<prompt>" },
975 delivery: "steer",
976 },
977 }),
978 event("session.execution.started", { sessionID: parent }),
979 event("session.text.ended", {
980 sessionID: parent,
981 assistantMessageID: "msg_next_reply",
982 ordinal: 0,
983 text: "NEXT",
984 }),
985 event("session.execution.succeeded", { sessionID: parent }),
986 ],
987 commands: (thread) => [
988 thread.create,
989 thread.message("start", bigPickle, BACKGROUND_PROMPT),
990 thread.message("next"),
991 ],
992 steps: (thread, run) => [
993 { type: "dispatch", command: thread.create },
994 { type: "advance_clock", duration: "1 millis" },
995 { type: "dispatch", command: thread.message("start", bigPickle, BACKGROUND_PROMPT) },
996 { type: "advance_clock", duration: "1 millis" },
997 { type: "await_thread_idle", threadId: thread.threadId },
998 { type: "dispatch", command: thread.message("next") },
999 { type: "advance_clock", duration: "1 millis" },
1001 type: "await_run_status",
1002 threadId: thread.threadId,
1003 runId: run(2),
1004 status: "completed",
1005 },
1006 { type: "await_thread_idle", threadId: thread.threadId },
1007 ],
1008 });
1009 // The parent's run ended; the lost subagent ended as interrupted and
1010 // said why; no follow-up is waited on; the next turn ran normally.
1011 assert.deepEqual(
1012 projection.runs.map((candidate) => candidate.status),
1013 ["completed", "completed"],
1014 );
1015 assert.lengthOf(projection.subagents, 1);
1016 assert.deepInclude(projection.subagents[0], { status: "interrupted" });
1017 assert.include(projection.subagents[0]?.result ?? "", "lost its connection to OpenCode");
1018 assert.isFalse(
1019 projection.turnItems.some(
1020 (item) => item.status === "running" || item.status === "waiting",
1021 ),
1022 );
1023 const shell = result.shellSnapshot.threads.find((row) => row.id === projection.thread.id);
1024 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
1025 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
1026 );
1027​
1028 it.effect(
1029 "settles a background subagent whose report OpenCode delivers into the launching turn",
1030 () =>
1031 Effect.gen(function* () {
1032 // The recorded background run, reordered as 2.0.18 ran it live when the
1033 // child ended first: the parent's execution is still answering when the
1034 // child's report is queued and delivered into it, and that one
1035 // execution then answers the report and ends. No execution starts on
1036 // its own, so no continuation run opens.
1037 const cwd = yield* checkpointWorkspace("opencode2-background-in-turn");
1038 const recorded = yield* readProviderReplayTranscript(
1039 new URL(
1040 "./testkit/fixtures/opencode2_background/opencode_transcript.ndjson",
1041 import.meta.url,
1042 ),
1043 );
1044 const byLabel = (label: string) => {
1045 const entry = recorded.entries.find(
1046 (candidate) => candidate.type !== "runtime_exit" && candidate.label === label,
1047 );
1048 assert.isDefined(entry);
1049 return entry!;
1050 };
1051 const parentEnd = recorded.entries.findIndex(
1052 (entry) => entry.type !== "runtime_exit" && entry.label === "session.execution.succeeded",
1053 );
1054 const childStart = recorded.entries.findIndex(
1055 (entry) => entry.type !== "runtime_exit" && entry.label === "session.step.started.3",
1056 );
1057 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
1058 ...recorded,
1059 scenario: "opencode2-background-in-turn",
1060 entries: [
1061 // The launch, up to the parent's answer, without its end.
1062 ...recorded.entries.slice(0, parentEnd),
1063 // The child runs to its end meanwhile.
1064 ...recorded.entries.slice(
1065 childStart,
1066 recorded.entries.indexOf(byLabel("session.inbox.enqueued.3")),
1067 ),
1068 // Its report is queued and delivered into the parent's running execution.
1069 byLabel("session.inbox.enqueued.3"),
1070 byLabel("session.inbox.delivered.3"),
1071 // That execution answers the report and ends.
1072 byLabel("session.text.ended.3"),
1073 byLabel("session.execution.succeeded.3"),
1074 ],
1075 });
1076 const thread = threadCommands({ name: "opencode2-background-in-turn", worktreePath: cwd });
1077 const ids = yield* IdAllocator.IdAllocatorV2;
1078 const result = yield* runOrchestratorV2ProviderReplayScenario(
1080 name: "opencode2-background-in-turn",
1081 transcript,
1082 commands: [thread.create, thread.message("start", bigPickle, BACKGROUND_PROMPT)],
1083 steps: [
1084 { type: "dispatch", command: thread.create },
1085 { type: "advance_clock", duration: "1 millis" },
1086 { type: "dispatch", command: thread.message("start", bigPickle, BACKGROUND_PROMPT) },
1087 { type: "advance_clock", duration: "1 millis" },
1089 type: "await_run_status",
1090 threadId: thread.threadId,
1091 runId: ids.derive.run({ threadId: thread.threadId, ordinal: 1 }),
1092 status: "completed",
1093 },
1094 { type: "await_thread_idle", threadId: thread.threadId },
1095 ],
1096 },
1097 OpenCode2OrchestratorReplayHarness,
1098 { runContinuationWorker: true },
1099 ).pipe(provideDeterministicTestRuntime);
1100 const projection = result.projections.get(thread.threadId);
1101 assert.isDefined(projection);
1102 // One run took the launch and the report; the subagent completed with
1103 // its output, and nothing waits on a follow-up.
1104 assert.deepEqual(
1105 projection!.runs.map((candidate) => candidate.status),
1106 ["completed"],
1107 );
1108 assert.lengthOf(projection!.subagents, 1);
1109 assert.deepInclude(projection!.subagents[0], { status: "completed" });
1110 assert.include(projection!.subagents[0]?.result ?? "", "CHILD_OK");
1111 assert.isTrue(
1112 projection!.turnItems.some(
1113 (item) =>
1114 item.type === "assistant_message" && item.text.includes("finished and returned"),
1115 ),
1116 );
1117 assert.isFalse(
1118 projection!.turnItems.some(
1119 (item) => item.status === "running" || item.status === "waiting",
1120 ),
1121 );
1122 const shell = result.shellSnapshot.threads.find((row) => row.id === projection!.thread.id);
1123 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
1124 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
1125 );
1126​
1127 it.effect(
1128 "runs plan mode as OpenCode's plan agent and switches back before the next prompt",
1129 () =>
1130 Effect.gen(function* () {
1131 const name = "opencode2_switch";
1132 const cwd = yield* checkpointWorkspace(name);
1133 const thread = threadCommands({ name, worktreePath: cwd });
1134 // The spike's recording: plan agent, then build agent and a new model on
1135 // one session. Its `<work>` is this test's workspace.
1136 const recorded = yield* Effect.gen(function* () {
1137 const fs = yield* FileSystem.FileSystem;
1138 const path = yield* Path.Path;
1139 const text = yield* fs.readFileString(
1140 yield* path.fromFileUrl(
1141 new URL(
1142 "./testkit/fixtures/opencode2_switch/opencode_transcript.ndjson",
1143 import.meta.url,
1144 ),
1145 ),
1146 );
1147 return yield* decodeProviderReplayNdjson(text.replaceAll("<work>", cwd));
1148 }).pipe(Effect.provide(NodeServices.layer));
1149 const projection = yield* runScenario({
1150 name,
1151 threadId: thread.threadId,
1152 entries: recorded.entries,
1153 commands: [
1154 thread.create,
1155 thread.interactionMode("mode-plan", "plan"),
1156 thread.message(
1157 "plan",
1158 bigPickle,
1159 "Create a file named plan_probe.txt containing HI using the write tool.",
1160 ),
1161 thread.interactionMode("mode-default", "default"),
1162 thread.message("switched", nemotron, "Reply exactly SWITCHED."),
1163 ],
1164 });
1165 assert.deepEqual(
1166 projection.runs.map((run) => [run.status, run.modelSelection.model]),
1168 ["completed", bigPickle.model],
1169 ["completed", nemotron.model],
1170 ],
1171 );
1172 const replies = projection.turnItems.flatMap((item) =>
1173 item.type === "assistant_message" ? [item.text] : [],
1174 );
1175 // The plan agent refused to write; OpenCode's own reminder told it why.
1176 assert.include(replies[0], "Plan mode");
1177 assert.equal(replies[1], "SWITCHED");
1178 assert.lengthOf(projection.providerThreads, 1);
1179 }).pipe(Effect.scoped),
1180 );
1181});