fix(core): hold a subagent's report until its background work finishes

This commit is contained in:
Kit Langton
2026-11-04 15:56:19 -08:00
Unverified
parent 4fde589b4d
commit bd18108c9b
6 changed files with 155 additions and 9 deletions
+17
View File
@@ -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<Job.Interface, "runningBackground">,
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<Job.Interface, "backgroundJobs">,
+2
View File
@@ -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<SessionSchema.ID, SessionRunner.RunError, InterruptReason>({
started: (sessionID) =>
@@ -33,6 +33,8 @@ export type Deps = {
readonly jobs: Job.Interface
readonly inbox: SessionInbox.Interface
readonly wake: (sessionID: SessionSchema.ID) => Effect.Effect<void>
/** True while the child still has background work or undelivered input that will wake it again. */
readonly pending: (sessionID: SessionSchema.ID) => Effect.Effect<boolean>
}
/**
@@ -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"
+37 -3
View File
@@ -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<Service, Interface>()("@opencode/SubagentJob") {}
const make: Effect.Effect<Interface, never, Session.Service | Job.Service | Scope.Scope> = 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<Interface, never, Session.Service | Job.Service | Scop
}).pipe(Effect.catchTag("Session.NotFoundError", () => 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<void, Session.NotFoundError, Scope.Scope> {
// 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<Interface, never, Session.Service | Job.Service | Scop
recovery: input.recovery,
run: Effect.gen(function* () {
yield* sessions.resume(input.recovery.childSessionID)
yield* settle(input.recovery.childSessionID)
const messages = yield* sessions.messages({
sessionID: input.recovery.childSessionID,
order: "desc",
@@ -108,5 +142,5 @@ const make: Effect.Effect<Interface, never, Session.Service | Job.Service | Scop
export const node: LayerNode.Provider<Service, never, typeof Node.tags.values.global> = 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],
})
+88 -1
View File
@@ -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<void>()
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,
)
})
+6 -5
View File
@@ -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<Session.ID>()
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) }])
}),