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
10 changes: 7 additions & 3 deletions packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -751,13 +751,17 @@ export const RunCommand = effectCmd({
typeof part.state.output === "string" &&
part.state.output.includes(`state="running"`)
) {
background.launch({ sessionID: taskID!, parentSessionID: part.sessionID })
const run =
"metadata" in part.state && typeof part.state.metadata?.runId === "string"
? part.state.metadata.runId
: undefined
background.launch({ sessionID: taskID!, parentSessionID: part.sessionID, run })
}
}
if (part.type === "text") {
const match = part.text.match(/<task id="([^"]+)" state="(?:completed|error|cancelled)">/)
const match = part.text.match(/<task id="([^"]+)"(?: run="([^"]+)")? state="(?:completed|error|cancelled)">/)
if (match?.[1] && !/<termination reason="waiting_for_subagent">/.test(part.text)) {
background.resolve(match[1])
background.resolve(match[2] ?? match[1])
// A normal notification is about to wake the root. Do not
// exit in the gap between its user part and busy status.
if (part.sessionID === sessionID && part.synthetic && part.metadata?.backgroundNoReply !== true)
Expand Down
42 changes: 28 additions & 14 deletions packages/opencode/src/cli/cmd/run/background-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,51 @@
* Only edges reachable from this run's root count toward its pending work.
*/
export const make = (rootSessionID: string) => {
const launched = new Map<string, string>()
// Pending deliveries keyed by run (`sessionID@started_at`, #400): a resumed
// subagent (task_id) reuses its session ID, so keying by session alone lets
// one run's terminal envelope settle another run's row, and two launches of
// one session collapse into a single pending entry. Launches observed
// without a run id (older servers, attach mode) fall back to the session ID.
const launched = new Map<string, { sessionID: string; parentSessionID: string }>()
// Latest launch attribution per session, for the reachability walk.
const parents = new Map<string, string>()
const resolved = new Set<string>()

const known = (sessionID: string): boolean => {
const seen = new Set<string>()
while (sessionID !== rootSessionID) {
if (seen.has(sessionID)) return false
seen.add(sessionID)
const parent = launched.get(sessionID)
const parent = parents.get(sessionID)
if (!parent) return false
sessionID = parent
}
return true
}
const pending = () => [...launched.keys()].filter((id) => known(id) && !resolved.has(id))
const pending = () =>
[...launched.entries()]
.filter(([key, entry]) => known(entry.sessionID) && !resolved.has(key))
.map(([, entry]) => entry.sessionID)

return {
launch(input: { sessionID: string; parentSessionID: string }) {
launch(input: { sessionID: string; parentSessionID: string; run?: string }) {
if (input.sessionID === rootSessionID) return false
// A session already launched and still pending is the same run. One that
// already resolved was resumed (task_id): a new run, so it is pending again.
if (launched.has(input.sessionID)) {
if (!resolved.has(input.sessionID)) return false
resolved.delete(input.sessionID)
parents.set(input.sessionID, input.parentSessionID)
const key = input.run ?? input.sessionID
// A launch re-emitted for a run still pending is the same run. One whose
// delivery already arrived was resumed (task_id): a new run, so it is
// pending again.
if (launched.has(key)) {
if (!resolved.has(key)) return false
resolved.delete(key)
}
launched.set(input.sessionID, input.parentSessionID)
return known(input.sessionID) && !resolved.has(input.sessionID)
launched.set(key, { sessionID: input.sessionID, parentSessionID: input.parentSessionID })
return known(input.sessionID) && !resolved.has(key)
},
// A fast delivery may arrive before its launch part.
resolve(sessionID: string) {
resolved.add(sessionID)
// A fast delivery may arrive before its launch part. The key is the run id
// when the envelope carries one, the session ID otherwise.
resolve(run: string) {
resolved.add(run)
},
pending,
settled: () => pending().length === 0,
Expand Down
24 changes: 20 additions & 4 deletions packages/opencode/src/tool/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,13 @@ function renderOutput(input: {
summary?: string
text: string
termination?: TerminationReason
// The run key (sessionID@started_at) of the job this envelope reports, so a
// resumed session's deliveries settle their own run and no other (#400).
run?: string
}) {
const tag = input.state === "error" ? "task_error" : "task_result"
return [
`<task id="${input.sessionID}" state="${input.state}">`,
`<task id="${input.sessionID}"${input.run ? ` run="${input.run}"` : ""} state="${input.state}">`,
...(input.summary ? [`<summary>${input.summary}</summary>`] : []),
`<${tag}>`,
input.text,
Expand Down Expand Up @@ -606,6 +609,7 @@ export const TaskTool = Tool.define(
text: renderOutput({
sessionID: nextSession.id,
state,
run: receiptKey,
summary:
state === "completed"
? `Background task completed: ${params.description}`
Expand Down Expand Up @@ -737,6 +741,7 @@ export const TaskTool = Tool.define(
text: renderOutput({
sessionID: descendant,
state,
run: runKey(job),
summary:
state === "completed"
? `Background task completed: ${job.title ?? "subagent"}`
Expand Down Expand Up @@ -835,12 +840,14 @@ export const TaskTool = Tool.define(
)

if (yield* background.extend({ id: nextSession.id, run: runWithEvidence() })) {
const extended = yield* background.get(nextSession.id)
return {
title: params.description,
metadata: {
...metadata,
background: true,
jobId: nextSession.id,
...(extended ? { runId: runKey(extended) } : {}),
},
output: renderOutput({
sessionID: nextSession.id,
Expand All @@ -859,9 +866,17 @@ export const TaskTool = Tool.define(
title: params.description,
metadata,
onPromote: Effect.all([
ctx.metadata({
title: params.description,
metadata: { ...metadata, background: true, jobId: nextSession.id },
Effect.gen(function* () {
const promoted = yield* background.get(nextSession.id)
yield* ctx.metadata({
title: params.description,
metadata: {
...metadata,
background: true,
jobId: nextSession.id,
...(promoted ? { runId: runKey(promoted) } : {}),
},
})
}),
notify(nextSession.id),
]),
Expand All @@ -875,6 +890,7 @@ export const TaskTool = Tool.define(
...metadata,
background: true,
jobId: info.id,
runId: runKey(info),
},
output: renderOutput({
sessionID: nextSession.id,
Expand Down
34 changes: 34 additions & 0 deletions packages/opencode/test/cli/run/background-tasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,40 @@ describe("headless background task tracking", () => {
expect(tasks.settled()).toBe(true)
})

test("two runs of one session are both pending until each reports", () => {
const tasks = BackgroundTasks.make(root)
expect(tasks.launch({ ...launch(root, child), run: `${child}@1` })).toBe(true)
expect(tasks.launch({ ...launch(root, child), run: `${child}@2` })).toBe(true)
// Keyed by session alone, the second launch deduped into the first and the
// run exited while a child still ran (#400).
expect(tasks.pending()).toEqual([child, child])
tasks.resolve(`${child}@1`)
expect(tasks.settled()).toBe(false)
tasks.resolve(`${child}@2`)
expect(tasks.settled()).toBe(true)
})

test("a terminal envelope for an earlier run does not settle a resumed run", () => {
const tasks = BackgroundTasks.make(root)
tasks.launch({ ...launch(root, child), run: `${child}@1` })
tasks.resolve(`${child}@1`)
// task_id resume: same session, new run, tracked on its own key.
expect(tasks.launch({ ...launch(root, child), run: `${child}@2` })).toBe(true)
expect(tasks.settled()).toBe(false)
// A late duplicate of the first run's envelope must not settle the second.
tasks.resolve(`${child}@1`)
expect(tasks.settled()).toBe(false)
tasks.resolve(`${child}@2`)
expect(tasks.settled()).toBe(true)
})

test("a re-emitted launch part for the same run still dedupes", () => {
const tasks = BackgroundTasks.make(root)
expect(tasks.launch({ ...launch(root, child), run: `${child}@1` })).toBe(true)
expect(tasks.launch({ ...launch(root, child), run: `${child}@1` })).toBe(false)
expect(tasks.pending()).toEqual([child])
})

test("a session that reported before its task part arrived stays settled", () => {
const tasks = BackgroundTasks.make(root)
tasks.resolve(child)
Expand Down
10 changes: 5 additions & 5 deletions packages/opencode/test/tool/task.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1956,7 +1956,7 @@ describe("tool.task", () => {
const notification = yield* Effect.promise(() => injected.promise)
const text = notification.parts[0]?.type === "text" ? notification.parts[0].text : ""
expect(notification.sessionID).toBe(chat.id)
expect(text).toContain(`<task id="${child}" state="cancelled">`)
expect(text).toMatch(new RegExp(`<task id="${child}" run="${child}@\\d+" state="cancelled">`))
expect(text).toContain("<summary>Background task cancelled: inspect bug</summary>")
expect(text).toContain('<termination reason="cancelled">')
expect(text).toContain("cancelled by the user")
Expand Down Expand Up @@ -3229,7 +3229,7 @@ it.instance("a child that yields for its own subagents keeps its job running and
const delivery = parentPrompts[0]
const delivered = delivery?.parts[0]?.type === "text" ? delivery.parts[0].text : ""
expect(delivery?.sessionID).toBe(chat.id)
expect(delivered).toContain(`<task id="${child}" state="completed">`)
expect(delivered).toMatch(new RegExp(`<task id="${child}" run="${child}@\\d+" state="completed">`))
expect(delivered).toContain("child final result")
expect(delivered).toContain('<termination reason="success">')

Expand All @@ -3238,7 +3238,7 @@ it.instance("a child that yields for its own subagents keeps its job running and
const resume = childPrompts[1]
const resumed = resume?.parts[0]?.type === "text" ? resume.parts[0].text : ""
expect(childPrompts).toHaveLength(2)
expect(resumed).toContain(`<task id="${grandchild}" state="completed">`)
expect(resumed).toMatch(new RegExp(`<task id="${grandchild}" run="${grandchild}@\\d+" state="completed">`))
expect(resumed).toContain("grandchild result")
expect(resumed).toContain("Background task completed: grandchild work")

Expand Down Expand Up @@ -3437,7 +3437,7 @@ it.instance(
"the child's final result was not delivered to the parent",
)
const delivered = parentPrompts[0]?.parts[0]?.type === "text" ? parentPrompts[0].parts[0].text : ""
expect(delivered).toContain(`<task id="${child}" state="completed">`)
expect(delivered).toMatch(new RegExp(`<task id="${child}" run="${child}@\\d+" state="completed">`))
expect(delivered).toContain("child final result")

// The child was resumed by the parked job with the settled report, and
Expand Down Expand Up @@ -3665,7 +3665,7 @@ for (const teardown of [false, true]) {
"the child's final result was not delivered to the parent",
)
const delivered = parentPrompts[0]?.parts[0]?.type === "text" ? parentPrompts[0].parts[0].text : ""
expect(delivered).toContain(`<task id="${child}" state="completed">`)
expect(delivered).toMatch(new RegExp(`<task id="${child}" run="${child}@\\d+" state="completed">`))
expect(delivered).toContain("AFTER_PARK")

// The settled report was delivered by the park, with no second prompt from
Expand Down
Loading