Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 26 additions & 16 deletions packages/core/src/job/recovery.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
import { Schema } from "effect"
import { SessionSchema } from "../session/schema.js"

const Shell = Schema.Struct({
kind: Schema.Literal("shell"),
sessionID: SessionSchema.ID,
shellID: Schema.String,
command: Schema.String,
})
const Image = Schema.Struct({
kind: Schema.Literal("image"),
sessionID: SessionSchema.ID,
path: Schema.String,
model: Schema.String,
})
const subagent = {
kind: Schema.Literal("subagent"),
childSessionID: SessionSchema.ID,
agent: Schema.String,
description: Schema.String,
}

const OutstandingItem = Schema.Union([Shell, Image, Schema.Struct({ ...subagent, sessionID: SessionSchema.ID })])
export type OutstandingItem = typeof OutstandingItem.Type

export const RecoverySchema = Schema.Union([
Shell,
Image,
Schema.Struct({
kind: Schema.Literal("shell"),
sessionID: SessionSchema.ID,
shellID: Schema.String,
command: Schema.String,
}),
Schema.Struct({
kind: Schema.Literal("subagent"),
...subagent,
parentSessionID: SessionSchema.ID,
childSessionID: SessionSchema.ID,
agent: Schema.String,
description: Schema.String,
}),
Schema.Struct({
kind: Schema.Literal("image"),
sessionID: SessionSchema.ID,
path: Schema.String,
model: Schema.String,
outstanding: Schema.optionalKey(Schema.Array(OutstandingItem)),
}),
])

Expand Down
22 changes: 2 additions & 20 deletions packages/core/src/session/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export * as SessionBackground from "./background.js"
import type { Kind, Status } from "@opencode/schema/job"
import { Effect } from "effect"
import type { Job } from "../job.js"
import type { OutstandingItem } from "../job/recovery.js"
import type { SessionSchema } from "./schema.js"

