From bd18108c9b2f526258d9d3d719710e89e1f388e1 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Wed, 4 Nov 2026 15:56:19 -0800 Subject: [PATCH] fix(core): hold a subagent's report until its background work finishes --- packages/core/src/session/background.ts | 17 ++++ packages/core/src/session/execution.ts | 2 + .../src/session/execution/subagent-report.ts | 5 ++ packages/core/src/session/subagent-job.ts | 40 ++++++++- packages/core/test/subagent-lifetime.test.ts | 89 ++++++++++++++++++- packages/core/test/tool-subagent.test.ts | 11 +-- 6 files changed, 155 insertions(+), 9 deletions(-) diff --git a/packages/core/src/session/background.ts b/packages/core/src/session/background.ts index 65691910f75..859a841e1f5 100644 --- a/packages/core/src/session/background.ts +++ b/packages/core/src/session/background.ts @@ -2,7 +2,9 @@ export * as SessionBackground from "./background.js" import type { Kind, Status } from "@opencode/schema/job" import { Effect } from "effect" +import type { Database } from "../database/database.js" import type { Job } from "../job.js" +import { SessionInbox } from "./inbox.js" import type { SessionSchema } from "./schema.js" export type Lookup = { @@ -50,6 +52,21 @@ export const outstanding = Effect.fnUntraced(function* ( }) }) +/** + * Whether an idle Session will be woken again by its own work: a background job of its own or a + * descendant's still running, or admitted input not yet delivered, such as a finished shell's + * notice. A subagent's report waits for this so it carries the child's final state. + */ +export const unsettled = Effect.fnUntraced(function* ( + jobs: Pick, + store: Lookup, + db: Database.Interface["db"], + sessionID: SessionSchema.ID, +) { + if ((yield* outstanding(jobs, store, sessionID)).length > 0) return true + return yield* SessionInbox.has(db, sessionID, "input") +}) + /** Active and unconsumed background jobs matching the requested Session, kind, status, and descendant scope. */ export const list = Effect.fn("SessionBackground.list")(function* ( jobs: Pick, diff --git a/packages/core/src/session/execution.ts b/packages/core/src/session/execution.ts index afd1acc3c46..2788d9ea0d4 100644 --- a/packages/core/src/session/execution.ts +++ b/packages/core/src/session/execution.ts @@ -6,6 +6,7 @@ import { Database } from "../database/database.js" import { Job } from "../job.js" import { Instance } from "../instance/service.js" import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { SessionBackground } from "./background.js" import { SessionEvent } from "./event.js" import { SessionRunCoordinator } from "./run-coordinator.js" import { SessionRunner } from "./runner/index.js" @@ -114,6 +115,7 @@ export const layer = Layer.effect( inbox, // The coordinator is created below; a report only runs after a busy period has settled. wake: (sessionID) => coordinator.wake(sessionID), + pending: (sessionID) => SessionBackground.unsettled(jobs, store, db, sessionID), }) const coordinator = yield* SessionRunCoordinator.make({ started: (sessionID) => diff --git a/packages/core/src/session/execution/subagent-report.ts b/packages/core/src/session/execution/subagent-report.ts index 20e8d5297ff..eb6893ecc43 100644 --- a/packages/core/src/session/execution/subagent-report.ts +++ b/packages/core/src/session/execution/subagent-report.ts @@ -33,6 +33,8 @@ export type Deps = { readonly jobs: Job.Interface readonly inbox: SessionInbox.Interface readonly wake: (sessionID: SessionSchema.ID) => Effect.Effect + /** True while the child still has background work or undelivered input that will wake it again. */ + readonly pending: (sessionID: SessionSchema.ID) => Effect.Effect } /** @@ -87,6 +89,9 @@ export const make = (deps: Deps) => { if (live && !live.notificationID) return // A job that finished or was cancelled mid-period already reported through its observer. if (!live && snap.remembered) return + // The child's own background work will wake it again, and that later settlement reports the + // final state. Failures and user interrupts report now. + if (outcome.type === "succeeded" && (yield* deps.pending(child.id))) return const recovery = subagentRecovery(live?.notificationID ? snap.recovery : undefined, child, parentID) const status = outcome.type === "succeeded" ? "completed" : outcome.type === "interrupted" ? "cancelled" : "error" diff --git a/packages/core/src/session/subagent-job.ts b/packages/core/src/session/subagent-job.ts index 780f7b7a7c1..6f08939141c 100644 --- a/packages/core/src/session/subagent-job.ts +++ b/packages/core/src/session/subagent-job.ts @@ -1,10 +1,16 @@ export * as SubagentJob from "./subagent-job.js" -import { Context, Effect, Layer, Scope } from "effect" +import { Context, Effect, Fiber, Layer, Scope, Stream } from "effect" import { Node } from "@opencode/util/effect/app-node" import type { LayerNode } from "@opencode/util/effect/layer-node" +import { Bus } from "../bus.js" +import { Database } from "../database/database.js" import { Job } from "../job.js" import { Session } from "../session.js" +import { SessionBackground } from "./background.js" +import { SessionEvent } from "./event.js" +import type { SessionSchema } from "./schema.js" +import { SessionStore } from "./store.js" import { SubagentCompletion } from "./subagent-completion.js" import { SubagentMetadata } from "./subagent-metadata.js" @@ -23,9 +29,16 @@ export interface Interface { export class Service extends Context.Service()("@opencode/SubagentJob") {} -const make: Effect.Effect = Effect.gen(function* () { +const make: Effect.Effect< + Interface, + never, + Session.Service | Job.Service | Bus.Service | SessionStore.Service | Database.Service | Scope.Scope +> = Effect.gen(function* () { const sessions = yield* Session.Service const jobs = yield* Job.Service + const bus = yield* Bus.Service + const store = yield* SessionStore.Service + const db = (yield* Database.Service).db const scope = yield* Scope.Scope // Jobs and their completion observers outlive the plugin that launched them. // Fork with the global context too, rather than retaining the caller's location. @@ -45,6 +58,26 @@ const make: Effect.Effect Effect.void)) }) + // Waits until the child stops for good: idle, with no background work or undelivered input left + // to wake it. It only waits and never resumes, since resuming an idle child runs a model step. + const settle = Effect.fnUntraced(function* ( + sessionID: SessionSchema.ID, + ): Effect.fn.Return { + // Listen before waiting and checking, so a settlement in between still ends the wait below. + const settled = yield* bus + .subscribe([SessionEvent.Execution.Succeeded, SessionEvent.Execution.Failed, SessionEvent.Execution.Interrupted]) + .pipe( + Stream.filter((event) => event.data.sessionID === sessionID), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ) + yield* sessions.wait(sessionID) + if (!(yield* sessions.active).has(sessionID) && !(yield* SessionBackground.unsettled(jobs, store, db, sessionID))) + return + yield* Fiber.join(settled) + return yield* settle(sessionID) + }, Effect.scoped) + const notify = Effect.fn("SubagentJob.notify")(function* (recovery: Recovery, startedAt: number) { const key = `${recovery.childSessionID}:${startedAt}` if (notifications.has(key)) return @@ -83,6 +116,7 @@ const make: Effect.Effect = Node.makeGlobalNode({ service: Service, layer: Layer.effect(Service, make), - deps: [Session.node, Job.node], + deps: [Session.node, Job.node, Bus.node, SessionStore.node, Database.node], }) diff --git a/packages/core/test/subagent-lifetime.test.ts b/packages/core/test/subagent-lifetime.test.ts index 0a5de6d13b1..697c60f901a 100644 --- a/packages/core/test/subagent-lifetime.test.ts +++ b/packages/core/test/subagent-lifetime.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test" -import { Effect, Layer } from "effect" +import { Deferred, Effect, Layer } from "effect" import { LanguageModel } from "@opencode/ai/effect" import { OpenAIChat } from "@opencode/ai/protocols" import { TestLLM } from "@opencode/ai/testing" @@ -142,4 +142,91 @@ describe("subagent observer lifetime", () => { 20_000, ) } + + it.live( + "child that starts a background shell and goes idle reports only after the shell exits", + () => + Effect.gen(function* () { + const dir = yield* tmpdirScoped() + yield* Effect.promise(() => + Bun.write( + `${dir.path}/opencode.json`, + JSON.stringify({ + agents: { reviewer: { mode: "subagent" } }, + permissions: [{ action: "*", resource: "*", effect: "allow" }], + }), + ), + ) + const sessions = yield* Session.Service + const locations = yield* LocationServiceMap.Service + const jobs = yield* Job.Service + const llm = yield* TestLLM.Test + const parent = yield* sessions.create({ + location: { directory: AbsolutePath.make(dir.path) }, + agent: Agent.ID.make("build"), + model: Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }), + }) + const child = yield* sessions.create({ parentID: parent.id, agent: Agent.ID.make("reviewer") }) + yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe( + Effect.provide(locations.get(parent.location)), + ) + const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) + // The child's background shell, which keeps running after the child's turn ends. + const exit = yield* Deferred.make() + yield* jobs.start({ + id: "shell-dev", + type: "shell", + title: "dev server", + recovery: { kind: "shell", sessionID: child.id, shellID: "shell-dev", command: "bun dev" }, + run: Deferred.await(exit).pipe(Effect.as("exited")), + }) + yield* jobs.background("shell-dev") + yield* llm.push(TestLLM.text("first", "first"), TestLLM.text("final", "final")) + + const result = yield* executeTool(registry, { + sessionID: parent.id, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-review", + name: "subagent", + input: { + agent: "reviewer", + sessionID: child.id, + description: "Review fixture", + prompt: "Review the fixture", + background: true, + }, + }, + }) + expect(result.status).toBe("completed") + yield* llm.wait(1).pipe(Effect.timeout("2 seconds")) + yield* sessions.wait(child.id) + expect((yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic")).toEqual([]) + expect((yield* jobs.get(child.id))?.status).toBe("running") + + // Mirrors the shell tool's notifyWhenDone: admit the exit notice to the child, which wakes + // it, then clear the durable marker. + yield* Deferred.succeed(exit, undefined) + const shell = (yield* jobs.wait({ id: "shell-dev" })).info + expect(shell?.notificationID).toBeDefined() + yield* sessions.synthetic({ + ...(shell?.notificationID ? { id: shell.notificationID } : {}), + sessionID: child.id, + text: "Background shell exited", + }) + if (shell?.notificationID) yield* jobs.completeBackground(shell.notificationID) + + yield* jobs.wait({ id: child.id }) + yield* llm.wait(3).pipe(Effect.timeout("2 seconds")) + yield* sessions.wait(parent.id) + const notices = (yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic") + expect(notices).toHaveLength(1) + expect(notices[0]).toMatchObject({ metadata: { source: "subagent", childID: child.id, state: "completed" } }) + expect(notices[0]?.text).toContain("final") + expect(notices[0]?.text).not.toContain("first") + expect(yield* jobs.pendingBackground).toEqual([]) + }), + 20_000, + ) }) diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 831e5ed365e..fcdb0c6ec2d 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -65,8 +65,11 @@ const executionNode = makeGlobalNode({ Effect.gen(function* () { const bus = yield* Bus.Service const store = yield* SessionStore.Service + const db = (yield* Database.Service).db const completed = new Set() const complete = Effect.fn("SubagentTest.complete")(function* (sessionID: Session.ID) { + // Deliver admitted input like a real drain, so the child does not look unsettled. + yield* SessionInbox.promote(db, bus, sessionID, "input") if (completed.has(sessionID)) return if ((yield* store.get(sessionID))?.title?.includes("fail")) { yield* new SessionRunnerModel.ModelNotSelectedError({ sessionID }) @@ -110,7 +113,7 @@ const executionNode = makeGlobalNode({ }) }), ), - deps: [Bus.node, SessionStore.node], + deps: [Bus.node, SessionStore.node, Database.node], }) const subagentPluginSupervisor = makeLocationNode({ @@ -488,7 +491,7 @@ describe("SubagentTool", () => { agent: "reviewer", model: childModel, }) - expect((yield* sessions.inbox(child.id)).find((message) => message.type === "user")?.payload.text).toBe( + expect((yield* sessions.context(child.id)).find((message) => message.type === "user")?.text).toBe( "You are a subagent spawned by another session.\nreview this", ) @@ -552,9 +555,7 @@ describe("SubagentTool", () => { expect((yield* sessions.list({ parentID: parent.id })).data).toHaveLength(1) expect((yield* sessions.get(childID)).title).toBe("review") expect( - (yield* sessions.inbox(childID)).flatMap((message) => - message.type === "user" ? [message.payload.text] : [], - ), + (yield* sessions.context(childID)).flatMap((message) => (message.type === "user" ? [message.text] : [])), ).toEqual(["You are a subagent spawned by another session.\nreview this", "continue this"]) expect(second.content).toEqual([{ type: "text", text: completedOutput(childID) }]) }),