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

OpenCode2OrchestratorV2.integration.test.ts

1,160 lines42.5 KB

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