mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-17 05:26:47 +03:00
fix(core): retain pending notices and failed subagent outcomes
This commit is contained in:
@@ -6,6 +6,7 @@ import type { Database } from "../database/database.js"
|
||||
import type { Job } from "../job.js"
|
||||
import { SessionInbox } from "./inbox.js"
|
||||
import type { SessionSchema } from "./schema.js"
|
||||
import type { SessionStore } from "./store.js"
|
||||
|
||||
export type Lookup = {
|
||||
readonly get: (sessionID: SessionSchema.ID) => Effect.Effect<{ readonly parentID?: SessionSchema.ID } | undefined>
|
||||
@@ -58,12 +59,20 @@ export const outstanding = Effect.fnUntraced(function* (
|
||||
* 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,
|
||||
jobs: Pick<Job.Interface, "runningBackground" | "pendingBackground">,
|
||||
store: Lookup & Pick<SessionStore.Interface, "message">,
|
||||
db: Database.Interface["db"],
|
||||
sessionID: SessionSchema.ID,
|
||||
) {
|
||||
if ((yield* outstanding(jobs, store, sessionID)).length > 0) return true
|
||||
// A job can finish before its observer admits the completion input. Keep that gap pending,
|
||||
// but ignore markers whose input was already delivered (observer cleanup may lag behind it).
|
||||
const parents = new Map<SessionSchema.ID, SessionSchema.ID | null>()
|
||||
for (const job of yield* jobs.pendingBackground) {
|
||||
const owner = job.recovery.kind === "subagent" ? job.recovery.parentSessionID : job.recovery.sessionID
|
||||
if (!(yield* descends(store, parents, owner, sessionID))) continue
|
||||
if (!(yield* store.message(job.notificationID))) return true
|
||||
}
|
||||
return yield* SessionInbox.has(db, sessionID, "input")
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * as SubagentJob from "./subagent-job.js"
|
||||
|
||||
import { Context, Effect, Fiber, Layer, Scope, Stream } from "effect"
|
||||
import { Context, Effect, Layer, Option, Queue, 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"
|
||||
@@ -60,22 +60,42 @@ const make: Effect.Effect<
|
||||
|
||||
// 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)
|
||||
const settle = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) {
|
||||
const outcomes = [
|
||||
SessionEvent.Execution.Succeeded,
|
||||
SessionEvent.Execution.Failed,
|
||||
SessionEvent.Execution.Interrupted,
|
||||
] as const
|
||||
const settled = yield* Queue.make<Bus.SubscribePayload<typeof outcomes>>()
|
||||
// Keep one subscription across all busy periods, including the initial resume. wait() ignores
|
||||
// failures, so retain terminal outcomes rather than mistaking a failed follow-up for success.
|
||||
yield* bus.subscribe(outcomes).pipe(
|
||||
Stream.filter((event) => event.data.sessionID === sessionID),
|
||||
Stream.runForEach((event) => Queue.offer(settled, event)),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
const terminal = Effect.fnUntraced(function* (event: Bus.SubscribePayload<typeof outcomes>) {
|
||||
if (event.type === SessionEvent.Execution.Failed.type)
|
||||
return yield* Effect.fail(new Error(event.data.error.message))
|
||||
if (event.type !== SessionEvent.Execution.Interrupted.type) return
|
||||
// Shutdown leaves the job's recovery marker to restart; it must not notify the parent.
|
||||
if (event.data.reason === "shutdown") return yield* Effect.never
|
||||
return yield* Effect.interrupt
|
||||
})
|
||||
yield* sessions.resume(sessionID)
|
||||
while (true) {
|
||||
yield* sessions.wait(sessionID)
|
||||
// Read active last: input may have been promoted while the pending-work queries ran.
|
||||
const pending = yield* SessionBackground.unsettled(jobs, store, db, sessionID)
|
||||
const active = (yield* sessions.active).has(sessionID)
|
||||
const event = yield* Queue.poll(settled)
|
||||
if (Option.isSome(event)) {
|
||||
yield* terminal(event.value)
|
||||
continue
|
||||
}
|
||||
if (!pending && !active) return
|
||||
yield* terminal(yield* Queue.take(settled))
|
||||
}
|
||||
}, Effect.scoped)
|
||||
|
||||
const notify = Effect.fn("SubagentJob.notify")(function* (recovery: Recovery, startedAt: number) {
|
||||
@@ -115,7 +135,6 @@ const make: Effect.Effect<
|
||||
metadata: {},
|
||||
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,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Deferred, Effect, Layer } from "effect"
|
||||
import { Deferred, Effect, Layer, Stream } from "effect"
|
||||
import { LanguageModel } from "@opencode/ai/effect"
|
||||
import { OpenAIChat } from "@opencode/ai/protocols"
|
||||
import { TestLLM } from "@opencode/ai/testing"
|
||||
@@ -143,9 +143,8 @@ describe("subagent observer lifetime", () => {
|
||||
)
|
||||
}
|
||||
|
||||
it.live(
|
||||
"child that starts a background shell and goes idle reports only after the shell exits",
|
||||
() =>
|
||||
for (const phase of ["running", "notice", "descendant", "failure"] as const) {
|
||||
it.live(`child waits for background work and its completion input (${phase})`, () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = yield* tmpdirScoped()
|
||||
yield* Effect.promise(() =>
|
||||
@@ -171,17 +170,26 @@ describe("subagent observer lifetime", () => {
|
||||
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 owner =
|
||||
phase === "descendant"
|
||||
? yield* sessions.create({ parentID: child.id, agent: Agent.ID.make("reviewer") })
|
||||
: child
|
||||
// Background shell work can belong to the child or a deeper descendant.
|
||||
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" },
|
||||
recovery: { kind: "shell", sessionID: owner.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"))
|
||||
yield* llm.push(
|
||||
TestLLM.text("first", "first"),
|
||||
...(phase === "descendant" ? [TestLLM.text("descendant done", "descendant")] : []),
|
||||
phase === "failure" ? Stream.die(new Error("follow-up failed")) : TestLLM.text("final", "final"),
|
||||
)
|
||||
const gate = yield* llm.gate()
|
||||
|
||||
const result = yield* executeTool(registry, {
|
||||
sessionID: parent.id,
|
||||
@@ -200,11 +208,33 @@ describe("subagent observer lifetime", () => {
|
||||
},
|
||||
})
|
||||
expect(result.status).toBe("completed")
|
||||
yield* llm.wait(1).pipe(Effect.timeout("2 seconds"))
|
||||
yield* gate.started
|
||||
// Finish the shell before the child goes idle, but hold its completion input. The
|
||||
// durable marker must bridge this gap even though runningBackground is now empty.
|
||||
if (phase === "notice") {
|
||||
yield* Deferred.succeed(exit, undefined)
|
||||
yield* jobs.wait({ id: "shell-dev" })
|
||||
}
|
||||
yield* gate.release
|
||||
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")
|
||||
|
||||
if (phase === "failure") {
|
||||
// A failed follow-up must release the job waiter even while the shell is still running.
|
||||
yield* sessions.synthetic({ sessionID: child.id, text: "Check the work again" })
|
||||
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: "error" } })
|
||||
expect(notices[0]?.text).toContain("follow-up failed")
|
||||
expect((yield* jobs.get(child.id))?.status).not.toBe("running")
|
||||
expect((yield* jobs.get("shell-dev"))?.status).toBe("running")
|
||||
return
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -212,21 +242,22 @@ describe("subagent observer lifetime", () => {
|
||||
expect(shell?.notificationID).toBeDefined()
|
||||
yield* sessions.synthetic({
|
||||
...(shell?.notificationID ? { id: shell.notificationID } : {}),
|
||||
sessionID: child.id,
|
||||
sessionID: owner.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* llm.wait(phase === "descendant" ? 4 : 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* llm.requests()).toHaveLength(phase === "descendant" ? 4 : 3)
|
||||
expect(yield* jobs.pendingBackground).toEqual([])
|
||||
}),
|
||||
20_000,
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user