export type Lookup = {
Expand All @@ -13,26 +14,7 @@ export type Lookup = {
>
}

export type OutstandingItem =
| {
readonly kind: "shell"
readonly sessionID: SessionSchema.ID
readonly shellID: string
readonly command: string
}
| {
readonly kind: "image"
readonly sessionID: SessionSchema.ID
readonly model: string
readonly path: string
}
| {
readonly kind: "subagent"
readonly sessionID: SessionSchema.ID
readonly childSessionID: SessionSchema.ID
readonly agent: string
readonly description: string
}
export type { OutstandingItem }

export type ListFilter = {
readonly sessionID?: SessionSchema.ID
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/session/execution/restart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ export const layer = (options?: Options) =>
}).pipe(
// A deleted parent owes nothing to the report; clear its row.
Effect.catchTag("Session.NotFoundError", () => jobs.completeBackground(notificationID)),
// Retain the formatted outbox row for the next boot: the notification ID is
// Retain the outbox row for the next boot: the notification ID is
// already owned by another item, so deleting it would lose the report.
Effect.catchTag("Session.SyntheticConflictError", (error) =>
Effect.logWarning("Failed to admit recovered subagent notification due to ID conflict", {
Expand Down Expand Up @@ -339,7 +339,7 @@ export const layer = (options?: Options) =>
}

if (background.status !== "running") {
// The outbox row already holds the formatted result; replay it without touching the child.
// Replay the settled report using the work captured with it.
yield* deliverSubagentSafe(notices, background.notificationID, recovery, background)
return false
}
Expand Down Expand Up @@ -377,7 +377,7 @@ export const layer = (options?: Options) =>
)
yield* store.releaseOrphanedChildClaims()
// Job.cancel persists the cancellation before interrupting the execution. A crash
// in between leaves its claim behind. Settlement writes a formatted error to the
// in between leaves its claim behind. Settlement writes an error to the
// outbox atomically with release; such an older report can coexist with a new claim.
for (const { status, recovery, error } of pending) {
if (status !== "cancelled" || recovery.kind !== "subagent" || error !== undefined) continue
Expand Down
7 changes: 3 additions & 4 deletions packages/core/src/session/execution/subagent-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export const make = (deps: Deps) => {
report,
).pipe(
Effect.as(true),
// Retain the formatted outbox row: the conflict proves the notification ID is already
// Retain the outbox row: the conflict proves the notification ID is already
// owned elsewhere, so deleting it would lose the report without admitting anything.
Effect.catchTag("SessionInbox.LifecycleConflict", (conflict) =>
Effect.logWarning("Subagent report notification ID conflicted in parent inbox", {
Expand Down Expand Up @@ -164,7 +164,6 @@ export const make = (deps: Deps) => {
}
const resolved = yield* resolveBody(sessionID, outcome, period?.startedSeq, jobState.mode)
if (!resolved) return
const formatted = SubagentCompletion.formatBody(resolved.body, child.id, running)
const recovery =
jobState.mode === "background"
? jobState.recovery
Expand All @@ -177,9 +176,9 @@ export const make = (deps: Deps) => {
}
const report: Job.SubagentOutboxReport = {
notificationID: jobState.mode === "background" ? jobState.notificationID : SessionMessage.ID.create(),
recovery,
recovery: { ...recovery, outstanding: running },
status: resolved.status,
...(resolved.status === "completed" ? { output: formatted } : { error: formatted }),
...(resolved.status === "completed" ? { output: resolved.body } : { error: resolved.body }),
...(jobState.mode === "background" ? { startedAt: jobState.startedAt } : {}),
}
yield* deps.jobs.recordSubagentReport(report)
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/session/subagent-completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ export const deliver = Effect.fnUntraced(function* <E>(
: input.status === "error"
? (input.error ?? "Subagent failed")
: (input.output ?? input.error ?? "Subagent cancelled")
// The body is all a recovered outbox row keeps, so the still-running list is how a replay tells this period apart.
// Only the model-facing tag says "running": the job and the message metadata keep the period's real status.
const state = input.status === "completed" && body.includes(STILL_RUNNING) ? "running" : input.status
// Older rows lack the snapshot. Replay their recorded job status and preserve the full report body.
const state = input.status === "completed" && recovery.outstanding?.length ? "running" : input.status
const formatted = formatBody(body, recovery.childSessionID, recovery.outstanding)
yield* sessions.synthetic({
...(input.notificationID ? { id: input.notificationID } : {}),
sessionID: recovery.parentSessionID,
description: recovery.description,
text: `<subagent sessionID="${recovery.childSessionID}" state="${state}" description="${recovery.description}">\n${body}\n</subagent>`,
text: `<subagent sessionID="${recovery.childSessionID}" state="${state}" description="${recovery.description}">\n${formatted}\n</subagent>`,
metadata: { source: "subagent", childID: recovery.childSessionID, agent: recovery.agent, state: input.status },
})
if (input.notificationID) yield* jobs.completeBackground(input.notificationID)
Expand Down
31 changes: 15 additions & 16 deletions packages/core/test/session-execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import { Agent } from "@opencode/core/agent"
import { ID } from "@opencode/core/model"
import { Provider } from "@opencode/core/provider"
import { daemonShells } from "./fixture/shell-daemon"
import { SubagentCompletion } from "@opencode/core/session/subagent-completion"
import { Cause, Context, Deferred, Effect, Exit, Fiber, Layer, LayerMap, Logger, Scope } from "effect"
import { eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
Expand Down Expand Up @@ -1422,7 +1421,8 @@ describe("SessionRestart background recovery", () => {
run: Deferred.await(complete),
})
yield* jobs.background(child)
yield* Deferred.succeed(complete, "Recovered result")
const output = "Example from the docs:\n\nBackground work still running:\n- shell (sh_1): bun test"
yield* Deferred.succeed(complete, output)
yield* jobs.wait({ id: child })

const parentWoken = yield* Deferred.make<void>()
Expand All @@ -1444,7 +1444,12 @@ describe("SessionRestart background recovery", () => {

expect(drained).toEqual([parent])
expect(yield* SessionInbox.list(database.db, parent)).toMatchObject([
{ payload: { text: expect.stringContaining("Recovered result"), metadata: { state: "completed" } } },
{
payload: {
text: `<subagent sessionID="${child}" state="completed" description="Completed inspection">\n${output}\n</subagent>`,
metadata: { state: "completed" },
},
},
])
expect(yield* restarted.pendingBackground).toEqual([])
}),
Expand All @@ -1458,25 +1463,19 @@ describe("SessionRestart background recovery", () => {
const child = Session.ID.make("ses_outbox_child")
yield* seedSessions(database, [parent])
yield* seedSessions(database, [child], { parent_id: parent })
const output = SubagentCompletion.formatBody("Started tests", child, [
{ kind: "shell", sessionID: child, shellID: "sh_1", command: "bun test" },
])
const complete = yield* Deferred.make<string>()
yield* jobs.start({
id: child,
type: "subagent",
yield* jobs.recordSubagentReport({
notificationID: SessionMessage.ID.create(),
status: "completed",
output: "Started tests",
recovery: {
kind: "subagent",
parentSessionID: parent,
childSessionID: child,
agent: "explore",
description: "Outbox inspection",
outstanding: [{ kind: "shell", sessionID: child, shellID: "sh_1", command: "bun test" }],
},
run: Deferred.await(complete),
})
yield* jobs.background(child)
yield* Deferred.succeed(complete, output)
yield* jobs.wait({ id: child })

const drained: Session.ID[] = []
const parentWoken = yield* Deferred.make<void>()
Expand All @@ -1495,13 +1494,13 @@ describe("SessionRestart background recovery", () => {
yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
yield* Deferred.await(parentWoken)

// Replay delivers the formatted row verbatim, its still-running list labelling the tag; the child never runs again.
// Replay uses the snapshot even though the shell is no longer running.
expect(drained).toEqual([parent])
expect(yield* SessionInbox.list(database.db, parent)).toMatchObject([
{
type: "synthetic",
payload: {
text: `<subagent sessionID="${child}" state="running" description="Outbox inspection">\n${output}\n</subagent>`,
text: `<subagent sessionID="${child}" state="running" description="Outbox inspection">\nStarted tests\n\nBackground work still running:\n- shell (sh_1): bun test\n</subagent>`,
metadata: { source: "subagent", childID: child, agent: "explore", state: "completed" },
},
},
Expand Down
7 changes: 5 additions & 2 deletions packages/core/test/subagent-completion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,12 @@ describe("SubagentCompletion", () => {

yield* SubagentCompletion.deliver(sessions, jobs, {
status: "completed",
output: "All green\n\nBackground work still running:\n- shell (shell_1): bun test",
output: "All green",
notificationID,
recovery,
recovery: {
...recovery,
outstanding: [{ kind: "shell", sessionID: recovery.childSessionID, shellID: "shell_1", command: "bun test" }],
},
})
yield* SubagentCompletion.deliver(sessions, jobs, { status: "error", error: "boom", recovery })
yield* SubagentCompletion.deliver(sessions, jobs, { status: "cancelled", recovery })
Expand Down
23 changes: 18 additions & 5 deletions packages/core/test/subagent-idle-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,8 @@ describe("subagent idle reports end to end", () => {
yield* waitForReports(h, h.parent.id, 1)
const first = yield* deliveredReports(h, h.parent.id)
expect(first).toHaveLength(1)
expect(first[0]?.text).toContain(`sessionID="${outputSessionID(launched.metadata)}" state="running"`)
expect(first[0]?.metadata?.state).toBe("completed")
expect(first[0]!.text).toContain("Started tests")
expect(first[0]!.text).toContain("Background work still running:\n- shell (")
expect(first[0]!.text).toContain(command)
Expand All @@ -342,6 +344,8 @@ describe("subagent idle reports end to end", () => {
const second = yield* deliveredReports(h, h.parent.id)
expect(second).toHaveLength(2)
expect(second[1]!.id).not.toBe(first[0]!.id)
expect(second[1]?.text).toContain(`sessionID="${outputSessionID(launched.metadata)}" state="completed"`)
expect(second[1]?.metadata?.state).toBe("completed")
expect(second[1]!.text).toContain("Tests green")
expect(second[1]!.text).not.toContain("Started tests")
expect(second[1]!.text).not.toContain("Background work still running:")
Expand All @@ -355,10 +359,11 @@ describe("subagent idle reports end to end", () => {
() =>
Effect.gen(function* () {
const h = yield* harness()
const quote = "The report used this heading:\n\nBackground work still running:\n- shell (sh_1): bun test"
yield* h.llm.serve(
script({
reviewer: [
TestLLM.text("first answer", "turn-1"),
TestLLM.text(quote, "turn-1"),
TestLLM.text("second answer", "turn-2"),
TestLLM.text("third answer", "turn-3"),
],
Expand All @@ -368,15 +373,23 @@ describe("subagent idle reports end to end", () => {
const launched = yield* h.call("call-launch")
const childID = outputSessionID(launched.metadata)
yield* waitForReports(h, h.parent.id, 1)
expect((yield* deliveredReports(h, h.parent.id))[0]!.text).toContain("first answer")
const text = `<subagent sessionID="${childID}" state="completed" description="review">\n${quote}\n</subagent>`
expect((yield* deliveredReports(h, h.parent.id))[0]).toMatchObject({
text,
metadata: { source: "subagent", childID, agent: "reviewer", state: "completed" },
})
const parent = (yield* h.llm.requests()).find((request) => request.model.id === "build")
expect(parent?.messages).toContainEqual(
expect.objectContaining({ content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]) }),
)
yield* h.sessions.wait(childID)
yield* h.jobs.wait({ id: childID })

yield* h.sessions.prompt({ sessionID: childID, text: "Follow up" })
yield* waitForReports(h, h.parent.id, 2)
const second = (yield* deliveredReports(h, h.parent.id))[1]!
expect(second.text).toContain("second answer")
expect(second.text).not.toContain("first answer")
expect(second.text).not.toContain(quote)

yield* h.sessions.prompt({ sessionID: childID, text: "Follow up again" })
yield* waitForReports(h, h.parent.id, 3)
Expand Down Expand Up @@ -526,11 +539,11 @@ describe("subagent idle reports end to end", () => {
yield* h.sessions.wait(childID)
yield* h.jobs.wait({ id: childID })

// The terminal transaction released the claim and persisted the formatted report,
// The terminal transaction released the claim and persisted the report,
// but delivery never happened.
expect((yield* h.sessions.context(h.parent.id)).filter((message) => message.type === "synthetic")).toEqual([])
expect(yield* h.jobs.pendingBackground).toMatchObject([
{ id: childID, status: "completed", output: "crash-safe answer" },
{ id: childID, status: "completed", output: "crash-safe answer", recovery: { outstanding: [] } },
])
expect(yield* claims(h)).toEqual({ [h.parent.id]: false, [childID]: false })
const requests = yield* h.llm.requests()
Expand Down
9 changes: 8 additions & 1 deletion packages/core/test/subagent-report.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,8 +467,10 @@ describe("SubagentReport outbox", () => {
const inbox = yield* SessionInbox.Service
const parent = sessionID("ses_outbox_parent")
const child = sessionID("ses_outbox_child")
const grandchild = sessionID("ses_outbox_grandchild")
yield* seedSessions(database, [parent])
yield* seedSessions(database, [child], { parent_id: parent, agent: "explore", title: "Outbox audit" })
yield* seedSessions(database, [grandchild], { parent_id: child, agent: "explore", title: "Check logs" })
yield* seedAssistant(database, child, 100, "Outbox report")
yield* store.claim(child)

Expand All @@ -477,7 +479,7 @@ describe("SubagentReport outbox", () => {
store,
jobs,
inbox,
draining: Effect.succeed(new Set()),
draining: Effect.succeed(new Set([grandchild])),
wake: (sessionID) => Effect.sync(() => void wakes.push(sessionID)),
})
const job = yield* jobs.start({
Expand Down Expand Up @@ -509,6 +511,11 @@ describe("SubagentReport outbox", () => {
session_id: parent,
status: "completed",
output: "Outbox report",
recovery: {
outstanding: [
{ kind: "subagent", sessionID: child, childSessionID: grandchild, agent: "explore", description: "Check logs" },
],
},
},
])

Expand Down
Loading