From 7e117213aa67712ac7690be0fff1ac71826dd5a3 Mon Sep 17 00:00:00 2001 From: Nikita Koynov <43469098+nkoynov@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:25:39 +0200 Subject: [PATCH 1/7] fix(opencode): a subagent reporting with its own work still running stays pending --- .../Adapters/OpenCode2AdapterV2.test.ts | 124 +++++++++++++++++- .../src/server/v2/adapter.ts | 38 +++++- 2 files changed, 156 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 88563aeb43492..6b32a14026f93 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1751,14 +1751,14 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { returnedRunning(tool.id), ]; }; - const childReport = (inboxID: string, text: string, description = "Sleep") => + const childReport = (inboxID: string, text: string, description = "Sleep", tag = "completed") => event("session.inbox.enqueued", { inboxID, sessionID: SESSION, item: { type: "synthetic", payload: { - text: `\n${text}\n`, + text: `\n${text}\n`, description, metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" }, }, @@ -1777,7 +1777,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { string, Record >(); - const state: { roster: ReadonlyArray | undefined } = { roster: undefined }; + const state: { roster: OrchestrationV2ProviderThread["pendingBackgroundTasks"] } = { + roster: undefined, + }; let wake = yield* Deferred.make(); yield* runtime.events.pipe( Stream.tap((event) => @@ -2152,6 +2154,122 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + const childStep = (run: number) => + event("session.step.started", { + sessionID: CHILD, + assistantMessageID: `msg_child_${run}`, + agent: "general", + model: { id: "big-pickle", providerID: "opencode", variant: "default" }, + started: 1, + }); + const STARTED = "TESTS_STARTED\n\nBackground work still running:\n- shell (sh_tests): npm test"; + // The child goes idle with its own work running, and OpenCode reports it as running. + const reportedRunning = [ + ...launchedAndRunning, + childSaid("TESTS_STARTED"), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_1", STARTED, "Sleep", "running"), + ]; + const finished = (labelled = false): ReadonlyArray => [ + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + childSaid("TESTS_PASSED", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + { ...childReport("msg_report_2", "TESTS_PASSED"), ...(labelled ? { label: "final" } : {}) }, + ]; + + it.effect( + "keeps a background subagent pending while its report says its own work still runs", + () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["final"]); + const { runtime, thread } = yield* resumed([...reportedRunning, ...finished(true)], { + replayGate: gate, + }); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("final"))); + yield* watch.until(() => watch.childTurns.get(`${CHILD}:turn:2`) === "completed"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "running", result: null }); + assert.deepEqual( + watch.state.roster?.map((task) => task.taskId), + ["call-background"], + ); + assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + gate.release("final"); + yield* watch.until( + () => + watch.calls.get("Sleep")?.status === "completed" && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "TESTS_PASSED" }); + }), + ); + + it.effect( + "settles a subagent kept by a running report when its next busy period writes nothing", + () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["idle"]); + const { runtime, thread } = yield* resumed( + [ + ...reportedRunning, + event("session.execution.started", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: CHILD }, "idle"), + ], + { replayGate: gate }, + ); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("idle"))); + yield* watch.until(() => watch.childTurns.get(`${CHILD}:turn:2`) === "running"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "running", result: null }); + gate.release("idle"); + yield* watch.until( + () => + watch.calls.get("Sleep")?.status === "completed" && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: STARTED }); + }), + ); + + it.effect.each([ + { name: "nothing runs below it", active: {}, result: STARTED }, + { + name: "its child runs again", + active: { [CHILD]: { type: "running" } }, + result: "TESTS_PASSED", + }, + ])( + "after a reconnect, settles a subagent kept by a running report only when $name", + ({ active, result }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...reportedRunning, + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", active), + ...(CHILD in active + ? [ + out("permission.list", { sessionID: CHILD }), + replyData("permission.list", []), + out("session.form.list", { sessionID: CHILD }), + replyData("session.form.list", []), + ...finished().slice(1), + ] + : []), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => { + const status = watch.calls.get("Sleep")?.status; + return status !== undefined && status !== "running" && watch.state.roster?.length === 0; + }); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result }); + }), + ); + const MIDDLE = "ses_middle0000000000000000000"; const DEEP = "ses_grandchild00000000000000"; const toolOf = (session: string, id: string) => ({ diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9e14f8c4ef36b..b7b0cba43fecb 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -298,6 +298,8 @@ interface SubagentCall { run: number | undefined; /** That turn's last text once it ended, which OpenCode sends as the run's report. */ answer: string | undefined; + /** The output of a report sent while the child's own background work still ran; a later report settles the call. */ + reported: string | undefined; child: ThreadState | undefined; status: OrchestrationV2Subagent["status"]; result: string | null; @@ -605,6 +607,11 @@ const reportOutcome = (state: string | undefined) => const subagentOutput = (text: string) => /^]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text; +// OpenCode keeps "completed" in a report's metadata and says "running" only in its tag +// when the child goes idle with its own background work still running. +const reportsRunningWork = (text: string) => + /^<(?:subagent|background-result)\b[^>]*?\sstate="running"/.test(text.trimStart()); + const isContinuation = (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) => turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider"; @@ -2437,6 +2444,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr for (const attached of callsAttachedTo(state)) { yield* settleCall(attached, terminal.status, terminal.failure.message); } + } else if ( + turn.startedSteps === 0 && + turn.answer === undefined && + !turn.missedEvents && + !hasBackground(state) + ) { + // OpenCode reports a busy period only when it wrote a new answer, so no later report comes. + for (const attached of callsAttachedTo(state)) { + if (attached.reported !== undefined) + yield* settleCall(attached, "completed", attached.reported); + } } return; } @@ -2818,6 +2836,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr background: false, run: undefined, answer: undefined, + reported: undefined, child: undefined, status: "running", result: null, @@ -3245,6 +3264,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr written !== undefined && candidate.run < written ? [candidate.call] : [], ); const outcome = reportOutcome(stringField(payload.metadata, "state")); + const running = outcome === "completed" && reportsRunningWork(payload.text); state.reports.set(inboxId, { inboxId, childId, @@ -3253,7 +3273,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr kind: "subagent", label: call?.title ?? stringField(payload.metadata, "description"), childThreadId: call?.child?.subagent?.appThread.id, - outcome, + outcome: running ? "updated" : outcome, }, }); const status = state.stoppedChildren.has(childId) @@ -3264,7 +3284,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ? "cancelled" : "completed"; for (const each of lost) yield* settleCall(each, "completed", each.answer); - for (const each of calls) yield* settleCall(each, status, output); + for (const each of calls) { + if (running && status === "completed" && each.background) each.reported = output; + else yield* settleCall(each, status, output); + } }); const holderOf = (sessionId: string) => { @@ -3807,7 +3830,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr for (const state of background) { for (const call of runningCalls(state)) { const child = call.child?.sessionId; - if (child === undefined || !(child in active)) { + if (call.reported !== undefined && call.child !== undefined) { + // Its child already reported; only work still running below it keeps the call. + const below = sessionsOf(call.child); + const working = + below.some((session) => session.sessionId in active) || + [...shells.values()].some( + (shell) => shell.running && below.includes(shell.state), + ); + if (!working) yield* settleCall(call, "completed", call.reported); + } else if (child === undefined || !(child in active)) { yield* settleCall(call, "interrupted", LOST_BACKGROUND); } } From b0e12caa6181ddf4f4fd0f8c628f25bb8184908c Mon Sep 17 00:00:00 2001 From: Nikita Koynov <43469098+nkoynov@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:42:32 +0200 Subject: [PATCH 2/7] fix(opencode): settle kept subagents on their child's next report and recheck their work on reconnect --- .../Adapters/OpenCode2AdapterV2.test.ts | 320 +++++++++++++++++- .../src/server/v2/OpenCode2Client.ts | 16 + .../src/server/v2/adapter.ts | 121 +++++-- 3 files changed, 412 insertions(+), 45 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 6b32a14026f93..daf2cdc7cfb7b 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1751,20 +1751,35 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { returnedRunning(tool.id), ]; }; - const childReport = (inboxID: string, text: string, description = "Sleep", tag = "completed") => - event("session.inbox.enqueued", { - inboxID, - sessionID: SESSION, - item: { - type: "synthetic", - payload: { - text: `\n${text}\n`, - description, - metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" }, + const childReport = ( + inboxID: string, + text: string, + description = "Sleep", + tag = "completed", + label?: string, + ) => + event( + "session.inbox.enqueued", + { + inboxID, + sessionID: SESSION, + item: { + type: "synthetic", + payload: { + text: `\n${text}\n`, + description, + metadata: { + source: "subagent", + childID: CHILD, + agent: "General", + state: tag === "running" ? "completed" : tag, + }, + }, + delivery: "steer", }, - delivery: "steer", }, - }); + label, + ); const watchCalls = ( runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, thread: OrchestrationV2ProviderThread, @@ -1773,6 +1788,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { const calls = new Map(); const callsById = new Map(); const childTurns = new Map(); + const attached = new Set(); const callsAtChildTurnStart = new Map< string, Record @@ -1795,6 +1811,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { status: event.subagent.status, result: event.subagent.result, }); + if (event.subagent.childThreadId !== null) attached.add(event.subagent.title); } if (event.type === "provider_thread.updated" && event.providerThread.id === thread.id) { state.roster = event.providerThread.pendingBackgroundTasks; @@ -1828,7 +1845,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* until(check); }); }); - return { calls, callsById, callsAtChildTurnStart, childTurns, state, until }; + return { calls, callsById, callsAtChildTurnStart, childTurns, attached, state, until }; }); const launchedAndRunning = [ ...backgroundLaunch(CHILD), @@ -2162,6 +2179,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { model: { id: "big-pickle", providerID: "opencode", variant: "default" }, started: 1, }); + const settled = (status: string | undefined) => status !== undefined && status !== "running"; const STARTED = "TESTS_STARTED\n\nBackground work still running:\n- shell (sh_tests): npm test"; // The child goes idle with its own work running, and OpenCode reports it as running. const reportedRunning = [ @@ -2229,12 +2247,284 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { () => watch.calls.get("Sleep")?.status === "completed" && watch.state.roster?.length === 0, ); - assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: STARTED }); + assert.deepEqual(watch.calls.get("Sleep"), { + status: "completed", + result: "TESTS_STARTED", + }); }), ); + it.effect("waits for a cancelled report after a kept subagent's turn is interrupted", () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["cancelled"]); + const { runtime, thread } = yield* resumed( + [ + ...reportedRunning, + event("session.execution.started", { sessionID: CHILD }), + event("session.execution.interrupted", { sessionID: CHILD }), + childReport("msg_report_2", "Stopped", "Sleep", "cancelled", "cancelled"), + ], + { replayGate: gate }, + ); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("cancelled"))); + yield* watch.until(() => watch.childTurns.get(`${CHILD}:turn:2`) === "interrupted"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "running", result: null }); + gate.release("cancelled"); + yield* watch.until(() => watch.calls.get("Sleep")?.status !== "running"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "cancelled", result: "Stopped" }); + }), + ); + + it.effect("settles a call that joined a kept subagent with the subagent's last report", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...launchedAndRunning, + childSaid("TESTS_STARTED"), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_1", STARTED, "Sleep", "running"), + ...callAgain({ background: true }), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + childSaid("ALSO_DONE", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport( + "msg_report_2", + "ALSO_DONE\n\nBackground work still running:\n- shell (sh_tests): npm test", + "Again", + "running", + ), + event("session.execution.started", { sessionID: CHILD }), + childStep(3), + childSaid("TESTS_PASSED", 3), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_3", "TESTS_PASSED", "Again"), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["Sleep", "Again"].every((title) => settled(watch.calls.get(title)?.status)) && + watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.calls), { + Sleep: { status: "completed", result: "TESTS_PASSED" }, + Again: { status: "completed", result: "TESTS_PASSED" }, + }); + }), + ); + + it.effect("settles a call whose Stop never reached its child at the child's running report", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...backgroundLaunch(CHILD), + out("session.interrupt", { sessionID: CHILD }), + reply("session.interrupt", { status: 500, body: {} }), + out("session.interrupt", { sessionID: SESSION }), + reply("session.interrupt", { interrupted: true }), + event("session.execution.interrupted", { sessionID: SESSION }), + childReport("msg_report_1", STARTED, "Sleep", "running"), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => watch.attached.has("Sleep")); + yield* runtime.interruptTurn({ + providerThread: thread, + providerTurnId: yield* providerTurnId, + requestRuntimeRestart: true, + }); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.equal(watch.calls.get("Sleep")?.status, "interrupted"); + }), + ); + + it.effect("settles a completed report whose description quotes a running state", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...launchedAndRunning, + childSaid("DONE"), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_1", "DONE", 'Review state="running" fix'), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => settled(watch.calls.get("Sleep")?.status) && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "DONE" }); + }), + ); + + it.effect("matches a report of a run that wrote no text to that run", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...launchedAndRunning, + ...callAgain({ background: true }), + childSaid("FIRST_OK"), + event("session.execution.succeeded", { sessionID: CHILD }), + ...callAgain({ background: true }, { id: "call-later", writesRules: false }), + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_2", "Subagent completed without a text response.", "Again"), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["call-background", "call-again", "call-later"].every( + (id) => watch.callsById.get(id)?.status === "completed", + ) && watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.callsById), { + "call-background": { status: "completed", result: "FIRST_OK" }, + "call-again": { status: "completed", result: "FIRST_OK" }, + "call-later": { + status: "completed", + result: "Subagent completed without a text response.", + }, + }); + }), + ); + + const GRAND = "ses_f1485c529ffeGrandchild00000"; + const grand = { sessionID: CHILD, assistantMessageID: "msg_child_grand", id: "call-grand" }; + const running = (body: string) => + `${body}\n\nBackground work still running:\n- shell (sh_tests): npm test`; + // The child and its own background subagent both report while the grandchild's work runs. + const keptChain = [ + ...launchedAndRunning, + event("session.tool.input.started", { ...grand, name: "subagent" }), + event("session.tool.called", { + ...grand, + name: "subagent", + input: { description: "Grand", prompt: "test", background: true }, + executed: false, + }), + event("session.created", { ...childCreated(GRAND), parentID: CHILD, title: "Grand" }), + event("session.tool.progress", { ...grand, metadata: { sessionID: GRAND, status: "running" } }), + event("session.tool.success", { + ...grand, + content: [{ type: "text", text: "The subagent is working in the background." }], + metadata: { sessionID: GRAND, status: "running" }, + executed: true, + }), + event("session.execution.started", { sessionID: GRAND }), + childSaid("CHILD_STARTED"), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_1", running("CHILD_STARTED"), "Sleep", "running"), + event("session.text.ended", { + sessionID: GRAND, + assistantMessageID: "msg_grand_1", + ordinal: 0, + text: "GRAND_STARTED", + }), + event("session.execution.succeeded", { sessionID: GRAND }), + event("session.inbox.enqueued", { + inboxID: "msg_grand_report", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: `\n${running("GRAND_STARTED")}\n`, + description: "Grand", + metadata: { source: "subagent", childID: GRAND, agent: "General", state: "completed" }, + }, + delivery: "steer", + }, + }), + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + childSaid("CHILD_WAITING", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_2", running("CHILD_WAITING"), "Sleep", "running"), + ]; + const settledChain = (replay: ReadonlyArray) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed(replay); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["Sleep", "Grand"].every((title) => watch.calls.get(title)?.status === "completed") && + watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.calls), { + Sleep: { status: "completed", result: "CHILD_STARTED" }, + Grand: { status: "completed", result: "GRAND_STARTED" }, + }); + }); + + it.effect("releases kept subagents up a chain when the deepest one's work ends quietly", () => + settledChain([ + ...keptChain, + event("session.execution.started", { sessionID: GRAND }), + event("session.execution.succeeded", { sessionID: GRAND }), + ]), + ); + + it.effect("after a reconnect, settles a chain of kept subagents whose work all ended", () => + settledChain([ + ...keptChain, + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", {}), + ]), + ); + + it.effect.each([ + { + name: "a Code Mode script still runs below it", + jobs: [{ kind: "codemode", status: "running" }], + }, + { + name: "only finished jobs remain below it", + jobs: [{ kind: "codemode", status: "completed" }], + }, + ])("after a reconnect, keeps a kept subagent only while $name", ({ jobs }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + ...reportedRunning, + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("rpc.call", ""), + out("rpc.call", ""), + reply("rpc.call", { output: null }), + reply("rpc.call", { output: null }), + out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }), + reply("job.list", { data: [] }), + out("job.list", { sessionID: CHILD, kind: "shell", descendants: "true" }), + reply("job.list", { data: [] }), + out("session.active"), + replyData("session.active", {}), + out("job.list", { sessionID: CHILD, descendants: "true" }), + reply("job.list", { + data: jobs.map((job) => ({ ...job, id: "job_1", sessionID: CHILD })), + }), + // The reconnect has finished before this arrives; only a call it kept takes it. + childReport("msg_report_2", "TESTS_PASSED"), + ], + { version: "2.2.6" }, + ); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.deepEqual(watch.calls.get("Sleep"), { + status: "completed", + result: jobs[0]!.status === "running" ? "TESTS_PASSED" : "TESTS_STARTED", + }); + }), + ); + it.effect.each([ - { name: "nothing runs below it", active: {}, result: STARTED }, + { name: "nothing runs below it", active: {}, result: "TESTS_STARTED" }, { name: "its child runs again", active: { [CHILD]: { type: "running" } }, diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts index 1cc1190de00dc..4c9217ad8e1f1 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts @@ -91,6 +91,7 @@ const NativeImageJob = Schema.Struct({ const decodeJobs = Schema.decodeUnknownEffect( Schema.Struct({ data: Schema.Array(Schema.Unknown) }), ); +const JobStatuses = Schema.Struct({ data: Schema.Array(Schema.Struct({ status: Schema.String })) }); const decodeImageJob = Schema.decodeUnknownOption(NativeImageJob); /** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */ @@ -102,6 +103,10 @@ export interface OpenCode2Api { readonly shellJobs?: ( sessionID: string, ) => Effect.Effect; + /** Running background jobs of any kind owned by a session or the subagent sessions below it. */ + readonly runningJobs?: ( + sessionID: string, + ) => Effect.Effect; readonly imageJobs: ( sessionID: string, ) => Effect.Effect, OpenCode2ImageError>; @@ -291,6 +296,17 @@ export const make = Effect.gen(function* () { Effect.flatMap(HttpClientResponse.schemaBodyJson(ShellJobs)), ); }), + runningJobs: Effect.fn("OpenCode2Client.runningJobs")(function (sessionID: string) { + return authenticated + .get(`${baseUrl}/api/experimental/job`, { + urlParams: { sessionID, descendants: "true" }, + }) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(JobStatuses)), + Effect.map((page) => page.data.filter((job) => job.status === "running").length), + ); + }), imageJobs: (sessionID: string) => authenticated .get(`${baseUrl}/api/experimental/job`, { diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index b7b0cba43fecb..aa223f1f32849 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -607,10 +607,19 @@ const reportOutcome = (state: string | undefined) => const subagentOutput = (text: string) => /^]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text; -// OpenCode keeps "completed" in a report's metadata and says "running" only in its tag -// when the child goes idle with its own background work still running. +// When the child goes idle with its own background work still running, OpenCode keeps "completed" +// in the report's metadata, says "running" only in the tag's state attribute (the description +// attribute after it is not escaped) and appends the list of that work to the body. const reportsRunningWork = (text: string) => - /^<(?:subagent|background-result)\b[^>]*?\sstate="running"/.test(text.trimStart()); + /^]*?\sstate="([^"]*)"/.exec(text.trimStart())?.[1] === "running"; + +const STILL_RUNNING = "\n\nBackground work still running:\n"; +// OpenCode's report body for a run that ended without text. +const NO_TEXT = "Subagent completed without a text response."; +const withoutRunningWork = (output: string) => { + const at = output.lastIndexOf(STILL_RUNNING); + return at === -1 ? output : output.slice(0, at); +}; const isContinuation = (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) => turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider"; @@ -2236,6 +2245,22 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* emitSubagent(call); }); + // OpenCode reports a busy period only when it wrote a new answer. A child whose work ended in a + // quiet one never reports again, nor do the idle subagents above it that were waiting on it. + const releaseQuiet = Effect.fnUntraced(function* (state: ThreadState) { + for ( + let current: ThreadState = state; + current.subagent !== undefined; + current = current.subagent.call.state + ) { + if (current.active !== undefined || busy.has(current.sessionId) || hasBackground(current)) + return; + const kept = callsAttachedTo(current).filter((call) => call.reported !== undefined); + if (kept.length === 0) return; + for (const call of kept) yield* settleCall(call, "completed", call.reported); + } + }); + const startChildTurn = Effect.fnUntraced(function* (child: ThreadState) { const subagent = child.subagent; if (subagent === undefined || child.active !== undefined) return; @@ -2445,16 +2470,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* settleCall(attached, terminal.status, terminal.failure.message); } } else if ( + terminal.status === "completed" && turn.startedSteps === 0 && turn.answer === undefined && - !turn.missedEvents && - !hasBackground(state) + !turn.missedEvents ) { - // OpenCode reports a busy period only when it wrote a new answer, so no later report comes. - for (const attached of callsAttachedTo(state)) { - if (attached.reported !== undefined) - yield* settleCall(attached, "completed", attached.reported); - } + yield* releaseQuiet(state); } return; } @@ -3240,10 +3261,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const childId = stringField(payload.metadata, "childID"); if (stringField(payload.metadata, "source") !== "subagent" || childId === undefined) return; strays.delete(childId); - const open = [...state.calls.values()].filter( + const outcome = reportOutcome(stringField(payload.metadata, "state")); + const stopped = state.stoppedChildren.has(childId); + const running = outcome === "completed" && !stopped && reportsRunningWork(payload.text); + const output = subagentOutput(payload.text); + const answer = running ? withoutRunningWork(output) : output; + const reporting = [...state.calls.values()].filter( (candidate) => candidate.child?.sessionId === childId, ); - const output = subagentOutput(payload.text); + // Calls an earlier running report kept wait for the child's work, not for one of its runs. + const kept = reporting.filter((candidate) => candidate.reported !== undefined); + const open = reporting.filter((candidate) => candidate.reported === undefined); + const answered = (candidate: SubagentCall) => + candidate.answer === answer || (candidate.answer === undefined && answer === NO_TEXT); const started = open .flatMap((candidate) => candidate.run === undefined ? [] : [{ call: candidate, run: candidate.run }], @@ -3252,9 +3282,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // The report names only the child, and reports arrive in order. So it belongs to the oldest // open run, unless that run ended with a different text: then its own report is lost. const next = started.find( - (candidate) => candidate.call.answer === undefined || candidate.call.answer === output, + (candidate) => candidate.call.answer === undefined || answered(candidate.call), ); - const written = next?.call.answer === output ? next.run : undefined; + const written = next !== undefined && answered(next.call) ? next.run : undefined; const call = written === undefined ? open[0] : next?.call; const calls = call?.run === undefined @@ -3263,20 +3293,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const lost = started.flatMap((candidate) => written !== undefined && candidate.run < written ? [candidate.call] : [], ); - const outcome = reportOutcome(stringField(payload.metadata, "state")); - const running = outcome === "completed" && reportsRunningWork(payload.text); + const named = call ?? kept[0]; state.reports.set(inboxId, { inboxId, childId, text: payload.text, report: { kind: "subagent", - label: call?.title ?? stringField(payload.metadata, "description"), - childThreadId: call?.child?.subagent?.appThread.id, + label: named?.title ?? stringField(payload.metadata, "description"), + childThreadId: named?.child?.subagent?.appThread.id, outcome: running ? "updated" : outcome, }, }); - const status = state.stoppedChildren.has(childId) + const status = stopped ? "interrupted" : outcome === "failed" ? "failed" @@ -3285,9 +3314,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr : "completed"; for (const each of lost) yield* settleCall(each, "completed", each.answer); for (const each of calls) { - if (running && status === "completed" && each.background) each.reported = output; + if (running && each.background) each.reported = answer; else yield* settleCall(each, status, output); } + // Any other report means the child went idle with nothing left running. + if (!running) for (const each of kept) yield* settleCall(each, status, output); }); const holderOf = (sessionId: string) => { @@ -3825,24 +3856,54 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr .withPermit(recoverImages(state).pipe(Effect.timeout(INVENTORY_TIMEOUT))) .pipe(Effect.ignore({ log: true })); } + // OpenCode's own jobs below a kept call (shells, Code Mode scripts, subagents, images); a + // failed read counts as work. + const jobsBelow = new Map(); + if ( + compareSemverVersions(connection.version, "2.2.6") >= 0 && + connection.runningJobs !== undefined + ) { + for (const state of background) { + for (const call of runningCalls(state)) { + const child = call.child?.sessionId; + if (call.reported === undefined || child === undefined || jobsBelow.has(child)) + continue; + const jobs = yield* connection + .runningJobs(child) + .pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.option); + jobsBelow.set(child, Option.getOrUndefined(jobs)); + } + } + } yield* lock.withPermit( Effect.gen(function* () { for (const state of background) { + const kept: Array = []; for (const call of runningCalls(state)) { const child = call.child?.sessionId; - if (call.reported !== undefined && call.child !== undefined) { - // Its child already reported; only work still running below it keeps the call. - const below = sessionsOf(call.child); - const working = - below.some((session) => session.sessionId in active) || - [...shells.values()].some( - (shell) => shell.running && below.includes(shell.state), - ); - if (!working) yield* settleCall(call, "completed", call.reported); - } else if (child === undefined || !(child in active)) { + if (call.reported !== undefined && call.child !== undefined) kept.push(call); + else if (child === undefined || !(child in active)) { yield* settleCall(call, "interrupted", LOST_BACKGROUND); } } + // Its child already reported; only work still running below it keeps a kept call. + // Deepest first, so the calls below one are settled before it is checked. + const deepestFirst = kept.toSorted( + (left, right) => + callsAbove(right.state.sessionId).length - callsAbove(left.state.sessionId).length, + ); + for (const call of deepestFirst) { + if (call.child === undefined || !isOrchestrationV2WorkActive(call.status)) continue; + const below = sessionsOf(call.child); + const jobs = jobsBelow.has(call.child.sessionId) + ? jobsBelow.get(call.child.sessionId) + : 0; + const working = + jobs === undefined || + jobs > 0 || + below.some((session) => session.sessionId in active || owesWork(session)); + if (!working) yield* settleCall(call, "completed", call.reported); + } const sessions = sessionsOf(state); for (const session of sessions) { discardWakes(session, session.wakes.splice(0)); From 0e7ca6a61918825e280613dab184d8a4a5f56ce7 Mon Sep 17 00:00:00 2001 From: Nikita Koynov <43469098+nkoynov@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:20:15 +0200 Subject: [PATCH 3/7] fix(opencode): after a reconnect keep a kept subagent only for running sessions or non-subagent jobs --- .../Adapters/OpenCode2AdapterV2.test.ts | 115 +++++++++++++----- .../src/server/v2/OpenCode2Client.ts | 12 +- .../src/server/v2/adapter.ts | 61 +++++----- 3 files changed, 121 insertions(+), 67 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index daf2cdc7cfb7b..b8f6299b203de 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2455,7 +2455,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { watch.state.roster?.length === 0, ); assert.deepEqual(Object.fromEntries(watch.calls), { - Sleep: { status: "completed", result: "CHILD_STARTED" }, + Sleep: { status: "completed", result: "CHILD_WAITING" }, Grand: { status: "completed", result: "GRAND_STARTED" }, }); }); @@ -2478,49 +2478,100 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ]), ); + const jobsBelow = (...jobs: ReadonlyArray<{ kind: string; status: string }>) => ({ + data: jobs.map((job, index) => ({ ...job, id: `job_${index}`, sessionID: CHILD })), + }); it.effect.each([ { name: "a Code Mode script still runs below it", - jobs: [{ kind: "codemode", status: "running" }], + listed: jobsBelow({ kind: "codemode", status: "running" }), + result: "TESTS_PASSED", }, { name: "only finished jobs remain below it", - jobs: [{ kind: "codemode", status: "completed" }], + listed: jobsBelow({ kind: "codemode", status: "completed" }), + result: "TESTS_STARTED", }, - ])("after a reconnect, keeps a kept subagent only while $name", ({ jobs }) => - Effect.gen(function* () { - const { runtime, thread } = yield* resumed( - [ + { + name: "OpenCode lists only a stored subagent job below it", + listed: jobsBelow({ kind: "subagent", status: "running" }), + result: "TESTS_STARTED", + }, + { + name: "OpenCode's job list can't be read", + listed: { status: 500, body: {} }, + result: "TESTS_STARTED", + }, + ])( + "after a reconnect, judges a kept subagent by OpenCode's jobs when $name", + ({ listed, result }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + ...reportedRunning, + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("rpc.call", ""), + out("rpc.call", ""), + reply("rpc.call", { output: null }), + reply("rpc.call", { output: null }), + out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }), + reply("job.list", { data: [] }), + out("job.list", { sessionID: CHILD, kind: "shell", descendants: "true" }), + reply("job.list", { data: [] }), + out("session.active"), + replyData("session.active", {}), + out("job.list", { sessionID: CHILD, descendants: "true" }), + reply("job.list", listed), + // The reconnect has finished before this arrives; only a call it kept takes it. + childReport("msg_report_2", "TESTS_PASSED"), + ], + { version: "2.2.6" }, + ); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result }); + }), + ); + + it.effect( + "after a reconnect, settles a kept subagent whose session holds only an unread report", + () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ ...reportedRunning, + event("session.inbox.enqueued", { + inboxID: "msg_grand_report", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: `\nGRAND_OK\n`, + description: "Grand", + metadata: { + source: "subagent", + childID: GRAND, + agent: "General", + state: "completed", + }, + }, + delivery: "steer", + }, + }), { type: "runtime_exit", status: "success" } as const, out("event.subscribe"), - out("rpc.call", ""), - out("rpc.call", ""), - reply("rpc.call", { output: null }), - reply("rpc.call", { output: null }), - out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }), - reply("job.list", { data: [] }), - out("job.list", { sessionID: CHILD, kind: "shell", descendants: "true" }), - reply("job.list", { data: [] }), out("session.active"), replyData("session.active", {}), - out("job.list", { sessionID: CHILD, descendants: "true" }), - reply("job.list", { - data: jobs.map((job) => ({ ...job, id: "job_1", sessionID: CHILD })), - }), - // The reconnect has finished before this arrives; only a call it kept takes it. - childReport("msg_report_2", "TESTS_PASSED"), - ], - { version: "2.2.6" }, - ); - const watch = yield* watchCalls(runtime, thread); - yield* runtime.startTurn(withLineage(thread)); - yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); - assert.deepEqual(watch.calls.get("Sleep"), { - status: "completed", - result: jobs[0]!.status === "running" ? "TESTS_PASSED" : "TESTS_STARTED", - }); - }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.deepEqual(watch.calls.get("Sleep"), { + status: "completed", + result: "TESTS_STARTED", + }); + }), ); it.effect.each([ diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts index 4c9217ad8e1f1..9efc2844a4582 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts @@ -91,7 +91,9 @@ const NativeImageJob = Schema.Struct({ const decodeJobs = Schema.decodeUnknownEffect( Schema.Struct({ data: Schema.Array(Schema.Unknown) }), ); -const JobStatuses = Schema.Struct({ data: Schema.Array(Schema.Struct({ status: Schema.String })) }); +const JobStatuses = Schema.Struct({ + data: Schema.Array(Schema.Struct({ kind: Schema.String, status: Schema.String })), +}); const decodeImageJob = Schema.decodeUnknownOption(NativeImageJob); /** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */ @@ -103,7 +105,7 @@ export interface OpenCode2Api { readonly shellJobs?: ( sessionID: string, ) => Effect.Effect; - /** Running background jobs of any kind owned by a session or the subagent sessions below it. */ + /** Running background jobs other than subagents owned by a session or the subagent sessions below it. */ readonly runningJobs?: ( sessionID: string, ) => Effect.Effect; @@ -304,7 +306,11 @@ export const make = Effect.gen(function* () { .pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(JobStatuses)), - Effect.map((page) => page.data.filter((job) => job.status === "running").length), + Effect.map( + (page) => + page.data.filter((job) => job.kind !== "subagent" && job.status === "running") + .length, + ), ); }), imageJobs: (sessionID: string) => diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index aa223f1f32849..add839ab84575 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -1076,9 +1076,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }; let replaying: Wake | undefined; - const owesWork = (state: ThreadState) => + const runsJobs = (state: ThreadState) => [...shells.values()].some((shell) => shell.state === state && shell.running) || - [...state.imageJobs.values()].some((job) => job.status === "running") || + [...state.imageJobs.values()].some((job) => job.status === "running"); + + const owesWork = (state: ThreadState) => + runsJobs(state) || state.wakes.length > 0 || state.reports.size > 0 || (state.subagent !== undefined && busy.has(state.sessionId)) || @@ -3317,8 +3320,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (running && each.background) each.reported = answer; else yield* settleCall(each, status, output); } - // Any other report means the child went idle with nothing left running. - if (!running) for (const each of kept) yield* settleCall(each, status, output); + // Calls kept earlier take the child's latest text; a report not tagged running means the + // child went idle with nothing left running. + for (const each of kept) { + if (running) each.reported = answer; + else yield* settleCall(each, status, output); + } }); const holderOf = (sessionId: string) => { @@ -3856,9 +3863,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr .withPermit(recoverImages(state).pipe(Effect.timeout(INVENTORY_TIMEOUT))) .pipe(Effect.ignore({ log: true })); } - // OpenCode's own jobs below a kept call (shells, Code Mode scripts, subagents, images); a - // failed read counts as work. - const jobsBelow = new Map(); + // OpenCode's running jobs below a kept call other than subagents (shells, Code Mode scripts, + // images): it also lists stored subagent jobs it never closed, and subagents count by their + // sessions. A failed read counts as none. + const jobsBelow = new Map(); if ( compareSemverVersions(connection.version, "2.2.6") >= 0 && connection.runningJobs !== undefined @@ -3868,42 +3876,31 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const child = call.child?.sessionId; if (call.reported === undefined || child === undefined || jobsBelow.has(child)) continue; - const jobs = yield* connection - .runningJobs(child) - .pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.option); - jobsBelow.set(child, Option.getOrUndefined(jobs)); + const jobs = yield* connection.runningJobs(child).pipe( + Effect.timeout(INVENTORY_TIMEOUT), + Effect.orElseSucceed(() => 0), + ); + jobsBelow.set(child, jobs); } } } yield* lock.withPermit( Effect.gen(function* () { for (const state of background) { - const kept: Array = []; for (const call of runningCalls(state)) { const child = call.child?.sessionId; - if (call.reported !== undefined && call.child !== undefined) kept.push(call); - else if (child === undefined || !(child in active)) { + if (call.reported !== undefined && call.child !== undefined) { + // Its child already reported; only a session or job still running below it keeps it. + const working = + (jobsBelow.get(call.child.sessionId) ?? 0) > 0 || + sessionsOf(call.child).some( + (session) => session.sessionId in active || runsJobs(session), + ); + if (!working) yield* settleCall(call, "completed", call.reported); + } else if (child === undefined || !(child in active)) { yield* settleCall(call, "interrupted", LOST_BACKGROUND); } } - // Its child already reported; only work still running below it keeps a kept call. - // Deepest first, so the calls below one are settled before it is checked. - const deepestFirst = kept.toSorted( - (left, right) => - callsAbove(right.state.sessionId).length - callsAbove(left.state.sessionId).length, - ); - for (const call of deepestFirst) { - if (call.child === undefined || !isOrchestrationV2WorkActive(call.status)) continue; - const below = sessionsOf(call.child); - const jobs = jobsBelow.has(call.child.sessionId) - ? jobsBelow.get(call.child.sessionId) - : 0; - const working = - jobs === undefined || - jobs > 0 || - below.some((session) => session.sessionId in active || owesWork(session)); - if (!working) yield* settleCall(call, "completed", call.reported); - } const sessions = sessionsOf(state); for (const session of sessions) { discardWakes(session, session.wakes.splice(0)); From b76e68c362fa1e3ae2ec87c9c2c6d44f27ce8063 Mon Sep 17 00:00:00 2001 From: Nikita Koynov <43469098+nkoynov@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:51:58 +0200 Subject: [PATCH 4/7] fix(opencode): release kept subagents above a child turn that failed without a report --- .../Adapters/OpenCode2AdapterV2.test.ts | 22 +++++++++++++++++++ .../src/server/v2/adapter.ts | 3 +++ 2 files changed, 25 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index b8f6299b203de..1e758c5b6460f 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2468,6 +2468,28 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ]), ); + it.effect("releases a kept subagent above one whose turn failed without a report", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...keptChain, + event("session.execution.started", { sessionID: GRAND }), + event("session.execution.failed", { + sessionID: GRAND, + error: { type: "unknown", message: "quota" }, + }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["Sleep", "Grand"].every((title) => settled(watch.calls.get(title)?.status)) && + watch.state.roster?.length === 0, + ); + assert.equal(watch.calls.get("Grand")?.status, "failed"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "CHILD_WAITING" }); + }), + ); + it.effect("after a reconnect, settles a chain of kept subagents whose work all ended", () => settledChain([ ...keptChain, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index add839ab84575..ffccfb87ada35 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -2472,6 +2472,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr for (const attached of callsAttachedTo(state)) { yield* settleCall(attached, terminal.status, terminal.failure.message); } + // No report follows either, so idle subagents above that were waiting on it are released. + const caller = state.subagent?.call.state; + if (caller !== undefined) yield* releaseQuiet(caller); } else if ( terminal.status === "completed" && turn.startedSteps === 0 && From 35cb90c322ab10d34f41cdb82c68d0f5ab2ea2b0 Mon Sep 17 00:00:00 2001 From: Nikita Koynov <43469098+nkoynov@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:03:28 +0200 Subject: [PATCH 5/7] fix(opencode): release a kept subagent after a quiet busy period that a reconnect cut into --- .../Adapters/OpenCode2AdapterV2.test.ts | 40 ++++++++++++++++++- .../src/server/v2/adapter.ts | 12 +++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 1e758c5b6460f..5a22478a2807f 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2254,6 +2254,41 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + const reconnectedWithChildActive = [ + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", { [CHILD]: { type: "running" } }), + out("permission.list", { sessionID: CHILD }), + replyData("permission.list", []), + out("session.form.list", { sessionID: CHILD }), + replyData("session.form.list", []), + ]; + it.effect.each([ + { + name: "spans a reconnect", + replay: [ + event("session.execution.started", { sessionID: CHILD }), + ...reconnectedWithChildActive, + ], + }, + { name: "starts while the stream is down", replay: reconnectedWithChildActive }, + ])("settles a kept subagent whose quiet busy period $name", ({ replay }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...reportedRunning, + ...replay, + event("session.execution.succeeded", { sessionID: CHILD }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => settled(watch.calls.get("Sleep")?.status) && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "TESTS_STARTED" }); + }), + ); + it.effect("waits for a cancelled report after a kept subagent's turn is interrupted", () => Effect.gen(function* () { const gate = makeProviderReplayGate(["cancelled"]); @@ -2619,7 +2654,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { replyData("permission.list", []), out("session.form.list", { sessionID: CHILD }), replyData("session.form.list", []), - ...finished().slice(1), + // Its end without a turn here would release the call on its own. + childStep(2), + childSaid("TESTS_PASSED", 2), + childReport("msg_report_2", "TESTS_PASSED"), ] : []), ]); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index ffccfb87ada35..2671351c0e740 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -2477,9 +2477,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (caller !== undefined) yield* releaseQuiet(caller); } else if ( terminal.status === "completed" && - turn.startedSteps === 0 && turn.answer === undefined && - !turn.missedEvents + // A turn that missed events may have written unseen; when unsure, release. + (turn.startedSteps === 0 || turn.missedEvents) ) { yield* releaseQuiet(state); } @@ -3630,6 +3630,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const turn = state.active; if (turn === undefined) { if (started && state.subagent === undefined) return yield* onWake(state); + // A subagent busy period that began while the stream was down ends without a turn here. + if ( + state.subagent !== undefined && + (event.type === "session.execution.succeeded" || + event.type === "session.execution.failed") + ) { + return yield* releaseQuiet(state); + } return; } if (turn.awaitingStart) { From fb158f6ddd26e684f2958cb98c7f2125c2607b2c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 02:11:45 +0000 Subject: [PATCH 6/7] test(opencode): trim running-report subagent tests to the regressions they guard Drops the interrupted-turn wait case and a job-list row that duplicates the subagent-kind filter row, and returns childReport to a single tag parameter. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 71 +++++-------------- 1 file changed, 17 insertions(+), 54 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 5a22478a2807f..f8301cd636ec3 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1751,35 +1751,26 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { returnedRunning(tool.id), ]; }; - const childReport = ( - inboxID: string, - text: string, - description = "Sleep", - tag = "completed", - label?: string, - ) => - event( - "session.inbox.enqueued", - { - inboxID, - sessionID: SESSION, - item: { - type: "synthetic", - payload: { - text: `\n${text}\n`, - description, - metadata: { - source: "subagent", - childID: CHILD, - agent: "General", - state: tag === "running" ? "completed" : tag, - }, + const childReport = (inboxID: string, text: string, description = "Sleep", tag = "completed") => + event("session.inbox.enqueued", { + inboxID, + sessionID: SESSION, + item: { + type: "synthetic", + payload: { + text: `\n${text}\n`, + description, + // OpenCode tags a report "running" only in the text; its metadata still says completed. + metadata: { + source: "subagent", + childID: CHILD, + agent: "General", + state: tag === "running" ? "completed" : tag, }, - delivery: "steer", }, + delivery: "steer", }, - label, - ); + }); const watchCalls = ( runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime, thread: OrchestrationV2ProviderThread, @@ -2289,29 +2280,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); - it.effect("waits for a cancelled report after a kept subagent's turn is interrupted", () => - Effect.gen(function* () { - const gate = makeProviderReplayGate(["cancelled"]); - const { runtime, thread } = yield* resumed( - [ - ...reportedRunning, - event("session.execution.started", { sessionID: CHILD }), - event("session.execution.interrupted", { sessionID: CHILD }), - childReport("msg_report_2", "Stopped", "Sleep", "cancelled", "cancelled"), - ], - { replayGate: gate }, - ); - const watch = yield* watchCalls(runtime, thread); - yield* runtime.startTurn(withLineage(thread)); - assert.isTrue(yield* Effect.promise(() => gate.waitForReached("cancelled"))); - yield* watch.until(() => watch.childTurns.get(`${CHILD}:turn:2`) === "interrupted"); - assert.deepEqual(watch.calls.get("Sleep"), { status: "running", result: null }); - gate.release("cancelled"); - yield* watch.until(() => watch.calls.get("Sleep")?.status !== "running"); - assert.deepEqual(watch.calls.get("Sleep"), { status: "cancelled", result: "Stopped" }); - }), - ); - it.effect("settles a call that joined a kept subagent with the subagent's last report", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ @@ -2544,11 +2512,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { listed: jobsBelow({ kind: "codemode", status: "running" }), result: "TESTS_PASSED", }, - { - name: "only finished jobs remain below it", - listed: jobsBelow({ kind: "codemode", status: "completed" }), - result: "TESTS_STARTED", - }, { name: "OpenCode lists only a stored subagent job below it", listed: jobsBelow({ kind: "subagent", status: "running" }), From d7ac62b412af84daafb4d1d92c505d33203f6a83 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 02:24:48 +0000 Subject: [PATCH 7/7] fix(opencode): settle kept subagents after reconnect's job reads and past idle levels - releaseQuiet walks up past an idle level with no kept call, so an ancestor a reconnect kept for a grandchild that ran again is released when it ends. - During reconnect, releaseQuiet defers to reconcile's settlement pass, so a backfilled quiet end cannot settle a call before OpenCode's job list shows a Code Mode script still running below it. - Job-list reads for kept calls run concurrently under one shared deadline instead of one 5s timeout each inside the 15s reconnect budget. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 93 ++++++++++++++++++- .../src/server/v2/adapter.ts | 52 +++++++---- 2 files changed, 126 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index f8301cd636ec3..7fc2d486d506a 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2503,6 +2503,73 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ]), ); + const grandMessage = { + type: "synthetic", + text: `\nGRAND_OK\n`, + description: "Grand", + metadata: { source: "subagent", childID: GRAND, agent: "General", state: "completed" }, + }; + // A report no call here waits for; it only opens the child's next busy period. + const grandReport = event("session.inbox.enqueued", { + inboxID: "msg_grand_report", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: grandMessage.text, + description: grandMessage.description, + metadata: grandMessage.metadata, + }, + delivery: "steer", + }, + }); + it.effect( + "releases a subagent a reconnect kept for a grandchild whose own call had settled", + () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...keptChain, + event("session.inbox.enqueued", { + inboxID: "msg_grand_final", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: `\nGRAND_DONE\n`, + description: "Grand", + metadata: { + source: "subagent", + childID: GRAND, + agent: "General", + state: "completed", + }, + }, + delivery: "steer", + }, + }), + event("session.execution.started", { sessionID: GRAND }), + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", { [GRAND]: { type: "running" } }), + out("permission.list", { sessionID: GRAND }), + replyData("permission.list", []), + out("session.form.list", { sessionID: GRAND }), + replyData("session.form.list", []), + event("session.execution.succeeded", { sessionID: GRAND }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => settled(watch.calls.get("Sleep")?.status) && watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.calls), { + Sleep: { status: "completed", result: "CHILD_WAITING" }, + Grand: { status: "completed", result: "GRAND_DONE" }, + }); + }), + ); + const jobsBelow = (...jobs: ReadonlyArray<{ kind: string; status: string }>) => ({ data: jobs.map((job, index) => ({ ...job, id: `job_${index}`, sessionID: CHILD })), }); @@ -2512,6 +2579,12 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { listed: jobsBelow({ kind: "codemode", status: "running" }), result: "TESTS_PASSED", }, + { + name: "its quiet busy period ended unseen while a Code Mode script still runs", + listed: jobsBelow({ kind: "codemode", status: "running" }), + result: "TESTS_PASSED", + cut: true, + }, { name: "OpenCode lists only a stored subagent job below it", listed: jobsBelow({ kind: "subagent", status: "running" }), @@ -2524,11 +2597,12 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, ])( "after a reconnect, judges a kept subagent by OpenCode's jobs when $name", - ({ listed, result }) => + ({ listed, result, cut = false }) => Effect.gen(function* () { const { runtime, thread } = yield* resumed( [ ...reportedRunning, + ...(cut ? [grandReport, event("session.execution.started", { sessionID: CHILD })] : []), { type: "runtime_exit", status: "success" } as const, out("event.subscribe"), out("rpc.call", ""), @@ -2541,6 +2615,23 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("job.list", { data: [] }), out("session.active"), replyData("session.active", {}), + ...(cut + ? [ + out("message.list", { sessionID: CHILD, order: "desc", limit: "50" }), + reply("message.list", { + data: [ + { + id: "msg_idle_2", + time: { created: 4 }, + type: "idle", + outcome: "succeeded", + }, + { ...grandMessage, id: "msg_grand_report", time: { created: 3 } }, + ], + cursor: {}, + }), + ] + : []), out("job.list", { sessionID: CHILD, descendants: "true" }), reply("job.list", listed), // The reconnect has finished before this arrives; only a call it kept takes it. diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 2671351c0e740..8b7ea67595e0c 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -2250,7 +2250,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // OpenCode reports a busy period only when it wrote a new answer. A child whose work ended in a // quiet one never reports again, nor do the idle subagents above it that were waiting on it. + // During a reconnect, reconcile settles kept calls itself once it has read OpenCode's jobs. + let reconciling = false; const releaseQuiet = Effect.fnUntraced(function* (state: ThreadState) { + if (reconciling) return; for ( let current: ThreadState = state; current.subagent !== undefined; @@ -2258,9 +2261,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ) { if (current.active !== undefined || busy.has(current.sessionId) || hasBackground(current)) return; - const kept = callsAttachedTo(current).filter((call) => call.reported !== undefined); - if (kept.length === 0) return; - for (const call of kept) yield* settleCall(call, "completed", call.reported); + for (const call of callsAttachedTo(current)) { + if (call.reported !== undefined) yield* settleCall(call, "completed", call.reported); + } } }); @@ -3876,24 +3879,29 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } // OpenCode's running jobs below a kept call other than subagents (shells, Code Mode scripts, // images): it also lists stored subagent jobs it never closed, and subagents count by their - // sessions. A failed read counts as none. + // sessions. A read that fails or misses the shared deadline counts as none. const jobsBelow = new Map(); if ( compareSemverVersions(connection.version, "2.2.6") >= 0 && connection.runningJobs !== undefined ) { - for (const state of background) { - for (const call of runningCalls(state)) { - const child = call.child?.sessionId; - if (call.reported === undefined || child === undefined || jobsBelow.has(child)) - continue; - const jobs = yield* connection.runningJobs(child).pipe( - Effect.timeout(INVENTORY_TIMEOUT), - Effect.orElseSucceed(() => 0), - ); - jobsBelow.set(child, jobs); - } - } + const runningJobs = connection.runningJobs; + const children = new Set( + background.flatMap((state) => + runningCalls(state).flatMap((call) => + call.reported === undefined || call.child === undefined ? [] : [call.child.sessionId], + ), + ), + ); + yield* Effect.forEach( + children, + (child) => + runningJobs(child).pipe( + Effect.tap((jobs) => Effect.sync(() => jobsBelow.set(child, jobs))), + Effect.ignore, + ), + { concurrency: 4, discard: true }, + ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.ignore); } yield* lock.withPermit( Effect.gen(function* () { @@ -4006,9 +4014,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } // An owned process's exit, rather than a read deadline, bounds recovery; the bounded retry // below then borrows a restarted server. HTTP waits stay outside the event lock so Stop can still settle. + reconciling = true; + const recovery = reconcile().pipe( + Effect.ensuring( + Effect.sync(() => { + reconciling = false; + }), + ), + ); yield* next.processExit === undefined - ? reconcile().pipe(Effect.timeout(RECONCILE_TIMEOUT)) - : whileAlive(next.processExit, reconcile()); + ? recovery.pipe(Effect.timeout(RECONCILE_TIMEOUT)) + : whileAlive(next.processExit, recovery); return stream; }).pipe( // Borrows and process exits stay bounded; only a live owned process is waited on above.