From 66e2fb94b1481bae3884df36e590cb2f3edef86b Mon Sep 17 00:00:00 2001 From: James Long Date: Wed, 11 Nov 2026 13:49:51 -0600 Subject: [PATCH] feat(core): always run subagents in the background (#63382) --- .../subagent-child-navigation.spec.ts | 9 +- .../e2e/regression/timeline-stream.spec.ts | 15 +- packages/app/src/session/composer/region.tsx | 2 +- .../app/src/session/requests/background.ts | 59 +---- .../src/session/requests/steer-background.ts | 3 +- .../src/session/timeline/message-timeline.tsx | 2 +- .../test-browser/session-background.test.ts | 48 ++-- packages/cli/test/run/noninteractive.test.ts | 41 +++ packages/core/src/tool/plugin/subagent.ts | 61 +---- packages/core/test/subagent-idle-e2e.test.ts | 23 +- packages/core/test/subagent-lifetime.test.ts | 2 +- packages/core/test/tool-subagent.test.ts | 233 ++++++++---------- .../timeline/research-and-agents.stories.tsx | 23 +- .../session-ui/src/tools/run-machine.test.ts | 13 +- packages/session-ui/src/tools/run-machine.ts | 15 +- .../session-ui/src/tools/tool-renderer.tsx | 11 +- packages/tui/src/mini/footer.ts | 2 - packages/tui/src/mini/footer.view.tsx | 22 +- packages/tui/src/mini/footer.width.ts | 4 +- packages/tui/src/mini/runtime.lifecycle.ts | 2 - packages/tui/src/mini/runtime.ts | 8 - packages/tui/src/mini/stream-v2.subagent.ts | 14 +- packages/tui/src/mini/types.ts | 1 - packages/tui/src/routes/session/index.tsx | 15 +- .../tui/inline-tool-wrap-snapshot.test.tsx | 8 - packages/tui/test/mini/footer.view.test.tsx | 12 +- packages/tui/test/mini/footer.width.test.ts | 1 - .../tui/test/mini/stream-v2.transport.test.ts | 5 +- services/site/src/docs/content/agents.mdx | 5 +- .../docs/content/build/plugins/gui/index.mdx | 2 +- services/site/src/docs/content/tools.mdx | 11 +- 31 files changed, 267 insertions(+), 405 deletions(-) diff --git a/packages/app/e2e/regression/subagent-child-navigation.spec.ts b/packages/app/e2e/regression/subagent-child-navigation.spec.ts index c60b60acfde..d6a3ca90c77 100644 --- a/packages/app/e2e/regression/subagent-child-navigation.spec.ts +++ b/packages/app/e2e/regression/subagent-child-navigation.spec.ts @@ -78,7 +78,7 @@ test("keeps the parent title anchored when opening a subagent", async ({ page }) } }) -test("navigates from a running subagent card and hides background controls in the child", async ({ page }) => { +test("navigates from a running subagent card without a background control", async ({ page }) => { const runningChildID = "ses_running_child" await setupTimeline(page, { settings: { timelineDetail: { ...timelinePresets[2].value, subagents: { placement: "separate" } } }, @@ -95,11 +95,12 @@ test("navigates from a running subagent card and hides background controls in th id: "call_subagent", name: "subagent", state: { - status: "running", + status: "completed", input: { description: "Inspect code" }, metadata: { status: "running", sessionID: runningChildID }, + content: [{ type: "text", text: "The subagent is working in the background." }], }, - time: { created: 2 }, + time: { created: 2, completed: 3 }, }, ], time: { created: 2 }, @@ -109,7 +110,7 @@ test("navigates from a running subagent card and hides background controls in th sessionStatus: { [sessionID]: { type: "busy" }, [runningChildID]: { type: "busy" } }, }) const hint = page.getByRole("button", { name: /move running work to the background/i }) - await expect(hint).toBeVisible() + await expect(hint).toHaveCount(0) await page.locator('[data-component="task-tool-card"]').click() await expect(page).toHaveURL(new RegExp(`/session/${runningChildID}$`)) await expect(hint).toHaveCount(0) diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 54f3e0dbc8e..fa7e6cc4108 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1040,7 +1040,7 @@ test("grows a streaming row without a ResizeObserver loop error", async ({ page }) test.describe("background shortcut", () => { - test("offers a standalone running subagent to the background with Ctrl+B", async ({ page }) => { + test("does not offer a running subagent to the background", async ({ page }) => { await setupTimeline(page, { settings: { timelineDetail: { ...detailed, subagents: { placement: "separate" } } }, sessionMessages: [user, runningSubagent()], @@ -1050,19 +1050,8 @@ test.describe("background shortcut", () => { await expect(card).not.toContainText("(background)") await expect(page.getByText("Called `subagent`", { exact: false })).toHaveCount(0) await expect(page.locator('[data-component="background-tool-control"]')).toHaveCount(0) - const hint = backgroundHint(page) - await expect(hint).toBeVisible() + await expect(backgroundHint(page)).toHaveCount(0) await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0) - await expect - .poll(async () => { - const [cardBox, hintBox] = await Promise.all([card.boundingBox(), hint.boundingBox()]) - - if (!cardBox || !hintBox) return undefined - - return { aligned: Math.abs(cardBox.x - hintBox.x) < 2, ordered: cardBox.y < hintBox.y } - }) - .toEqual({ aligned: true, ordered: true }) - await expectBackgroundRequest(page) }) for (const name of ["read", "shell"] as const) { diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index d1432a66e1f..fb7abbba899 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -454,7 +454,7 @@ export function ActiveSessionComposerRegion(props: { ...task, agent: task.agent ?? (task.sessionID ? data.session.get(task.sessionID)?.agent : undefined), key: task.id, - target: task.partID ?? task.id, + target: task.id, })), ) diff --git a/packages/app/src/session/requests/background.ts b/packages/app/src/session/requests/background.ts index 1f305781450..a92d62b29d5 100644 --- a/packages/app/src/session/requests/background.ts +++ b/packages/app/src/session/requests/background.ts @@ -9,12 +9,11 @@ import { Option, Schema } from "effect" import { createMemo } from "solid-js" // `started` is when the work began running: the latest call's run time, the child session's creation, or the shell's -// start. A subagent's `partID` names the call that still blocks the run. +// start. type Subagent = { id: string type: "subagent" - sessionID: string | undefined - partID: string | undefined + sessionID: string label: string | undefined agent?: string started: number @@ -62,18 +61,15 @@ export function createSessionBackground(input: { calls, blocking: assistant?.content.flatMap((part) => { - if (part.type !== "tool" || part.state.status !== "running") return [] - - if (part.name !== "shell" && part.name !== "subagent") return [] - const shell = part.name === "shell" + if (part.type !== "tool" || part.state.status !== "running" || part.name !== "shell") return [] return [ { - type: shell ? ("shell" as const) : ("subagent" as const), + type: "shell" as const, partID: part.id, - id: text(shell ? part.state.metadata.shellID : part.state.metadata.sessionID), - label: text(shell ? part.state.input.command : part.state.input.description), - agent: shell ? undefined : text(part.state.input.agent), + id: text(part.state.metadata.shellID), + label: text(part.state.input.command), + agent: undefined, started: part.time.ran ?? part.time.created, }, ] @@ -83,8 +79,8 @@ export function createSessionBackground(input: { const blocking = createMemo(() => history().blocking) - // Like the TUI, a subagent runs exactly while its session, or any session below it, is running. A blocking call - // stands in only until its child session is known. + // Like the TUI, a subagent runs exactly while its session, or any session below it, is running. Subagents always run + // in the background, so every running descendant is background work. const subagents = createMemo(() => { const id = input.sessionID() @@ -106,13 +102,8 @@ export function createSessionBackground(input: { return false } - // A call names its child once the child exists; until the call reports it, the child's title is its description. - const calls = current.blocking.flatMap((item) => (item.type === "subagent" ? [item] : [])) - - const child = (item: (typeof calls)[number], info: SessionInfo) => - item.id ? info.id === item.id : !!item.label && info.parentID === id && info.title === item.label - - const running = sessions.flatMap((info): Subagent[] => { + // The latest call for a child names it; its own session decides whether it still runs. + return sessions.flatMap((info): Subagent[] => { if (input.status(info.id) !== "running" || !descends(info.id)) return [] const latest = current.calls.get(info.id) @@ -121,36 +112,15 @@ export function createSessionBackground(input: { id: info.id, type: "subagent", sessionID: info.id, - partID: calls.find((item) => child(item, info))?.partID, label: latest?.label ?? info.title ?? info.id, agent: latest?.agent, started: latest?.started ?? info.time.created, }, ] }) - - const pending = calls.flatMap((item): Subagent[] => - sessions.some((info) => child(item, info)) - ? [] - : [ - { - id: item.id ?? item.partID, - type: "subagent", - sessionID: item.id, - partID: item.partID, - label: item.label, - agent: item.agent, - started: item.started, - }, - ], - ) - - // Work that blocks the run comes before work already in the background. - return [...pending, ...running.filter((task) => task.partID), ...running.filter((task) => !task.partID)] }) - // Background work: running subagents whose call no longer blocks the run, and the session's live shells outside - // its blocking calls. + // Background work: every running subagent, and the session's live shells outside its blocking calls. const tasks = createMemo((): Task[] => { const id = input.sessionID() @@ -170,10 +140,7 @@ export function createSessionBackground(input: { return [{ id: shell.id, type: "shell" as const, label: shell.command, started: shell.time.started }] }) - return [ - ...subagents().flatMap((task) => (task.partID ? [] : [{ ...task, label: task.label ?? task.id }])), - ...shells, - ] + return [...subagents().map((task) => ({ ...task, label: task.label ?? task.id })), ...shells] }) return { blocking, subagents, tasks } diff --git a/packages/app/src/session/requests/steer-background.ts b/packages/app/src/session/requests/steer-background.ts index 03b6690e237..5914e887037 100644 --- a/packages/app/src/session/requests/steer-background.ts +++ b/packages/app/src/session/requests/steer-background.ts @@ -1,5 +1,6 @@ /** - * A steer moves the run's blocking shells and subagents to the background, so the agent reads it at its next step. + * A steer moves the run's blocking shells to the background, so the agent reads it at its next step. Subagents always + * run in the background already, so a steer never moves them. * The move reads the blocking work once the steer is admitted, so work that started during admission moves too. * Nothing is claimed: the server moves each job once and ignores repeated moves, so overlapping steers, a failed * move, or one that ran before a job started never leave work for a later steer to skip. diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index d7b72eddfda..d91da9f0b92 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -41,7 +41,7 @@ import { SessionHeaderSpacer } from "@/session/header/session-header" import { SessionHeaderGap } from "@/session/header/drag-area" import { SessionWorkingIndicator } from "@/session/header/session-working-indicator" -type BlockingTask = { type: "shell" | "subagent"; partID: string; id?: string; label?: string; started: number } +type BlockingTask = { type: "shell"; partID: string; id?: string; label?: string; started: number } type SessionBackground = { blocking: Accessor diff --git a/packages/app/test-browser/session-background.test.ts b/packages/app/test-browser/session-background.test.ts index be520f8d900..365fef2b4b2 100644 --- a/packages/app/test-browser/session-background.test.ts +++ b/packages/app/test-browser/session-background.test.ts @@ -117,7 +117,7 @@ describe("createSessionBackground", () => { }) }) - test("shows a blocking call until its child session is known, then follows the child's status", () => { + test("ignores a legacy blocking subagent call and counts its running child", () => { createRoot((dispose) => { const [store, setStore] = createStore<{ messages: ReturnType[] @@ -126,10 +126,14 @@ describe("createSessionBackground", () => { }>({ messages: [ assistant("current", [ - tool("call", "subagent", {}, { description: "Inspect", agent: "explore" }, "running", { - created: 5, - ran: 6, - }), + tool( + "call", + "subagent", + { status: "running", sessionID: "child" }, + { description: "Inspect", agent: "explore" }, + "running", + { created: 5, ran: 6 }, + ), ]), ], sessions: [], @@ -144,27 +148,26 @@ describe("createSessionBackground", () => { shells: () => [], }) - const pending = { - id: "call", + // Subagents always run in the background, so a leftover running call blocks nothing. + expect(background.blocking()).toEqual([]) + expect(background.subagents()).toEqual([]) + expect(background.tasks()).toEqual([]) + + setStore("sessions", [session("child")]) + expect(background.subagents()).toEqual([]) + setStore("status", "child", "running") + + const task = { + id: "child", type: "subagent", - sessionID: undefined, - partID: "call", + sessionID: "child", label: "Inspect", agent: "explore", started: 6, } - expect(background.subagents()).toEqual([pending]) - setStore("messages", 0, "content", 0, "state", "metadata", { sessionID: "child" }) - expect(background.subagents()).toEqual([{ ...pending, id: "child", sessionID: "child" }]) - setStore("sessions", [session("child")]) - expect(background.subagents()).toEqual([]) - setStore("status", "child", "running") - expect(background.subagents()).toEqual([{ ...pending, id: "child", sessionID: "child" }]) - // Blocking work is not background work. - expect(background.tasks()).toEqual([]) - setStore("messages", 0, "time", "completed", 7) - expect(background.blocking()).toEqual([]) - expect(background.tasks()).toEqual([{ ...pending, id: "child", sessionID: "child", partID: undefined }]) + + expect(background.subagents()).toEqual([task]) + expect(background.tasks()).toEqual([task]) dispose() }) }) @@ -212,11 +215,10 @@ describe("createSessionBackground", () => { id: "live-child", type: "subagent", sessionID: "live-child", - partID: undefined, label: "live-child", started: 40, }, - { id: "child", type: "subagent", sessionID: "child", partID: undefined, label: "renamed", started: 0 }, + { id: "child", type: "subagent", sessionID: "child", label: "renamed", started: 0 }, { id: "shell", type: "shell", label: "updated command", started: 0 }, ]) expect(background.blocking()).toBe(blocking) diff --git a/packages/cli/test/run/noninteractive.test.ts b/packages/cli/test/run/noninteractive.test.ts index f6ee2eb9ca9..9061888df42 100644 --- a/packages/cli/test/run/noninteractive.test.ts +++ b/packages/cli/test/run/noninteractive.test.ts @@ -670,6 +670,47 @@ describe("runNonInteractivePrompt", () => { expect(lists).toEqual([]) }) + test("waits for a subagent's report and the parent turn it triggers before exiting", async () => { + const lists: ExperimentalJobListOutput[] = [[subagentJob], []] + const output = await capture({ + format: "json", + jobs: () => lists.shift() ?? [], + messages: (messageID) => [ + idleMessage("failed", "msg_report_idle"), + { id: messageID, type: "user", text: "hello", time: { created: 1 } }, + ], + turn: (id) => [ + prompted(id), + settled(), + { + id: "evt_report_text", + created: 2, + type: "session.text.ended", + durable: { aggregateID: "ses_1", seq: 2, version: 1 }, + data: { sessionID: "ses_1", assistantMessageID: "msg_report_answer", ordinal: 0, text: "Report handled." }, + }, + { + id: "evt_report_failed", + created: 3, + type: "session.execution.failed", + durable: { aggregateID: "ses_1", seq: 3, version: 1 }, + data: { sessionID: "ses_1", error: { type: "unknown", message: "report turn failed" } }, + }, + ], + }) + const events = jsonLines(output.stdout) + expect(events.find((event) => event.type === "background_wait")).toMatchObject({ + jobs: [{ id: "ses_child", kind: "subagent" }], + }) + expect(output.stdout).toContain("Report handled.") + // The first turn succeeded; the report-triggered turn decides the exit code. + expect(output.exitCode).toBe(1) + expect(events.find((event) => event.type === "error")).toMatchObject({ + error: { message: "Execution failed" }, + }) + expect(lists).toEqual([]) + }) + test("a recovered step failure exits 0, reports its retry once, and still waits for background work", async () => { const lists: ExperimentalJobListOutput[] = [[shellJob("sh_train", "python train.py")], []] const retry = { attempt: 1, error: { type: "provider.transport", message: "Recovered transport error" } } diff --git a/packages/core/src/tool/plugin/subagent.ts b/packages/core/src/tool/plugin/subagent.ts index f6337f89c88..acff3a36475 100644 --- a/packages/core/src/tool/plugin/subagent.ts +++ b/packages/core/src/tool/plugin/subagent.ts @@ -11,7 +11,6 @@ import { Model } from "../../model.js" import { Permission } from "../../permission.js" import { Session } from "../../session.js" import { SessionSchema } from "../../session/schema.js" -import { SubagentCompletion } from "../../session/subagent-completion.js" import { SubagentJob } from "../../session/subagent-job.js" import { SubagentMetadata } from "../../session/subagent-metadata.js" @@ -22,12 +21,12 @@ const backgroundResult = (sessionID: SessionSchema.ID, notify: boolean) => ({ status: "running" as const, output: notify ? [ - `The subagent is working in the background (sessionID: ${sessionID}). You will be notified automatically when it finishes.`, + `The subagent is working in the background (sessionID: ${sessionID}). You will receive a message when it goes idle, and again after each later round of work.`, "DO NOT sleep, poll for progress, ask the subagent for status, or duplicate this subagent's work; avoid working with the same files or topics it is using.", "Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.", "To send it follow-ups or change its instructions while it runs, call subagent again with this sessionID.", ].join("\n") - : `The subagent is working in the background (sessionID: ${sessionID}) and will not notify you when it finishes. To check on it, call the subagent tool with this sessionID or read the session.`, + : `The subagent is working in the background (sessionID: ${sessionID}) and will not notify you when it finishes, so you won't receive its result. Only use notify=false for work whose result you don't need. To send it more work, call subagent again with this sessionID.`, }) export const Input = Schema.Struct({ @@ -44,10 +43,6 @@ export const Input = Schema.Struct({ sessionID: Schema.optionalKey(SessionSchema.ID).annotate({ description: "Send a follow-up to an existing subagent, running or finished. Omit to start a new one.", }), - background: Schema.optionalKey(Schema.Boolean).annotate({ - description: - "Run the subagent in the background and return immediately. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress.", - }), notify: Schema.optionalKey(Schema.Boolean).annotate({ description: "Send you a `` message each time this subagent goes idle. Defaults to true for new subagents. On follow-ups (sessionID), keeps the subagent's current setting unless you pass it.", @@ -56,16 +51,16 @@ export const Input = Schema.Struct({ export const Output = Schema.Struct({ sessionID: SessionSchema.ID, - status: Schema.Literals(["completed", "running"]), + status: Schema.Literal("running"), output: Schema.String, }) export const description = [ "Spawns an agent in a child session to work on the specified task.", - "The output includes a sessionID you can pass back later to continue that specific conversation with the subagent.", + "Subagents always run in the background: the call returns immediately with a sessionID, and you receive a `` message each time the child goes idle, including after later work.", + "Keep working on non-overlapping tasks, or briefly tell the user what you launched and end your response. Do not sleep, poll for progress, or ask the child for status.", "New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.", - "Foreground (default) runs the subagent to completion and returns its final response.", - "Background mode (background=true) launches it asynchronously and returns immediately; you are notified when it finishes.", - "Use background only for independent work that can run while you continue elsewhere.", + "Pass the returned sessionID to continue that specific child conversation. A follow-up to a running child joins its current run.", + "Pass notify=false for a new subagent only if you don't need its results: you won't receive its idle reports.", ].join("\n") export const Plugin = { @@ -209,7 +204,6 @@ export const Plugin = { ), )) - const background = input.background === true const notify = input.notify ?? SubagentMetadata.notify(child.metadata) // A child that is not draining yet must be admitted without waking: the job's resume // owns the start, so the period cannot run before its boundary is registered. @@ -240,47 +234,12 @@ export const Plugin = { agent: agent.name, description: input.description, } - yield* subagents.start(recovery, { background }) - - if (background) return backgroundResult(child.id, notify) - - const result = yield* jobs.block({ id: child.id, sessionID: context.sessionID }).pipe( - Effect.onInterrupt(() => - Effect.all([sessions.interrupt(child.id), jobs.cancel(child.id)], { - discard: true, - }), - ), - ) - if (result?.type === "backgrounded") return backgroundResult(child.id, notify) - // Failure surfaces keep the sessionID visible so the model can continue the child. - if (result?.info.status === "error") - return yield* new ToolFailure({ - message: SubagentCompletion.formatBody( - `Subagent failed (sessionID: ${child.id}): ${result.info.error ?? "unknown error"}`, - child.id, - yield* subagents.outstanding(child.id), - ), - }) - if (result?.info.status === "cancelled") - return yield* new ToolFailure({ - message: SubagentCompletion.formatBody( - `Subagent cancelled (sessionID: ${child.id})`, - child.id, - yield* subagents.outstanding(child.id), - ), - }) - return { - sessionID: child.id, - status: "completed" as const, - output: result?.info.output ?? SubagentCompletion.NO_TEXT, - } + yield* subagents.start(recovery, { background: true }) + return backgroundResult(child.id, notify) }).pipe( Effect.map((output) => ({ output, - content: - output.status === "completed" - ? `\n${output.output}\n` - : output.output, + content: output.output, metadata: { sessionID: output.sessionID, status: output.status }, })), ), diff --git a/packages/core/test/subagent-idle-e2e.test.ts b/packages/core/test/subagent-idle-e2e.test.ts index 6abe7a75c8b..10263169cbc 100644 --- a/packages/core/test/subagent-idle-e2e.test.ts +++ b/packages/core/test/subagent-idle-e2e.test.ts @@ -334,7 +334,7 @@ describe("subagent idle reports end to end", () => { }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") expect(launched).toMatchObject({ status: "completed", metadata: { status: "running" } }) yield* waitForReports(h, h.parent.id, 1) @@ -372,7 +372,7 @@ describe("subagent idle reports end to end", () => { build: [TestLLM.text("parent ack", "parent-1"), TestLLM.text("parent ack", "parent-2")], }), ) - const launched = yield* h.call("call-launch", { background: true }) + 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") @@ -412,18 +412,18 @@ describe("subagent idle reports end to end", () => { build: [TestLLM.text("parent ack", "parent-1"), TestLLM.text("parent ack", "parent-2")], }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* waitForReports(h, h.parent.id, 1) yield* h.sessions.wait(childID) yield* h.jobs.wait({ id: childID }) - const second = yield* h.call("call-follow-up", { background: true, sessionID: childID }) + const second = yield* h.call("call-follow-up", { sessionID: childID }) expect(second).toMatchObject({ metadata: { sessionID: childID, status: "running" } }) yield* waitForReports(h, h.parent.id, 2) expect((yield* deliveredReports(h, h.parent.id))[1]!.text).toContain("second answer") - const third = yield* h.call("call-follow-up-again", { background: true, sessionID: childID }) + const third = yield* h.call("call-follow-up-again", { sessionID: childID }) expect(third).toMatchObject({ metadata: { sessionID: childID, status: "running" } }) yield* waitForReports(h, h.parent.id, 3) expect((yield* deliveredReports(h, h.parent.id))[2]!.text).toContain("third answer") @@ -454,7 +454,6 @@ describe("subagent idle reports end to end", () => { agent: "fallback", description: "grandchild review", prompt: "review the grandchild fixture", - background: true, }), TestLLM.text("child launched grandchild", "child-turn-1"), TestLLM.text("child saw first grandchild report", "child-turn-2"), @@ -474,7 +473,7 @@ describe("subagent idle reports end to end", () => { }), ) - const launched = yield* h.call("call-child", { background: true, description: "child review" }) + const launched = yield* h.call("call-child", { description: "child review" }) const childID = outputSessionID(launched.metadata) yield* waitForReports(h, h.parent.id, 1) @@ -532,7 +531,6 @@ describe("subagent idle reports end to end", () => { agent: "fallback", description: "grandchild review", prompt: "review the grandchild fixture", - background: true, }), TestLLM.text("silent child launched grandchild", "child-turn-1"), TestLLM.text("silent child saw grandchild", "child-turn-2"), @@ -543,7 +541,6 @@ describe("subagent idle reports end to end", () => { ) const launched = yield* h.call("call-silent-child", { - background: true, notify: false, description: "silent child review", }) @@ -578,7 +575,7 @@ describe("subagent idle reports end to end", () => { }), ) - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* Deferred.await(crashed) yield* h.sessions.wait(childID) @@ -647,7 +644,7 @@ describe("subagent idle reports end to end", () => { type: "tool-call", id: "call-launch", name: SubagentTool.name, - input: { agent: "reviewer", description: "restart review", prompt: "review this", background: true }, + input: { agent: "reviewer", description: "restart review", prompt: "review this" }, }, }) const childID = outputSessionID(launched.metadata) @@ -704,7 +701,7 @@ describe("subagent idle reports end to end", () => { }), ) const gate = yield* h.llm.gate() - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* gate.started expect((yield* claims(h))[childID]).toBe(true) @@ -739,7 +736,7 @@ describe("subagent idle reports end to end", () => { }), ) const gate = yield* h.llm.gate() - const launched = yield* h.call("call-launch", { background: true }) + const launched = yield* h.call("call-launch") const childID = outputSessionID(launched.metadata) yield* gate.started diff --git a/packages/core/test/subagent-lifetime.test.ts b/packages/core/test/subagent-lifetime.test.ts index 0a5de6d13b1..d24148b8d9b 100644 --- a/packages/core/test/subagent-lifetime.test.ts +++ b/packages/core/test/subagent-lifetime.test.ts @@ -106,11 +106,11 @@ describe("subagent observer lifetime", () => { sessionID: child.id, description: "Review fixture", prompt: "Review the fixture", - background: true, }, }, }) expect(result.status).toBe("completed") + expect(result.output).toMatchObject({ status: "running" }) yield* gate.started expect(yield* sessions.context(parent.id)).toEqual([]) if (evict) { diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 714e5502d33..503a2ea0f78 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Context, Deferred, Effect, Exit, Fiber, Layer, Schema, Scope, Stream } from "effect" -import { LanguageModel } from "@opencode/ai/effect" +import { AIError, InvalidRequestError, LanguageModel, LLMEvent } from "@opencode/ai/effect" import { OpenAIChat } from "@opencode/ai/protocols" import { TestLLM } from "@opencode/ai/testing" import path from "path" @@ -45,9 +45,6 @@ import { testEffect } from "./lib/effect" import { executeTool, registerToolPlugin, toolIdentity } from "./lib/tool" const childText = "child final response" -const subagentOutput = (sessionID: Session.ID, output: string) => - `\n${output}\n` -const completedOutput = (sessionID: Session.ID) => subagentOutput(sessionID, childText) const childModel = Model.Ref.make({ id: Model.ID.make("child"), providerID: Provider.ID.make("test") }) const parentModel = Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }) const overrideModel = Model.Ref.make({ @@ -262,7 +259,7 @@ describe("SubagentTool", () => { type: "tool-call", id: "call-completion-replay", name: SubagentTool.name, - input: { agent: "reviewer", description: "background review", prompt: "review", background: true }, + input: { agent: "reviewer", description: "background review", prompt: "review" }, }, }) const marker = yield* Deferred.await(admitted) @@ -409,12 +406,13 @@ describe("SubagentTool", () => { expect(settled).toMatchObject({ status: "completed", - metadata: { status: "completed" }, - content: [{ type: "text", text: expect.stringContaining(childText) }], + output: { status: "running" }, + metadata: { status: "running" }, + content: [{ type: "text", text: expect.stringContaining("working in the background") }], }) expect(settled.metadata).toEqual({ sessionID: outputSessionID(settled.metadata), - status: "completed", + status: "running", }) expect((yield* sessions.get(outputSessionID(settled.metadata))).parentID).toBe(parent.id) }), @@ -422,7 +420,7 @@ describe("SubagentTool", () => { ), ) - it.live("runs a foreground child session and returns the final assistant text", () => + it.live("starts a child session and returns the running handle", () => tmpdirScoped().pipe( Effect.flatMap((dir) => Effect.gen(function* () { @@ -448,12 +446,14 @@ describe("SubagentTool", () => { expect(settled).toMatchObject({ status: "completed", - metadata: { status: "completed" }, - content: [{ type: "text", text: expect.stringContaining(childText) }], + output: { status: "running" }, + metadata: { status: "running" }, + content: [{ type: "text", text: expect.stringContaining("working in the background") }], }) const child = yield* sessions.get(outputSessionID(settled.metadata)) - expect(settled.content).toEqual([{ type: "text", text: completedOutput(child.id) }]) - expect(settled.metadata).toEqual({ sessionID: child.id, status: "completed" }) + expect(settled.output).toMatchObject({ sessionID: child.id, status: "running" }) + expect(settled.output.output).toContain(`sessionID: ${child.id}`) + expect(settled.metadata).toEqual({ sessionID: child.id, status: "running" }) expect(progress[0]).toEqual({ sessionID: child.id, status: "running" }) expect(child).toMatchObject({ parentID: parent.id, @@ -529,7 +529,11 @@ describe("SubagentTool", () => { message.type === "user" ? [message.payload.text] : [], ), ).toEqual(["You are a subagent spawned by another session.\nreview this", "continue this"]) - expect(second.content).toEqual([{ type: "text", text: completedOutput(childID) }]) + expect(second).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) }), ), ), @@ -566,13 +570,13 @@ describe("SubagentTool", () => { description: "follow up", prompt: "continue while running", sessionID: child.id, - background: true, }, }, }) expect(result).toMatchObject({ status: "completed", + output: { status: "running" }, metadata: { sessionID: child.id, status: "running" }, }) expect((yield* sessions.inbox(child.id)).find((message) => message.type === "user")?.payload.text).toBe( @@ -585,7 +589,7 @@ describe("SubagentTool", () => { ), ) - completionIt.live("follow-ups to a running background child return immediately and notify once", () => + completionIt.live("follow-ups to a running child return immediately and notify once", () => tmpdirScoped().pipe( Effect.flatMap((dir) => Effect.gen(function* () { @@ -605,7 +609,7 @@ describe("SubagentTool", () => { Stream.runCollect, Effect.forkScoped({ startImmediately: true }), ) - const call = (id: string, input: { background?: boolean; sessionID?: Session.ID }) => + const call = (id: string, input: { sessionID?: Session.ID }) => executeTool(registry, { sessionID: parent.id, ...toolIdentity, @@ -617,12 +621,12 @@ describe("SubagentTool", () => { }, }).pipe(Effect.timeout("2 seconds")) - const launched = yield* call("call-launch", { background: true }) + const launched = yield* call("call-launch", {}) const childID = outputSessionID(launched.metadata) yield* gate.started - const steered = yield* call("call-steer", { background: true, sessionID: childID }) - const unflagged = yield* call("call-steer-foreground", { sessionID: childID }) - ;[launched, steered, unflagged].forEach((result) => + const steered = yield* call("call-steer", { sessionID: childID }) + const followed = yield* call("call-steer-again", { sessionID: childID }) + ;[launched, steered, followed].forEach((result) => expect(result).toMatchObject({ metadata: { sessionID: childID, status: "running" } }), ) @@ -713,7 +717,8 @@ describe("SubagentTool", () => { }) expect(yield* call(switched.id, "call-switched-child")).toMatchObject({ status: "completed", - metadata: { sessionID: switched.id, status: "completed" }, + output: { status: "running" }, + metadata: { sessionID: switched.id, status: "running" }, }) expect(yield* sessions.get(switched.id)).toMatchObject({ agent: "reviewer", @@ -722,7 +727,8 @@ describe("SubagentTool", () => { // Switching to an agent without a configured model keeps the child's current model. expect(yield* call(switched.id, "call-modelless-switch", "fallback")).toMatchObject({ status: "completed", - metadata: { sessionID: switched.id, status: "completed" }, + output: { status: "running" }, + metadata: { sessionID: switched.id, status: "running" }, }) expect(yield* sessions.get(switched.id)).toMatchObject({ agent: "fallback", @@ -757,13 +763,21 @@ describe("SubagentTool", () => { // The requested model beats the agent's configured model. const spawned = yield* call("call-override", { model: "test/override#fast", sessionID: "" }) - expect(spawned).toMatchObject({ status: "completed", metadata: { status: "completed" } }) + expect(spawned).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { status: "running" }, + }) const child = yield* sessions.get(outputSessionID(spawned.metadata)) expect(child).toMatchObject({ agent: "reviewer", model: overrideModel }) // Continuing with a model switches the existing child even when the agent is unchanged. const continued = yield* call("call-override-continue", { sessionID: child.id, model: "test/override" }) - expect(continued).toMatchObject({ status: "completed", metadata: { sessionID: child.id } }) + expect(continued).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: child.id, status: "running" }, + }) expect((yield* sessions.get(child.id)).model).toEqual({ id: overrideModel.id, providerID: overrideModel.providerID, @@ -795,40 +809,6 @@ describe("SubagentTool", () => { ), ) - it.live("returns child runner failures as tool errors", () => - tmpdirScoped().pipe( - Effect.flatMap((dir) => - Effect.gen(function* () { - const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) - const sessions = yield* Session.Service - const parent = yield* sessions.create({ location }) - yield* withSubagent(parent.location) - const locations = yield* LocationServiceMap.Service - const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) - - expect( - yield* executeTool(registry, { - sessionID: parent.id, - ...toolIdentity, - call: { - type: "tool-call", - id: "call-subagent-failure", - name: SubagentTool.name, - input: { agent: "reviewer", description: "fail review", prompt: "please fail" }, - }, - }), - ).toEqual({ - status: "error", - error: { - type: "tool.execution", - message: expect.stringContaining("No model is available for session"), - }, - }) - }), - ), - ), - ) - completionIt.live("notifies once when background work completes", () => tmpdirScoped().pipe( Effect.flatMap((dir) => @@ -861,7 +841,7 @@ describe("SubagentTool", () => { type: "tool-call", id: "call-background-subagent", name: SubagentTool.name, - input: { agent: "reviewer", description: "background review", prompt: "review", background: true }, + input: { agent: "reviewer", description: "background review", prompt: "review" }, }, }) const childID = outputSessionID(settled.metadata) @@ -932,62 +912,82 @@ const reportingFixture = () => }) describe("SubagentTool reporting", () => { - completionIt.live("returns a foreground answer inline without reporting to the parent", () => + completionIt.live("reports the child's final answer to the parent", () => Effect.gen(function* () { const fixture = yield* reportingFixture() - const settled = yield* fixture.call("call-foreground-inline") + const settled = yield* fixture.call("call-report") const childID = outputSessionID(settled.metadata) - expect(settled.status).toBe("completed") - expect(settled.content).toEqual([{ type: "text", text: completedOutput(childID) }]) - expect((yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent")).toEqual([]) + expect(settled).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) + yield* fixture.sessions.wait(childID) + yield* fixture.sessions.wait(fixture.parent.id) + + const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") + expect(reports).toHaveLength(1) + expect(reports[0]?.text).toContain(` + completionIt.live("reports only the current busy period when an idle child is continued", () => Effect.gen(function* () { const fixture = yield* reportingFixture() const llm = yield* TestLLM.Test yield* llm.push(TestLLM.text("first answer", "first")) - const first = yield* fixture.call("call-foreground-first") + const first = yield* fixture.call("call-first") const childID = outputSessionID(first.metadata) - expect(first.content).toEqual([{ type: "text", text: subagentOutput(childID, "first answer") }]) + yield* fixture.sessions.wait(childID) + yield* fixture.sessions.wait(fixture.parent.id) + const firstReports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") + expect(firstReports).toHaveLength(1) + expect(firstReports[0]?.text).toContain("first answer") - const second = yield* fixture.call("call-foreground-second", { sessionID: childID }) - expect(second.content).toEqual([{ type: "text", text: completedOutput(childID) }]) + const second = yield* fixture.call("call-second", { sessionID: childID }) + expect(second).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) + yield* fixture.sessions.wait(childID) + yield* fixture.sessions.wait(fixture.parent.id) + + const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") + expect(reports).toHaveLength(2) + expect(reports[1]?.text).toContain(childText) + expect(reports[1]?.text).not.toContain("first answer") }), ) - completionIt.live("includes still-running background work in a foreground answer", () => + completionIt.live("reports a child runner failure to the parent", () => Effect.gen(function* () { const fixture = yield* reportingFixture() - const jobs = yield* Job.Service - const child = yield* fixture.sessions.create({ - parentID: fixture.parent.id, - title: "review", - agent: Agent.ID.make("reviewer"), - model: childModel, - }) - yield* jobs.start({ - id: "sh_foreground_shell", - type: "shell", - recovery: { kind: "shell", sessionID: child.id, shellID: "sh_1", command: "bun test --watch" }, - background: true, - run: Effect.never, - }) + const llm = yield* TestLLM.Test + yield* llm.push( + TestLLM.failAfter( + new AIError({ reason: new InvalidRequestError({ message: "provider exploded" }) }), + LLMEvent.textStart({ id: "failed" }), + ), + ) - const settled = yield* fixture.call("call-foreground-running-shell", { sessionID: child.id }) - expect(settled.content).toEqual([ - { - type: "text", - text: subagentOutput( - child.id, - `${childText}\n\nBackground work still running:\n- shell (sh_1): bun test --watch`, - ), - }, - ]) - yield* jobs.cancel("sh_foreground_shell") + const settled = yield* fixture.call("call-failing-child", { description: "fail review" }) + const childID = outputSessionID(settled.metadata) + expect(settled).toMatchObject({ + status: "completed", + output: { status: "running" }, + metadata: { sessionID: childID, status: "running" }, + }) + yield* fixture.sessions.wait(childID) + yield* fixture.sessions.wait(fixture.parent.id) + + const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") + expect(reports).toHaveLength(1) + expect(reports[0]?.text).toContain(` { Effect.gen(function* () { const fixture = yield* reportingFixture() const jobs = yield* Job.Service - const spawned = yield* fixture.call("call-silent-spawn", { background: true, notify: false }) + const spawned = yield* fixture.call("call-silent-spawn", { notify: false }) const childID = outputSessionID(spawned.metadata) expect(spawned.content).toEqual([ { type: "text", - text: `The subagent is working in the background (sessionID: ${childID}) and will not notify you when it finishes. To check on it, call the subagent tool with this sessionID or read the session.`, + text: `The subagent is working in the background (sessionID: ${childID}) and will not notify you when it finishes, so you won't receive its result. Only use notify=false for work whose result you don't need. To send it more work, call subagent again with this sessionID.`, }, ]) expect((yield* fixture.sessions.get(childID)).metadata).toEqual({ "subagent.notify": false }) @@ -1009,16 +1009,21 @@ describe("SubagentTool reporting", () => { expect(yield* fixture.notices).toEqual([]) // Omitted notify keeps the child silent across follow-ups. - const silent = yield* fixture.call("call-silent-follow", { sessionID: childID, background: true }) + const silent = yield* fixture.call("call-silent-follow", { sessionID: childID }) expect(silent.content).toEqual(spawned.content) yield* fixture.sessions.wait(childID) yield* fixture.sessions.wait(fixture.parent.id) expect((yield* fixture.sessions.get(childID)).metadata).toEqual({ "subagent.notify": false }) expect(yield* fixture.notices).toEqual([]) - const loud = yield* fixture.call("call-loud-follow", { sessionID: childID, background: true, notify: true }) + const loud = yield* fixture.call("call-loud-follow", { sessionID: childID, notify: true }) expect(loud.content).toEqual([ - { type: "text", text: expect.stringContaining("You will be notified automatically when it finishes.") }, + { + type: "text", + text: expect.stringContaining( + "You will receive a message when it goes idle, and again after each later round of work.", + ), + }, ]) yield* fixture.sessions.wait(childID) yield* fixture.sessions.wait(fixture.parent.id) @@ -1051,7 +1056,7 @@ describe("SubagentTool reporting", () => { type: "tool-call", id: "call-silent-parent-child", name: SubagentTool.name, - input: { agent: "reviewer", description: "review", prompt: "review this", background: true }, + input: { agent: "reviewer", description: "review", prompt: "review this" }, }, }) const childID = outputSessionID(spawned.metadata) @@ -1066,30 +1071,6 @@ describe("SubagentTool reporting", () => { expect(delivered[0]?.text).toContain(` - Effect.gen(function* () { - const fixture = yield* reportingFixture() - const llm = yield* TestLLM.Test - const gate = yield* llm.gate() - const running = yield* fixture - .call("call-foreground-backgrounded", {}) - .pipe(Effect.forkScoped({ startImmediately: true })) - - yield* gate.started - yield* fixture.sessions.background(fixture.parent.id) - const settled = yield* Fiber.join(running) - const childID = outputSessionID(settled.metadata) - expect(settled).toMatchObject({ status: "completed", metadata: { sessionID: childID, status: "running" } }) - - yield* gate.release - yield* fixture.sessions.wait(childID) - yield* fixture.sessions.wait(fixture.parent.id) - const reports = (yield* fixture.notices).filter((notice) => notice.metadata?.["source"] === "subagent") - expect(reports).toHaveLength(1) - expect(reports[0]?.text).toContain(` { diff --git a/packages/session-ui/src/timeline/research-and-agents.stories.tsx b/packages/session-ui/src/timeline/research-and-agents.stories.tsx index 29d51b374e0..86e85d9fdd3 100644 --- a/packages/session-ui/src/timeline/research-and-agents.stories.tsx +++ b/packages/session-ui/src/timeline/research-and-agents.stories.tsx @@ -1,4 +1,4 @@ -import type { JsonValue, SessionMessageAssistant, SessionMessageAssistantTool } from "@opencode/client/promise" +import type { SessionMessageAssistant, SessionMessageAssistantTool } from "@opencode/client/promise" import { createMemo } from "solid-js" import { createStore } from "solid-js/store" import type { SessionDocument } from "../document" @@ -134,11 +134,9 @@ function CodebaseExplorationStory() { state: completed ? { status: "completed", input, content: [{ type: "text", text: "Complete" }], metadata: {} } : { status: "running", input, metadata: {} }, - time: { - created: STORY_TIME, - ran: STORY_TIME + 100, - ...(completed ? { completed: STORY_TIME + 200 } : {}), - }, + time: completed + ? { created: STORY_TIME, ran: STORY_TIME + 100, completed: STORY_TIME + 200 } + : { created: STORY_TIME, ran: STORY_TIME + 100 }, } satisfies SessionMessageAssistantTool } @@ -154,7 +152,9 @@ function CodebaseExplorationStory() { agent: "build", model: STORY_MODEL, content: [tool("read", state.read), tool("glob", state.glob)], - time: { created: STORY_TIME, ...(state.read && state.glob ? { completed: STORY_TIME + 300 } : {}) }, + time: state.read && state.glob + ? { created: STORY_TIME, completed: STORY_TIME + 300 } + : { created: STORY_TIME }, } satisfies SessionMessageAssistant, ], status: { type: state.read && state.glob ? "idle" : "busy" }, @@ -327,7 +327,7 @@ const RecoverFromToolFailures = { render: () => { const names = ["shell", "edit", "write", "patch", "webfetch", "websearch", "subagent", "skill", "mcp_probe"] - const input = (name: string): Record => { + const input = (name: string) => { if (name === "shell") return { command: "exit 1" } if (name === "edit" || name === "write") return { path: "src/error.ts", content: "" } @@ -423,7 +423,7 @@ const StartingBackgroundWork = { "tool_notice_background", "subagent", "running", - { description: "Inspect code", background: true }, + { description: "Inspect code" }, { metadata: { status: "running" }, }, @@ -452,5 +452,8 @@ const researchScenarios = { export const AgentResearch = { args: { scenario: "workflow" }, argTypes: { scenario: { control: "select", options: Object.keys(researchScenarios) } }, - render: (args: { scenario: string }) => researchScenarios[args.scenario as keyof typeof researchScenarios].render(), + render: (args: { scenario: string }) => + Object.entries(researchScenarios) + .find(([name]) => name === args.scenario)?.[1] + .render() ?? researchScenarios.workflow.render(), } diff --git a/packages/session-ui/src/tools/run-machine.test.ts b/packages/session-ui/src/tools/run-machine.test.ts index 85eacaa9f75..d2d7a146e2c 100644 --- a/packages/session-ui/src/tools/run-machine.test.ts +++ b/packages/session-ui/src/tools/run-machine.test.ts @@ -137,37 +137,34 @@ describe("transitionSubagentRun", () => { return transitionSubagentRun(state, { type: "sync", props: subagentRunProps(tool, childBusy) }) } - test("a subagent handed to the background runs until its child session goes idle", () => { + test("a subagent runs until its child session goes idle", () => { const delegating = step(INITIAL_SUBAGENT_RUN_STATE, { status: "streaming", metadata: {} }) expect(delegating).toBe(INITIAL_SUBAGENT_RUN_STATE) expect(viewSubagentRun(delegating)).toMatchObject({ delegating: true, running: true }) - const foreground = step(delegating, { status: "running", metadata: {} }, true) + const running = step(delegating, { status: "running", metadata: {} }, true) - expect(viewSubagentRun(foreground)).toEqual({ + expect(viewSubagentRun(running)).toEqual({ delegating: false, running: true, basicStatus: "running", - background: false, }) - // The call completes with `status: "running"` once the subagent moved to the background. + // The call completes with `status: "running"` while the child keeps working in the background. const handoff = { status: "completed", metadata: { ...child, status: "running" } } - const background = step(foreground, handoff, true) + const background = step(running, handoff, true) expect(viewSubagentRun(background)).toEqual({ delegating: false, running: true, basicStatus: "running", - background: true, }) expect(step(background, handoff, true)).toBe(background) expect(viewSubagentRun(step(background, handoff))).toEqual({ delegating: false, running: false, basicStatus: "completed", - background: true, }) }) diff --git a/packages/session-ui/src/tools/run-machine.ts b/packages/session-ui/src/tools/run-machine.ts index 03f8b68ba84..3232b4cb7c1 100644 --- a/packages/session-ui/src/tools/run-machine.ts +++ b/packages/session-ui/src/tools/run-machine.ts @@ -138,22 +138,18 @@ export function stoppedShell(tool: { /** A subagent call as the renderer decoded it. */ type SubagentTool = { readonly status: string | undefined - readonly metadata: { readonly status?: string; readonly background?: boolean } + readonly metadata: { readonly status?: string } } export type SubagentRunProps = { readonly status: string | undefined - readonly background: boolean - /** The child session is busy, which outlives the call when the subagent runs in the background. */ + /** The child session is busy, which outlives the call because every subagent runs in the background. */ readonly childBusy: boolean } export function subagentRunProps(tool: SubagentTool, childBusy: boolean): SubagentRunProps { return { status: tool.status, - // A completed call whose result reports `running` handed the subagent off to the background. - background: - tool.metadata.background === true || (tool.status === "completed" && tool.metadata.status === "running"), childBusy, } } @@ -161,7 +157,7 @@ export function subagentRunProps(tool: SubagentTool, childBusy: boolean): Subage /** The model is writing the delegation, or the subagent runs, finished or failed. */ export type SubagentRunState = | { readonly status: "delegating" } - | { readonly status: "running" | "completed" | "error"; readonly background: boolean } + | { readonly status: "running" | "completed" | "error" } export type SubagentRunEvent = { readonly type: "sync"; readonly props: SubagentRunProps } @@ -175,9 +171,9 @@ export function transitionSubagentRun(state: SubagentRunState, event: SubagentRu const status = props.status === "running" || props.childBusy ? "running" : props.status === "error" ? "error" : "completed" - if (state.status === status && state.background === props.background) return state + if (state.status === status) return state - return { status, background: props.background } + return { status } } export function viewSubagentRun(state: SubagentRunState) { @@ -185,6 +181,5 @@ export function viewSubagentRun(state: SubagentRunState) { delegating: state.status === "delegating", running: state.status === "delegating" || state.status === "running", basicStatus: state.status === "delegating" ? "streaming" : state.status, - background: state.status !== "delegating" && state.background, } } diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index b700af94489..66d56646609 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -163,7 +163,6 @@ export const toolMetadata = Schema.decodeUnknownSync( command: optional(Schema.String), shellID: optional(Schema.String), status: optional(Schema.String), - background: optional(Schema.Boolean), interrupted: optional(Schema.Boolean), notice: optional(Schema.String), count: optional(Schema.Finite), @@ -1771,15 +1770,7 @@ ToolRegistry.register({ const view = createMemo(() => viewSubagentRun(run())) - const subtitle = createMemo(() => { - const value = input().description || childSessionId() - - if (!value) return value - - if (view().background) return `${value} (background)` - - return value - }) + const subtitle = createMemo(() => input().description || childSessionId()) const href = createMemo(() => sessionLink(childSessionId(), data.sessionHref)) const clickable = createMemo(() => !!(childSessionId() && (data.navigateToSession || href()))) diff --git a/packages/tui/src/mini/footer.ts b/packages/tui/src/mini/footer.ts index eb868d99114..36b1cd69423 100644 --- a/packages/tui/src/mini/footer.ts +++ b/packages/tui/src/mini/footer.ts @@ -100,7 +100,6 @@ type RunFooterOptions = { onModelSelect?: (model: NonNullable) => CycleResult | void | Promise onVariantSelect?: (variant: string | undefined) => CycleResult | void | Promise onInterrupt?: () => void - onBackground?: () => void onQueuedPromptAction?: (action: QueuedPromptAction, inboxID: string) => Promise onEditorOpen: (input: { value: string }) => Promise onSubagentSelect?: (sessionID: string | undefined) => void @@ -358,7 +357,6 @@ export class RunFooter implements FooterApi { onFormCancel: footer.handleFormCancel, onCycle: footer.handleCycle, onInterrupt: footer.handleInterrupt, - onBackground: options.onBackground, onQueuedPromptAction: options.onQueuedPromptAction, onEditorOpen: (input) => { footer.finishStartup() diff --git a/packages/tui/src/mini/footer.view.tsx b/packages/tui/src/mini/footer.view.tsx index 21771043b20..405e770ee28 100644 --- a/packages/tui/src/mini/footer.view.tsx +++ b/packages/tui/src/mini/footer.view.tsx @@ -108,7 +108,6 @@ type RunFooterViewProps = { onFormCancel: (input: FormCancel) => void | Promise onCycle: () => void onInterrupt: () => boolean - onBackground?: () => void onQueuedPromptAction?: (action: QueuedPromptAction, inboxID: string) => Promise onEditorOpen: (input: { value: string }) => Promise onInputClear: () => void @@ -185,7 +184,6 @@ export function RunFooterView(props: RunFooterViewProps) { return tabs().findIndex((item) => item.sessionID === sessionID) + 1 }) - const foregroundSubagents = createMemo(() => activeTabs().some((item) => !item.background)) const model = createMemo(() => { const current = props.currentModel() return current ? modelInfo(props.providers(), current) : undefined @@ -199,7 +197,6 @@ export function RunFooterView(props: RunFooterViewProps) { const command = () => shortcut("command.palette.show") const subagentShortcut = () => shortcut("session.child.first") const queuedShortcut = () => shortcut("session.queued_prompts") - const backgroundShortcut = () => shortcut("session.background") const subagentInterruptShortcut = () => shortcut("composer.subagent.interrupt") const interrupt = () => shortcut("session.interrupt") const variantCycle = () => monoShortcut(shortcuts.all("variant.cycle") ?? "", props.mono) @@ -452,8 +449,7 @@ export function RunFooterView(props: RunFooterViewProps) { return [] } - const items: Array<{ id: "queued" | "subagents" | "background"; key: string; label: string; expanded?: string }> = - [] + const items: Array<{ id: "queued" | "subagents"; key: string; label: string; expanded?: string }> = [] if (queuedPrompts().length > 0 && queuedShortcut()) { items.push({ id: "queued", key: queuedShortcut(), label: `${queuedPrompts().length} pending` }) } @@ -465,9 +461,6 @@ export function RunFooterView(props: RunFooterViewProps) { expanded: `${activeTabs().length} subagent${activeTabs().length === 1 ? "" : "s"}`, }) } - if (foregroundSubagents() && backgroundShortcut()) { - items.push({ id: "background", key: backgroundShortcut(), label: "bg", expanded: "background" }) - } return items }) const commandHint = createMemo(() => { @@ -575,19 +568,6 @@ export function RunFooterView(props: RunFooterViewProps) { ], })) - Keymap.createLayer(() => ({ - enabled: active().type === "prompt" && route().type === "composer" && foregroundSubagents() && !!props.onBackground, - priority: 1, - commands: [ - { - id: "session.background", - title: "Background subagents", - group: "Session", - run: () => props.onBackground?.(), - }, - ], - })) - Keymap.createLayer(() => ({ enabled: active().type === "prompt" && route().type === "composer" && tabs().length > 0, commands: [ diff --git a/packages/tui/src/mini/footer.width.ts b/packages/tui/src/mini/footer.width.ts index 8d839ade69d..795ce3bc3ff 100644 --- a/packages/tui/src/mini/footer.width.ts +++ b/packages/tui/src/mini/footer.width.ts @@ -14,7 +14,6 @@ export type FooterStatuslineGroup = { | "escape" | "queued" | "subagents" - | "background" | "agent" | "model" | "context" @@ -29,7 +28,7 @@ export function footerStatuslinePolicy(input: { mono?: boolean status?: { text: string; expanded?: string } escape?: FooterAction - work: Array + work: Array model?: { name: string; variant?: string } agent?: string context?: { compact: string; full: string } @@ -69,7 +68,6 @@ export function footerStatuslinePolicy(input: { "escape", "queued", "subagents", - "background", "agent", "model", "context", diff --git a/packages/tui/src/mini/runtime.lifecycle.ts b/packages/tui/src/mini/runtime.lifecycle.ts index 934766699fd..880ca083076 100644 --- a/packages/tui/src/mini/runtime.lifecycle.ts +++ b/packages/tui/src/mini/runtime.lifecycle.ts @@ -77,7 +77,6 @@ export type LifecycleInput = { onModelSelect?: (model: NonNullable) => CycleResult | void | Promise onVariantSelect?: (variant: string | undefined) => CycleResult | void | Promise onInterrupt?: () => void - onBackground?: () => void onQueuedPromptAction?: (action: QueuedPromptAction, inboxID: string) => Promise onSubagentSelect?: (sessionID: string | undefined) => void onSubagentInterrupt?: (sessionID: string) => void @@ -249,7 +248,6 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise { if (closed || renderer.isDestroyed) { diff --git a/packages/tui/src/mini/runtime.ts b/packages/tui/src/mini/runtime.ts index a140271a541..2d1e4fdb767 100644 --- a/packages/tui/src/mini/runtime.ts +++ b/packages/tui/src/mini/runtime.ts @@ -383,14 +383,6 @@ async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDep ).catch(() => {}) return true }, - onBackground: () => { - if (!state.sessionID) { - return - } - - log?.write("send.background", { sessionID: state.sessionID }) - void state.sdk.session.background({ sessionID: state.sessionID }).catch(() => {}) - }, onQueuedPromptAction: async (action, inboxID) => { if (!state.sessionID) return log?.write(`send.pending.${action}`, { sessionID: state.sessionID, inboxID }) diff --git a/packages/tui/src/mini/stream-v2.subagent.ts b/packages/tui/src/mini/stream-v2.subagent.ts index 0feddffdc94..0f290f27aad 100644 --- a/packages/tui/src/mini/stream-v2.subagent.ts +++ b/packages/tui/src/mini/stream-v2.subagent.ts @@ -12,9 +12,7 @@ // and reconnect, then continue from live deltas using the same // projected-prefix dedup the parent transport uses. // -// Per-child interruption uses `v2.session.interrupt(childID)`. Per-child -// backgrounding is intentionally absent: subagent jobs block the parent -// session, so only whole-session `v2.session.background(parentID)` exists. +// Per-child interruption uses `v2.session.interrupt(childID)`. import type { EventSubscribeOutput, OpenCodeClient, @@ -106,7 +104,6 @@ type ChildState = { label: string description: string status: FooterSubagentTab["status"] - background: boolean title?: string lastUpdatedAt: number frames: Frame[] @@ -195,7 +192,6 @@ function tab(child: ChildState): FooterSubagentTab { label: child.label, description: child.description || child.title || "", status: child.status, - background: child.background ? true : undefined, title: child.title, } } @@ -233,7 +229,6 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac label: FALLBACK_LABEL, description: "", status: "running", - background: false, lastUpdatedAt: 0, frames: [], fragments: createFragmentReconciler(), @@ -286,7 +281,6 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac if (agent) child.label = Locale.titlecase(agent) const description = text(meta.description) if (description) child.description = description - if (meta.background === true) child.background = true } const userFrame = (child: ChildState, messageID: string, prompt: Pick) => { @@ -943,7 +937,6 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac const child = admitChild(found.sessionID) if (!child) return applyMeta(child, record(tool.state.input)) - if (tool.state.status === "completed" && found.running) child.background = true if (child.status === "running") { const running = found.running && (!active || found.sessionID in active) child.status = running ? "running" : "completed" @@ -989,10 +982,7 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac const child = admitChild(found.sessionID) if (!child) return applyMeta(child, pending) - if (event.type === "session.tool.success" && found.running) { - child.background = true - child.status = "running" - } + if (event.type === "session.tool.success" && found.running) child.status = "running" if (event.type === "session.tool.success" && !found.running && child.status === "running") child.status = "completed" touch(child, event.created) diff --git a/packages/tui/src/mini/types.ts b/packages/tui/src/mini/types.ts index f93e9e5579c..4519a2a9140 100644 --- a/packages/tui/src/mini/types.ts +++ b/packages/tui/src/mini/types.ts @@ -316,7 +316,6 @@ export type FooterSubagentTab = { label: string description: string status: "running" | "completed" | "cancelled" | "error" - background?: boolean title?: string } diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index fb3573801bc..b8b4262ba88 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1908,8 +1908,7 @@ function BackgroundToolHint(props: { messages: SessionMessageInfo[] }) { ) const part = current?.content.find((part): part is SessionMessageAssistantTool => { if (part.type !== "tool" || part.state.status !== "running") return false - const name = canonicalToolName(part.name) - return name === "shell" || name === "subagent" + return canonicalToolName(part.name) === "shell" }) if (!current || !part) return return { key: `${current.id}:${part.id}`, started: part.time.ran ?? part.time.created } @@ -3340,11 +3339,6 @@ function Subagent(props: ToolProps) { const id = sessionID() if (id) navigate({ type: "session", sessionID: id }) }} - status={ - isBackgroundSubagent(props.metadata, props.part.state.status) ? ( - Background - ) : undefined - } > {`${continuation() ? "Continue subagent" : `${Locale.titlecase(stringValue(props.input.agent) ?? stringValue(props.input.subagent_type) ?? "General")} Subagent`} — ${description() ?? "Subagent"}${model() ? ` · ${model()}` : ""}`} @@ -3364,13 +3358,6 @@ export function subagentModelLabel( return `${name ?? reference}${variant ? ` (${variant})` : ""}` } -export function isBackgroundSubagent( - metadata: Record, - status: SessionMessageAssistantTool["state"]["status"], -) { - return status === "completed" && metadata.status === "running" -} - export { executeCallSummary } function ExecuteCallView(props: { call: Accessor }) { diff --git a/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx b/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx index bf2c303bf7f..661e9c4a13b 100644 --- a/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx +++ b/packages/tui/test/cli/tui/inline-tool-wrap-snapshot.test.tsx @@ -5,7 +5,6 @@ import { InlineToolRow, executeCallSummary, genericToolSummary, - isBackgroundSubagent, parseApplyPatchFiles, parseDiagnostics, parseQuestionAnswers, @@ -231,13 +230,6 @@ describe("TUI inline tool wrapping", () => { ).toEqual([{ message: "valid", range: { start: { line: 2, character: 3 } } }]) }) - test("labels only detached or async subagents as background", () => { - expect(isBackgroundSubagent({ status: "running" }, "running")).toBeFalse() - expect(isBackgroundSubagent({ status: "running" }, "completed")).toBeTrue() - expect(isBackgroundSubagent({ status: "running" }, "error")).toBeFalse() - expect(isBackgroundSubagent({ status: "completed" }, "completed")).toBeFalse() - }) - test("labels only explicit subagent model overrides", () => { const models = [{ providerID: "anthropic", id: "claude-opus-4-1", name: "Claude Opus 4.1" }] expect(subagentModelLabel(undefined, models)).toBeUndefined() diff --git a/packages/tui/test/mini/footer.view.test.tsx b/packages/tui/test/mini/footer.view.test.tsx index 6eb1381db41..6609d4eee24 100644 --- a/packages/tui/test/mini/footer.view.test.tsx +++ b/packages/tui/test/mini/footer.view.test.tsx @@ -1760,7 +1760,7 @@ test("direct footer counts queued and steering work while running", async () => const frame = app.captureCharFrame() const transparent = RGBA.fromValues(0, 0, 0, 0).toInts() const statusline = footerStatusline(app.renderer.root) - expect(frame).toContain("esc stop · ctrl+x q 2 pending · ↓ 1 subagent · ctrl+b background · Build") + expect(frame).toContain("ctrl+x q 2 pending · ↓ 1 subagent · Build") expect(frame).toMatch(/opencode · ctrl\+p menu *$/m) expect(frame).not.toContain("1 agent") expect(statusline.backgroundColor.toInts()).toEqual(transparent) @@ -1990,7 +1990,6 @@ test.each(["ctrl+g", "none"])("context actions use only configured bindings (%s) "session.interrupt": "ctrl+i", "session.queued_prompts": queued, "session.child.first": "ctrl+j", - "session.background": "none", "command.palette.show": "ctrl+y", }, }), @@ -2034,7 +2033,7 @@ test("identity and context precede the provider and a non-fitting provider block } }) -test("direct footer keeps compact work, model detail, and context ahead of cost and rich labels", async () => { +test("direct footer keeps work, model detail, context, and cost in priority order", async () => { const app = await renderFooter({ currentAgent: "Plan", subagents: { @@ -2055,7 +2054,7 @@ test("direct footer keeps compact work, model detail, and context ahead of cost await app.renderOnce() const statusline = footerStatusline(app.renderer.root) expect(app.captureCharFrame().split("\n")[statusline.y].trimEnd()).toBe( - "\u25aa esc stop · ↓ 1 sub · ctrl+b bg · Plan · a-model-name-long-enough… · 16% ctx", + "\u25aa esc stop · ↓ 1 sub · Plan · a-model-name-long-enough… · 159.6K (16%) · $4.23", ) } finally { app.cleanup() @@ -2186,7 +2185,7 @@ test("direct footer reserves the working indicator beside complete status text", } }) -test("direct footer always offers backgrounding for a foreground subagent", async () => { +test("direct footer never offers backgrounding for a subagent", async () => { const app = await renderFooter({ subagents: { tabs: [subagent({ sessionID: "s-1", label: "Explore", description: "Inspect auth flow" })], @@ -2201,7 +2200,8 @@ test("direct footer always offers backgrounding for a foreground subagent", asyn await app.renderOnce() const frame = app.captureCharFrame() - expect(frame).toContain("↓ 1 subagent · ctrl+b background · Build · gpt-5 · ctrl+p menu") + expect(frame).toContain("↓ 1 subagent · Build · gpt-5 · ctrl+p menu") + expect(frame).not.toContain("ctrl+b") expect(frame).not.toContain("queued") } finally { app.cleanup() diff --git a/packages/tui/test/mini/footer.width.test.ts b/packages/tui/test/mini/footer.width.test.ts index 59795d8563f..d761d63a9ba 100644 --- a/packages/tui/test/mini/footer.width.test.ts +++ b/packages/tui/test/mini/footer.width.test.ts @@ -31,7 +31,6 @@ describe("run footer width", () => { work: [ { id: "queued", key: "ctrl+x q", label: "12 queued" }, { id: "subagents", key: mono ? "down" : "\u2193", label: "2 sub", expanded: "2 subagents" }, - { id: "background", key: "ctrl+b", label: "bg", expanded: "background" }, ], }, { work: [], status: { text: "Shell" }, escape: { key: "esc", label: "normal" }, context: screenshot.context }, diff --git a/packages/tui/test/mini/stream-v2.transport.test.ts b/packages/tui/test/mini/stream-v2.transport.test.ts index 77abc864921..79b3f4f4775 100644 --- a/packages/tui/test/mini/stream-v2.transport.test.ts +++ b/packages/tui/test/mini/stream-v2.transport.test.ts @@ -3789,7 +3789,6 @@ describe("V2 mini transport", () => { label: "Explore", description: "Inspect progress", status: "running", - background: undefined, }, ]) @@ -4559,7 +4558,7 @@ describe("V2 mini transport", () => { model: { providerID: "test", id: "model" }, }, }) - // Parent's background subagent tool.success adopts the child mid-discovery. + // Parent's subagent tool.success adopts the child mid-discovery. events.push({ id: "evt_parent_input", created: 0, @@ -4581,7 +4580,7 @@ describe("V2 mini transport", () => { sessionID: "ses_1", assistantMessageID: "msg_parent_a", id: "call_sub", - input: { agent: "explore", description: "Find things", prompt: "go", background: true }, + input: { agent: "explore", description: "Find things", prompt: "go" }, executed: true, }, }) diff --git a/services/site/src/docs/content/agents.mdx b/services/site/src/docs/content/agents.mdx index 5fe770b51ce..6538c3401f5 100644 --- a/services/site/src/docs/content/agents.mdx +++ b/services/site/src/docs/content/agents.mdx @@ -115,7 +115,10 @@ Set `mode` according to where the agent should run: | `subagent` | Runs only in a child session through the `subagent` tool. | | `all` | Runs either as a primary agent or a subagent. | -Subagents run with fresh context in foreground or background child sessions. The parent agent's `subagent` permissions control which agents it may launch; the child uses its own configured permissions. +Subagents run with fresh context in their own child sessions. They always run in +the background: the parent receives a report when a child goes idle, and again +after each later round of work. The parent agent's `subagent` permissions control +which agents it may launch; the child uses its own configured permissions. ```jsonc { diff --git a/services/site/src/docs/content/build/plugins/gui/index.mdx b/services/site/src/docs/content/build/plugins/gui/index.mdx index 4adbbfacd92..e6baf86e1e1 100644 --- a/services/site/src/docs/content/build/plugins/gui/index.mdx +++ b/services/site/src/docs/content/build/plugins/gui/index.mdx @@ -1716,7 +1716,7 @@ if (session && file) void file.sync("README.md") - `directory` is the session's workspace directory, and `local` is `true` when that is the project root. - `listedProject` is the sidebar project the session belongs to. - `visit` is a new object each time the session is routed. -- `background` lists the shell commands and subagents the session moved to the background. +- `background` lists the session's running subagents and shell commands. - `ctx.sessions.list()` returns the sessions of the open shell tabs. - The screen's `file` reads the workspace's files, and `comment` holds the line comments of the next prompt. `composer` is the next prompt: its text, attached parts, and model; see diff --git a/services/site/src/docs/content/tools.mdx b/services/site/src/docs/content/tools.mdx index 2277ba6faa6..60561ccd107 100644 --- a/services/site/src/docs/content/tools.mdx +++ b/services/site/src/docs/content/tools.mdx @@ -215,10 +215,13 @@ ID, a short `description`, and a complete `prompt`. Ask the explore subagent to map the authentication flow and return the key files. ``` -Foreground calls wait for the result. `background: true` returns immediately -and notifies the parent when the child finishes. Pass the returned `sessionID` -to continue that same child conversation. Only subagent-mode agents can be -used, and the default nesting depth is one. +Subagents always run in the background. The call returns immediately with a +`sessionID`, and the parent receives a `` message when the child goes +idle, and again after each later round of work, so it can keep working or end +its turn without waiting. Pass the returned `sessionID` to continue that same +child conversation; a follow-up to a running child joins its current run. Set +`notify: false` on a new subagent to stop its idle reports. Only subagent-mode +agents can be used, and the default nesting depth is one. Permission: `subagent` with the selected agent ID as its resource.