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