A local-first multi-agent app development platform, built on PenguinHarness
feat: move a running tool call to the background from its card (#691)
Yaowei Zheng367ab0848785
diff --git a/changelog/unreleased/2026-09-11-send-tool-to-background.md b/changelog/unreleased/2026-09-11-send-tool-to-background.mdnew file mode 100644index 00000000..9ed30ba4--- /dev/null+++ b/changelog/unreleased/2026-09-11-send-tool-to-background.md@@ -0,0 +1,36 @@+# A running tool call can be moved to the background from its card++- **Date:** 2026-09-11+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#691](https://github.com/Prism-Shadow/penguin-harness/pull/691)++[中文版](2026-09-11-send-tool-to-background.zh.md)++While an `exec_command` or `run_subagent` call is executing, its row in the conversation now+carries a "Send to background" action that hands the work back as a background task: the call+closes with a `process_id` / `subagent_id`, nothing is killed, and the turn continues instead of+waiting out the command. The completion arrives later as the usual background-task notice, the+way a `run_in_background` launch reports, and the detached process shows up in the session's+process list with its Stop and Remove actions.++## Details++- Core gives each executing tool call a detach channel of its own, separate from the run's abort+ signal, and `Session.detachToolCall(toolCallId)` fires it. A detach is not an interruption: the+ call ends `completed` with a handle and no interruption marker, and only the two tools with a+ background form observe it — every other tool behaves exactly as before.+- A detached `run_subagent` child inherits the launching call's approval sink and live message+ tap, so it keeps running and streaming after the turn that started it has ended.+- New route `POST /api/sessions/:sessionId/tool-calls/:toolCallId/background` — 204 on success,+ 404 `tool_call_not_found` when nothing with that id is executing, 409 `tool_not_detachable`+ when the tool has no background form.+- The action is inline text on the row, styled as a link and sized like the rest of the row, so+ a row carrying it measures exactly like one that does not. It is offered only while the call+ is executing, only on a main-session card, and not on a call already launched with+ `run_in_background` — that one's work is already parked.+- A call whose work went to the background is marked `[Background]` right of its duration, in+ the row's own mono type and the same bracketed shape the row uses for an outcome that needs a+ word. It is read from the note the call returned, so it survives a reload.+- The chat header's background-task chip keeps its glyph and its count and moves from the+ live-status green to the muted tone, so it reads the same as the session row's mark.diff --git a/changelog/unreleased/2026-09-11-send-tool-to-background.zh.md b/changelog/unreleased/2026-09-11-send-tool-to-background.zh.mdnew file mode 100644index 00000000..6bc50361--- /dev/null+++ b/changelog/unreleased/2026-09-11-send-tool-to-background.zh.md@@ -0,0 +1,29 @@+# 运行中的工具调用可以从卡片上转为后台任务++- **Date:** 2026-09-11+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#691](https://github.com/Prism-Shadow/penguin-harness/pull/691)++[English](2026-09-11-send-tool-to-background.md)++`exec_command` 与 `run_subagent` 正在执行时,对话里的工具调用行新增一个「转入后台执行」动作,点击即把这+次调用的工作交还为后台任务:调用带着 `process_id` / `subagent_id` 正常结束,进程不会被杀掉,主对话不必等+命令跑完就继续进行。任务完成后仍以一贯的后台任务通知送回,与 `run_in_background` 启动的任务一致;转入后台的进程+也会出现在 Session 的进程列表里,带有原有的停止与移除操作。++## 细节++- 核心为每个执行中的工具调用单独提供一条 detach 通道,与本次运行的中断信号相互独立,由+ `Session.detachToolCall(toolCallId)` 触发。转为后台不是中断:调用以 `completed` 结束、带回句柄、不附+ 中断标记;只有具备后台形态的这两个工具会响应它,其余工具行为完全不变。+- 转为后台的 `run_subagent` 子会话会继承本次调用的审批出口与实时消息通道,因此在发起它的这一轮结束后+ 仍能继续运行并持续推送消息。+- 新增路由 `POST /api/sessions/:sessionId/tool-calls/:toolCallId/background`——成功返回 204,该 id 没有+ 正在执行的调用时返回 404 `tool_call_not_found`,工具没有后台形态时返回 409 `tool_not_detachable`。+- 该动作是行内文字(链接样式,字号与行内其余文字一致),因此带它的行与不带它的行高度完全相同。它只在调用+ 执行中、且只在主会话的卡片上出现;已经用 `run_in_background` 启动的调用不出现——那次调用的工作本来就已+ 经在后台。+- 工作已转入后台的调用,在时长右侧标出 `[后台任务]`:与行内其余文字同为等宽字体,用的也是该行标注结果+ 时一贯的方括号写法。该标记读自调用返回的说明文字,因此刷新页面后依然保留。+- 对话头部的后台任务标记保留原有图标与计数,配色由活动状态的绿色改为弱化灰,与会话列表行上的标记一致。diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.tsindex 43abc3d6..74431a0f 100644--- a/packages/core/src/environment/environment.ts+++ b/packages/core/src/environment/environment.ts@@ -44,6 +44,7 @@ import type {ThinkingLevelName,ToolConfig,ToolDefinition,+ ToolDetachResult,ToolExecutionRequest,ToolPermission,} from "../interfaces/index.js";@@ -469,6 +470,30 @@ export class Environment implements EnvironmentInterface {return this.commandSessions.kill(processId);}+ /**+ * Detach channels of the calls currently executing, keyed by tool_call_id: the only handle+ * a host has on one call. An entry lives exactly as long as its call — `executeTool`+ * registers one on entry and deletes it in its finalization — so an id that is not here is+ * a call that is not running. `detachable` is the tool's own declaration; a call whose tool+ * has no background form still gets an entry, so the registry can tell "nothing is running"+ * apart from "that tool cannot be detached".+ */+ private readonly inFlight = new Map<string, { detach: AbortController; detachable: boolean }>();++ /**+ * Asks one executing call to continue as a background task (see+ * EnvironmentInterface.detachToolCall). Firing the controller is the whole action: the tool+ * observes it, registers its work and returns a handle. Idempotent — a second click on a+ * call still winding down fires an already-aborted controller and changes nothing.+ */+ detachToolCall(toolCallId: string): ToolDetachResult {+ const entry = this.inFlight.get(toolCallId);+ if (!entry) return "not_running";+ if (!entry.detachable) return "not_detachable";+ entry.detach.abort();+ return "detached";+ }+/*** Lists tools available to the current Session, for context_engine to initialize GenerativeModel.* Only lists tools that have been assembled (i.e. supported by the registry) — tool names@@ -569,6 +594,11 @@ export class Environment implements EnvironmentInterface {if (signal?.aborted) ac.abort();const onAbort = (): void => ac.abort();signal?.addEventListener("abort", onAbort, { once: true });+ // Per-call detach channel, minted here so something outside the engine can reach ONE call+ // (see detachToolCall). Kept separate from `ac`: that signal means "stop", this one means+ // "hand your work back and let the turn close".+ const detachCtrl = new AbortController();+ this.inFlight.set(toolCallId, { detach: detachCtrl, detachable: tool.detachable === true });let timedOut = false;const timer =timeoutMs > 0@@ -609,6 +639,7 @@ export class Environment implements EnvironmentInterface {workspaceDir: this.workspaceDir,toolCallId,signal: ac.signal,+ detachSignal: detachCtrl.signal,// Pass through the parent's approve callback (run_subagent uses it so the child Session// inherits the parent's approval mode; other tools ignore it)....(request.approve ? { approve: request.approve } : {}),@@ -724,6 +755,9 @@ export class Environment implements EnvironmentInterface {} finally {if (timer) clearTimeout(timer);signal?.removeEventListener("abort", onAbort);+ // The call is over: a detach arriving from here on has nothing to act on and must+ // answer "not running" rather than firing a controller nobody is listening to.+ this.inFlight.delete(toolCallId);}// Uniform finalization. Content basis = the tool's self-produced full message (fallbackdiff --git a/packages/core/src/environment/tools/background/detach.ts b/packages/core/src/environment/tools/background/detach.tsnew file mode 100644index 00000000..b897bd1a--- /dev/null+++ b/packages/core/src/environment/tools/background/detach.ts@@ -0,0 +1,19 @@+/**+ * The collect-window signal shared by the two tools that can hand a running call back as a+ * background task (`exec_command`, `run_subagent`).+ */++/**+ * Union of the two channels that end a collect window: an interruption (`signal`) and a+ * per-call detach request (`detachSignal`). Collecting stops on either, but what each MEANS+ * is different — an interruption ends the call, a detach promotes it — so the caller reads+ * the two signals separately once the window is over and decides there.+ */+export function collectUntil(+ signal?: AbortSignal,+ detachSignal?: AbortSignal,+): AbortSignal | undefined {+ if (!signal) return detachSignal;+ if (!detachSignal) return signal;+ return AbortSignal.any([signal, detachSignal]);+}diff --git a/packages/core/src/environment/tools/background/index.ts b/packages/core/src/environment/tools/background/index.tsindex 6bcb6d3e..ce2788c9 100644--- a/packages/core/src/environment/tools/background/index.ts+++ b/packages/core/src/environment/tools/background/index.ts@@ -4,5 +4,6 @@export { BackgroundRegistry } from "./registry.js";export type { BackgroundTask } from "./registry.js";export { clampYield, tailForReport, reportLabel } from "./limits.js";+export { collectUntil } from "./detach.js";export { WakeSignal } from "./wake-signal.js";export { CappedTextBuffer } from "./capped-buffer.js";diff --git a/packages/core/src/environment/tools/exec-command.ts b/packages/core/src/environment/tools/exec-command.tsindex a2b6618f..d31b01ac 100644--- a/packages/core/src/environment/tools/exec-command.ts+++ b/packages/core/src/environment/tools/exec-command.ts@@ -21,11 +21,12 @@import path from "node:path";import { partialToolCallOutput } from "../../omnimessage/index.js";import type { OmniMessage } from "../../omnimessage/index.js";+import { DETACHED_TOOL_NOTE_PREFIX } from "../../interfaces/index.js";import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces/index.js";import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";import { DEFAULT_EXEC_YIELD_MS, isStopSignal, resultForExit } from "./command/index.js";import type { ManagedSession } from "./command/index.js";-import { clampYield, reportLabel, tailForReport } from "./background/index.js";+import { clampYield, collectUntil, reportLabel, tailForReport } from "./background/index.js";import { describeArgumentError, stringArgument } from "./tool-arguments.js";/** Tool name constant (used only inside this tool module, not exposed to Environment). */@@ -66,11 +67,12 @@ export function createExecCommandTool(return {name: definition.name,definition,+ detachable: true,async *execute(args: Record<string, unknown>,ctx: ToolExecutionContext,): AsyncGenerator<OmniMessage, ToolResult | void> {- const { toolCallId, signal } = ctx;+ const { toolCallId, signal, detachSignal } = ctx;const delta = (output: string): OmniMessage =>partialToolCallOutput({ eventType: "delta", output, toolCallId });@@ -134,18 +136,36 @@ export function createExecCommandTool(// On interruption, kill the whole process group (background children included) to// avoid orphans; once the process moves to background this listener is removed in finally.+ // Deliberately listens to `signal` only: a detach leaves the process running — it is the+ // opposite request.const onAbort = (): void => session.kill();let registered = false;signal?.addEventListener("abort", onAbort, { once: true });try {- for await (const chunk of session.collect(yieldMs, signal)) yield delta(chunk);+ // Either an interruption or a detach ends collection; which one fired is read below.+ for await (const chunk of session.collect(yieldMs, collectUntil(signal, detachSignal))) {+ yield delta(chunk);+ }if (signal?.aborted) return { stopReason: "aborted" };if (session.running) {- // Still running at the deadline: register as a background process, returning- // process_id so input_command can continue accessing it.+ // Still running: register as a background process, returning process_id so+ // input_command can continue accessing it. Whatever was collected up to this point+ // has already been yielded, so it stays in this call's output.const id = manager.register(session);registered = true;+ if (detachSignal?.aborted) {+ // Detached by the user rather than by the yield deadline: the model never chose+ // to poll this one, so arm the completion report the way a run_in_background+ // launch does — otherwise the command would finish with nobody told.+ armCommandDoneReport(session, id, services);+ return {+ stopReason: "completed",+ note:+ `${DETACHED_TOOL_NOTE_PREFIX} with process_id ${id}; its completion will arrive ` ++ `as a user message — no need to poll. Use input_command to interact (kill: true stops it)]`,+ };+ }return {stopReason: "completed",note: `[process running with process_id ${id}; use input_command to send input or poll for output]`,diff --git a/packages/core/src/environment/tools/run-subagent.ts b/packages/core/src/environment/tools/run-subagent.tsindex da945386..7105c39c 100644--- a/packages/core/src/environment/tools/run-subagent.ts+++ b/packages/core/src/environment/tools/run-subagent.ts@@ -29,7 +29,7 @@*/import { partialToolCallOutput, userText } from "../../omnimessage/index.js";import type { OmniMessage } from "../../omnimessage/index.js";-import { SUBAGENT_THINKING_LEVELS } from "../../interfaces/index.js";+import { DETACHED_TOOL_NOTE_PREFIX, SUBAGENT_THINKING_LEVELS } from "../../interfaces/index.js";import type {EnvironmentServices,ThinkingLevelName,@@ -42,7 +42,7 @@ import {resultForSubagentExit,} from "./subagent/index.js";import { collectWindow } from "./subagent/collect.js";-import { clampYield, reportLabel, tailForReport } from "./background/index.js";+import { clampYield, collectUntil, reportLabel, tailForReport } from "./background/index.js";import { describeArgumentError } from "./tool-arguments.js";/** Tool name constant (used only within this tool module, never exposed to Environment). */@@ -64,11 +64,12 @@ export function createSubagentTool(return {name: SUBAGENT_NAME,definition,+ detachable: true,async *execute(args: Record<string, unknown>,ctx: ToolExecutionContext,): AsyncGenerator<OmniMessage, ToolResult | void> {- const { toolCallId, signal, approve } = ctx;+ const { toolCallId, signal, approve, detachSignal } = ctx;const fail = function* (msg: string): Generator<OmniMessage> {yield partialToolCallOutput({ eventType: "delta", output: msg, toolCallId });};@@ -192,24 +193,49 @@ export function createSubagentTool(// An interruption within the startup window kills the child session (consistent with// exec_command); once switched to background, this listener is removed in `finally`.+ // A detach is not on this listener: it leaves the child running, which is the point.const onAbort = (): void => session.kill();let registered = false;signal?.addEventListener("abort", onAbort, { once: true });+ const windowSignal = collectUntil(signal, detachSignal);try {session.startRun([userText(prompt, "parent_agent")]);yield* collectWindow(session, {yieldMs,toolCallId,- ...(signal ? { signal } : {}),+ ...(windowSignal ? { signal: windowSignal } : {}),...(approve ? { approve } : {}),});if (signal?.aborted) return { stopReason: "aborted" };if (session.running) {- // Still running once the window expires: register as a background session, returning- // subagent_id for input_subagent to continue accessing it.+ // Still running: register as a background session, returning subagent_id for+ // input_subagent to continue accessing it.const id = manager.register(session);registered = true;+ if (detachSignal?.aborted) {+ // Detached by the user mid-window. The child now outlives this call, so it needs+ // everything the collect window was giving it: a standing approval sink (without+ // one its next read-write tool parks at the approval queue forever, since no+ // window will ever attach another) and a live message tap, so it keeps streaming+ // to the frontend past this turn's end. Its completion is reported like a+ // run_in_background launch's — nobody is going to poll for it.+ armSubagentDoneReport(session, id, prompt, services);+ if (approve) session.setPersistentApprovalSink(approve);+ const forward = services?.backgroundForward;+ if (forward) session.setMessageTap(forward);+ // No approval hint here, exactly as on a run_in_background launch: the standing+ // sink just attached carries a queued request to the user itself, so "poll to+ // review" would send the model after work it is not doing — the deadline+ // promotion below keeps the hint because it has no such sink.+ return {+ stopReason: "completed",+ note:+ `${DETACHED_TOOL_NOTE_PREFIX} with subagent_id ${id}; its completion will arrive ` ++ `as a user message — no need to poll. Use input_subagent to interact ` ++ `(abort: true stops its current run)]`,+ };+ }return {stopReason: "completed",note:diff --git a/packages/core/src/environment/tools/types.ts b/packages/core/src/environment/tools/types.tsindex c14df65a..900e6235 100644--- a/packages/core/src/environment/tools/types.ts+++ b/packages/core/src/environment/tools/types.ts@@ -21,6 +21,15 @@ export interface ToolExecutionContext {toolCallId: string;/** Abort signal; the tool should close out and return as soon as possible once it fires. */signal?: AbortSignal;+ /**+ * Per-call detach request: the host asked for THIS call to continue as a background task so+ * the conversation can move on. Deliberately a channel of its own rather than a second+ * meaning for `signal`: Environment classifies any `signal.aborted` as `aborted` and appends+ * the interruption note, and a detached call is not interrupted — it hands back a registry+ * handle and its work keeps running. A tool that ignores this field behaves exactly as it+ * did before; only tools with a background form (exec_command, run_subagent) observe it.+ */+ detachSignal?: AbortSignal;/** The parent Agent's approval callback; run_subagent passes it through to the child Session so it inherits the parent's approval mode (unused by most tools). */approve?: ApproveFn;}@@ -71,6 +80,13 @@ export interface BuiltinTool {name: string;/** Tool definition handed to the LLM (including description / parameters / permission / maxOutputLength). */definition: ToolDefinitionConfig;+ /**+ * Whether this tool can hand a running call back as a background task when+ * `ctx.detachSignal` fires (it registers the work and returns a handle instead of ending+ * it). Missing = no background form: the detach channel is never armed for the call, and+ * `Environment.detachToolCall` answers `not_detachable`.+ */+ detachable?: boolean;/** Executes one tool call: args is the already-parsed argument object, ctx is the runtime context. */execute(args: Record<string, unknown>,diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.tsindex d1c5ded8..1eb6b5bd 100644--- a/packages/core/src/interfaces/environment.ts+++ b/packages/core/src/interfaces/environment.ts@@ -386,6 +386,24 @@ export interface ToolExecutionRequest {approve?: ApproveFn;}+/**+ * Outcome of a detach request (`EnvironmentInterface.detachToolCall`):+ * - `detached` — the call was asked to hand its work back as a background task;+ * - `not_running` — no call with that id is executing right now (unknown, or already finished);+ * - `not_detachable` — the call is running, but its tool has no background form.+ * The three are separate because a host answers them differently — the last one is a+ * permanent property of the tool, while the first two describe a moment.+ */+export type ToolDetachResult = "detached" | "not_running" | "not_detachable";++/**+ * The opening phrase of the note a detached call returns. Shared because a render layer has+ * to recognize a detached call from the stored output alone — the click that detached it is+ * not in the Trace, and a reloaded page has nothing else to go on — so the sentence the tool+ * writes and the string that matches it must be one value.+ */+export const DETACHED_TOOL_NOTE_PREFIX = "[moved to the background by the user";+/*** One background command process owned by the environment (an exec_command promoted past* its yield window): the registry handle plus display metadata for a host UI's process@@ -462,6 +480,14 @@ export interface EnvironmentInterface {listBackgroundCommands?(): BackgroundCommandInfo[];/** Kills one background command process by id (whole process group); false when the id is unknown. Optional, like listBackgroundCommands. */killBackgroundCommand?(processId: string): boolean;+ /**+ * Asks one EXECUTING tool call to hand its work back as a background task, so the turn can+ * close and the conversation carry on (the Web App's per-card button). Addressed by+ * tool_call_id, the only handle a host has on a single call. Not an abort: the call ends+ * `completed` with a registry handle, nothing is killed, and the work's completion arrives+ * later as the usual background report. Optional, like listBackgroundCommands.+ */+ detachToolCall?(toolCallId: string): ToolDetachResult;/*** Whether a background subagent session is mid-round. Hosts pin a Session's runtime entry* on it: a `run_in_background` child outlives the call that launched it, and evicting thediff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex c37fb65f..f6d3ca82 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -43,6 +43,7 @@ import type {EnvironmentInterface,LLMInterface,ThinkingLevelName,+ ToolDetachResult,ToolPermission,} from "./interfaces/index.js";import { vetoForToolCall, withCommandPolicy } from "./internal/command-policy.js";@@ -883,6 +884,16 @@ export class Session {return this.environment.killBackgroundCommand?.(processId) ?? false;}+ /**+ * Asks one of this Session's EXECUTING tool calls to continue as a background task, so the+ * turn can close (see EnvironmentInterface.detachToolCall). Not an abort: the call ends+ * `completed` with a registry handle and its work keeps running. An environment without the+ * method has no call to detach.+ */+ detachToolCall(toolCallId: string): ToolDetachResult {+ return this.environment.detachToolCall?.(toolCallId) ?? "not_running";+ }+/** Whether a background subagent of this Session is mid-round (see EnvironmentInterface.hasRunningBackgroundSubagents). */hasRunningBackgroundSubagents(): boolean {return this.environment.hasRunningBackgroundSubagents?.() ?? false;diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.tsindex 23f22a6a..3f1ed3c7 100644--- a/packages/core/test/background-execution.test.ts+++ b/packages/core/test/background-execution.test.ts@@ -1,8 +1,9 @@/*** Behavior tests for background execution: `run_in_background` on exec_command /- * run_subagent, the completion-report pipeline (Environment listener → Session notice- * queue → engine boundary delivery), input_command's kill termination, and the- * `sender` marking on user texts.+ * run_subagent, detaching a call that is already executing (the Web App's per-card button),+ * the completion-report pipeline (Environment listener → Session notice queue → engine+ * boundary delivery), input_command's kill termination, and the `sender` marking on user+ * texts.*/import { afterEach, describe, expect, it, vi } from "vitest";import { mkdtemp, rm } from "node:fs/promises";@@ -49,7 +50,9 @@ import type {SubagentRunner,ToolConfig,ToolDefinitionConfig,+ ToolDetachResult,} from "../src/interfaces/index.js";+import { DETACHED_TOOL_NOTE_PREFIX } from "../src/interfaces/index.js";import type { ToolExecutionContext } from "../src/environment/tools/types.js";// ---------------------------------------------------------------------------@@ -93,6 +96,37 @@ async function runTool(return { output: p.output ?? "", stopReason: p.stop_reason };}+/**+ * Runs a tool and detaches the call from outside the moment `when` holds against the output+ * seen so far — the Web App's button, fired while the call is still executing.+ */+async function runToolDetachedOn(+ env: Environment,+ name: string,+ args: Record<string, unknown>,+ when: (seen: string) => boolean,+): Promise<FinalOutput & { detach: ToolDetachResult | null; completeOutputs: number }> {+ const toolCallId = `call_${name}_detach`;+ let detach: ToolDetachResult | null = null;+ let seen = "";+ let completeOutputs = 0;+ let last: OmniMessage | null = null;+ for await (const msg of env.executeTool({+ toolCall: toolCall({ name, arguments: JSON.stringify(args), toolCallId }),+ })) {+ const p = msg.payload as { type?: string; output?: string };+ if (p.type === "tool_call_output") {+ completeOutputs += 1;+ last = msg;+ } else {+ seen += p.output ?? "";+ }+ if (detach === null && when(seen)) detach = env.detachToolCall(toolCallId);+ }+ const p = (last?.payload ?? {}) as { output?: string; stop_reason?: string };+ return { output: p.output ?? "", stopReason: p.stop_reason, detach, completeOutputs };+}+function extractProcessId(output: string): string {const m = output.match(/process_id (proc-[0-9a-f]+)/);expect(m, `expected a process_id in: ${JSON.stringify(output)}`).toBeTruthy();@@ -353,6 +387,78 @@ describe("exec_command run_in_background", () => {});});+// ---------------------------------------------------------------------------+// Detaching an executing call (the Web App's per-card button)+// ---------------------------------------------------------------------------++describe("detaching an executing tool call", () => {+ it("ends the call as completed with a process_id, kills nothing, and closes out exactly once", async () => {+ const { env } = await makeEnv();+ const res = await runToolDetachedOn(+ env,+ "exec_command",+ // A yield window far longer than the test: the promotion below can only be the detach.+ { cmd: "printf 'before\\n'; sleep 0.3; printf 'after\\n'; sleep 30", yield_time_ms: 60000 },+ (seen) => seen.includes("before"),+ );+ expect(res.detach).toBe("detached");+ // A detach is not an interruption: no aborted stop reason, no interruption marker.+ expect(res.stopReason).toBe("completed");+ expect(res.output).not.toContain("[interrupted");+ expect(res.output).toContain(DETACHED_TOOL_NOTE_PREFIX);+ // Exactly one complete tool_call_output, so the engine's loop closes normally.+ expect(res.completeOutputs).toBe(1);+ // Whatever had been collected stays in this call's output.+ expect(res.output).toContain("before");++ // The process was NOT killed: it is registered, running, and still producing output that+ // a later input_command poll picks up.+ const id = extractProcessId(res.output);+ expect(env.listBackgroundCommands().find((p) => p.processId === id)?.running).toBe(true);+ const polled = await runTool(env, "input_command", { process_id: id, yield_time_ms: 1500 });+ expect(polled.output).toContain("after");+ });++ it("reports the detached command's completion as a background task", async () => {+ const { env } = await makeEnv();+ const events: BackgroundTaskDoneEvent[] = [];+ env.setBackgroundTaskListener((e) => events.push(e));+ const res = await runToolDetachedOn(+ env,+ "exec_command",+ { cmd: "printf 'before\\n'; sleep 0.4; printf 'done\\n'; exit 0", yield_time_ms: 60000 },+ (seen) => seen.includes("before"),+ );+ const id = extractProcessId(res.output);+ await waitFor(() => events.length === 1);+ expect(events[0]).toMatchObject({ kind: "command", id, status: "completed" });+ expect(events[0]!.output).toContain("done");+ });++ it("answers not_running for an unknown or finished call, and not_detachable for a tool with no background form", async () => {+ const { env } = await makeEnv();+ expect(env.detachToolCall("call_nobody")).toBe("not_running");++ const launched = await runTool(env, "exec_command", {+ cmd: "printf 'poll me\\n'; sleep 30",+ run_in_background: true,+ });+ const id = extractProcessId(launched.output);+ // input_command only polls a process the registry already holds — there is nothing to+ // hand back, so the call is refused rather than silently ending early.+ const polled = await runToolDetachedOn(+ env,+ "input_command",+ { process_id: id, yield_time_ms: 1500 },+ (seen) => seen.includes("poll me"),+ );+ expect(polled.detach).toBe("not_detachable");+ expect(polled.stopReason).toBe("completed");+ // The call is over: its detach channel is gone with it.+ expect(env.detachToolCall("call_input_command_detach")).toBe("not_running");+ });+});+describe("background-state listener", () => {it("pings on a background launch, again when the process exits, and on a kill", async () => {const { env } = await makeEnv();@@ -699,6 +805,95 @@ describe("run_subagent run_in_background", () => {expect(events[0]!.status).toBe("completed");});+ it("a detached child keeps running, inherits the call's approval sink and message tap, and reports on settle", async () => {+ const manager = new SubagentSessionManager();+ cleanups.push(() => manager.dispose());+ const decisions: string[] = [];+ const gates = new Map<string, () => void>();+ const runner = runnerOf(async function* ({ prompt, approve }) {+ // Parked until the test releases it, so the detach lands mid-round.+ await new Promise<void>((r) => gates.set(prompt, r));+ const tc = withHop(toolCall({ name: "exec_command", arguments: "{}", toolCallId: "c1" }));+ decisions.push(await approve!(tc as OmniMessage<ToolCallPayload>));+ yield withHop(partialText("delta", "child answer"));+ yield withHop(assistantText("child answer"));+ });+ const events: BackgroundTaskDoneEvent[] = [];+ const tapped: OmniMessage[] = [];+ const services = {+ subagentRunner: runner,+ subagentSessions: manager,+ backgroundDone: (e: BackgroundTaskDoneEvent) => events.push(e),+ backgroundForward: (m: OmniMessage) => tapped.push(m),+ };+ const tool = createSubagentTool(SUB_DEF, services);+ const approveSpy: ApproveFn = async () => "allow";+ const detach = new AbortController();+ const timer = setTimeout(() => detach.abort(), 50);+ const res = await drive(+ tool,+ // A yield window far longer than the test: the promotion can only be the detach.+ { prompt: "long job", yield_time_ms: 60000 },+ { ...CTX, approve: approveSpy, detachSignal: detach.signal },+ );+ clearTimeout(timer);+ // Not an interruption: the call completes with a handle, and the child is still alive.+ expect(res.stopReason).toBe("completed");+ expect(res.note).toContain(DETACHED_TOOL_NOTE_PREFIX);+ const id = extractSubagentId(res.note);+ expect(manager.hasRunning()).toBe(true);++ await waitFor(() => gates.has("long job"));+ gates.get("long job")!();+ // Without the standing sink handed over at detach time, this parks forever: no collect+ // window will ever attach another one.+ await waitFor(() => decisions.length === 1);+ expect(decisions[0]).toBe("allow");+ await waitFor(() => events.length === 1);+ expect(events[0]).toMatchObject({ kind: "subagent", id, status: "completed" });+ // And its messages keep streaming to the host past the launching turn's end.+ expect(tapped.some((m) => (m.payload as { type?: string }).type === "text")).toBe(true);+ });++ it("a detached child with a queued approval is not reported as something to poll for", async () => {+ const manager = new SubagentSessionManager();+ cleanups.push(() => manager.dispose());+ const decisions: string[] = [];+ const runner = runnerOf(async function* ({ approve }) {+ const tc = withHop(toolCall({ name: "exec_command", arguments: "{}", toolCallId: "c1" }));+ decisions.push(await approve!(tc as OmniMessage<ToolCallPayload>));+ yield withHop(assistantText("child answer"));+ });+ const tool = createSubagentTool(SUB_DEF, {+ subagentRunner: runner,+ subagentSessions: manager,+ });+ // The user has not answered yet, so the request is still queued when the detach lands:+ // pendingApprovals is 1 at the moment the note is written.+ let asked = false;+ let held = true;+ const approveSpy: ApproveFn = async () => {+ asked = true;+ await waitFor(() => !held);+ return "allow";+ };+ const detach = new AbortController();+ void waitFor(() => asked).then(() => detach.abort());+ const res = await drive(+ tool,+ { prompt: "long job", yield_time_ms: 60000 },+ { ...CTX, approve: approveSpy, detachSignal: detach.signal },+ );+ expect(res.note).toContain(DETACHED_TOOL_NOTE_PREFIX);+ // The standing sink attached at detach time carries that request to the user itself, so+ // the note must not send the model off to poll for it (a run_in_background launch says+ // nothing either; only the deadline promotion, which gets no standing sink, does).+ expect(res.note).not.toContain("poll to review");+ held = false;+ await waitFor(() => decisions.length === 1);+ expect(decisions[0]).toBe("allow");+ });+it("input_subagent fails on an id this conversation never allocated (nothing to resume)", async () => {const manager = new SubagentSessionManager();cleanups.push(() => manager.dispose());diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 97e6ddee..ca3b866d 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -278,6 +278,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| DELETE | /steer/:steerId | Recall an undelivered steering message (ids ride `task_state`'s `pendingSteering`): withdraws it from the queue → 200 with its original content `{text, images, files}` (files read back from the scratchpad as data URLs, their disk copies deleted) so the composer can restore it for editing; 409 `not_pending` once it was delivered to the model || DELETE | /follow-ups/:followUpId | Recall a queued follow-up task (ids ride `task_state`'s `pendingFollowUps`): removes it before it auto-starts → 200 with its original content `{text, images, files}` — every queued follow-up carries that content, however it was queued; 409 `follow_up_started` once it already started || POST | /approvals/:toolCallId | Approval decision: `{decision}` is `allow` or `deny` → 204 |+| POST | /tool-calls/:toolCallId/background | Hand one **executing** tool call back as a background task, so the turn can close and the conversation carries on: 204. The call ends `completed` with its `process_id` / `subagent_id`, nothing is killed, and the completion arrives later as the usual background-task notice. 404 `tool_call_not_found` when nothing with that id is executing (unknown, already finished, or the runtime is gone), 409 `tool_not_detachable` when the call is running but its tool has no background form (only `exec_command` and `run_subagent` have one) || POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle || POST | /retry-now | "Retry now" on the reconnect countdown: skips the in-progress backoff wait, firing the next retry immediately (attempt counter unchanged) → 200 `{skipped}` — `skipped:false` is the benign "no wait in progress" case, never an error || POST | /compact | Trigger context compaction: 202; 409 when there is nothing to compact, the reason carried by the code — `compaction_not_configured` (this Agent has no compaction configured), `nothing_to_compact` (the context has no completed conversation turn yet), `already_compacted` (nothing new was said since the last compaction). A Session resumed after a server restart reports availability from its Trace, so an existing conversation stays compactable without running a Task first |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 8f281949..27d78bb7 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -278,6 +278,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| DELETE | /steer/:steerId | 撤回一条尚未送达的插话(id 随 `task_state` 的 `pendingSteering` 下发):从队列中撤出 → 200,返回其原始内容 `{text, images, files}`(文件从 scratchpad 读回为 data URL,磁盘副本随之删除),供输入框恢复编辑;已送达模型则 409 `not_pending` || DELETE | /follow-ups/:followUpId | 撤回一条排队中的跟进消息(id 随 `task_state` 的 `pendingFollowUps` 下发):在自动发出前移除 → 200,返回其原始内容 `{text, images, files}`——排队中的跟进消息一律带有该内容,与其入队路径无关;已自动发出则 409 `follow_up_started` || POST | /approvals/:toolCallId | 审批决定:`{decision}` 取 `allow` 或 `deny` → 204 |+| POST | /tool-calls/:toolCallId/background | 把一个**正在执行**的工具调用交还为后台任务,使本轮可以结束、对话继续进行:204。调用带着 `process_id` / `subagent_id` 以 `completed` 结束,不杀任何进程,任务完成后仍以一贯的后台任务通知送回。该 id 没有正在执行的调用时(未知、已结束,或运行时已不存在)返回 404 `tool_call_not_found`;调用在运行但其工具没有后台形态时返回 409 `tool_not_detachable`(只有 `exec_command` 与 `run_subagent` 具备后台形态) || POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 || POST | /retry-now | 重连倒计时上的「立即重试」:跳过进行中的退避等待、立刻发起下一次重试(重试计数不变)→ 200 `{skipped}`——`skipped:false` 表示当前没有等待可跳过(良性空操作,非错误) || POST | /compact | 触发上下文压缩:202;无可压缩内容返回 409,具体原因由 code 承载——`compaction_not_configured`(该 Agent 没有配置压缩)、`nothing_to_compact`(当前上下文尚未完成一轮对话)、`already_compacted`(上次压缩后还没有新的对话)。服务重启后恢复的 Session 依据 Trace 判断可压缩性,因此已有对话无需先跑一次 Task 即可压缩 |diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.mdindex 71f3fd9f..98a7fe8d 100644--- a/packages/docs/content/tools.en.md+++ b/packages/docs/content/tools.en.md@@ -206,7 +206,7 @@ The Web App's subagents panel drives a selected child with the **same composer a### Background completion reports-A task launched with `run_in_background: true` reports its completion as a **user message injected by the harness** — the model does not need to poll. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).+A task launched with `run_in_background: true`, and a running call the user moved to the background from its row in the Web App, both report their completion as a **user message injected by the harness** — the model does not need to poll. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).Delivery: while a Task is running, the report rides the next turn boundary — a final reply already streaming does not lose it, the Task simply continues for one more turn to react. While the Session is idle, the hosting server starts a new Task carrying the report (SDK embedders subscribe via `Session.onBackgroundNotice` / `takeBackgroundNotices`, or get it prepended to the next run). A command terminated through `input_command`'s `kill` sends no report — that call's own result already carries the outcome — and neither does a subagent round ended by an explicit `abort` (the aborter reads the outcome directly). Reports cover **model-initiated rounds only** — the `run_in_background` launch and `input_subagent` follow-ups; a round the user starts from the subagents panel is their own conversation with the child and sends no report (its answer text stays in the model-facing buffer for the next poll).diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.mdindex 5da3404f..1bda0e13 100644--- a/packages/docs/content/tools.zh.md+++ b/packages/docs/content/tools.zh.md@@ -203,7 +203,7 @@ Web App 的智能体面板用**与主对话相同的 composer**(子会话变### 后台完成回报-以 `run_in_background: true` 启动的任务在结束时,以**Harness 注入的 user message** 回报完成——模型无需轮询。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。+以 `run_in_background: true` 启动的任务,以及用户在 Web App 的工具调用行上转入后台的调用,都在结束时以**Harness 注入的 user message** 回报完成——模型无需轮询。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。送达时机:Task 进行中时,回报搭乘下一个 turn 边界——即使最终回复已在流式输出,Task 也会为回应它再延续一个 turn。Session 空闲时,托管 Server 自动以该回报发起新 Task(SDK 嵌入方可订阅 `Session.onBackgroundNotice` / `takeBackgroundNotices`,否则回报并入下一次 run 的输入)。经 `input_command` 的 `kill` 终止的命令不发回报——该调用自身的结果已说明结局;被显式 `abort` 结束的子会话轮同样不发(打断者当场读到结局)。回报只覆盖**模型自己发起的轮**——`run_in_background` 的启动轮与 `input_subagent` 的续跑轮;用户从智能体面板发起的轮是用户与子会话自己的对话,不发回报(该轮答案文本留在模型面缓冲,下次轮询照常取得)。diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 76f49b1e..8bf6480b 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -1118,6 +1118,31 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {return c.body(null, 204);});+ // Hand one EXECUTING tool call back as a background task (the tool card's button), so the+ // turn can close and the conversation carry on. Addressed by tool_call_id, like the+ // approval route — the only handle the frontend has on a single call.+ //+ // 404 when nothing with that id is executing: unknown, already finished, or the runtime is+ // gone. 409 when the call is real and running but its tool has no background form — 404+ // would deny a call the user can see on screen, and 400 would blame a request that is+ // well-formed; the conflict is with what the tool IS, the same shape as refusing to remove+ // a running process.+ app.post("/:sessionId/tool-calls/:toolCallId/background", (c) => {+ const row = resolveSession(c);+ const result = deps.manager.detachToolCall(row.sessionId, pathParam(c, "toolCallId"));+ if (result === "not_detachable") {+ throw new HttpError(+ 409,+ "tool_not_detachable",+ "This tool has no background form; it cannot be moved to the background.",+ );+ }+ if (result === "not_running") {+ throw new HttpError(404, "tool_call_not_found", "This tool call is no longer running.");+ }+ return c.body(null, 204);+ });+app.post("/:sessionId/abort", (c) => {const row = resolveSession(c);const aborted = deps.manager.abortTask(row.sessionId);diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 6baa8649..bdf26055 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -55,6 +55,7 @@ import type {SubagentMessageOutcome,TextPayload,ThinkingLevelName,+ ToolDetachResult,} from "@prismshadow/penguin-core";import type {PendingFollowUpInfo,@@ -180,6 +181,8 @@ export interface RuntimeSession {listBackgroundCommands?(): BackgroundCommandInfo[];/** Kills one background command process (core `Session.killBackgroundCommand`); false when the id is unknown. Optional, like listBackgroundCommands. */killBackgroundCommand?(processId: string): boolean;+ /** Hands one EXECUTING tool call back as a background task (core `Session.detachToolCall`). Optional: test fakes may omit it, reading as "not_running". */+ detachToolCall?(toolCallId: string): ToolDetachResult;/** Whether a background subagent is mid-round (core `Session.hasRunningBackgroundSubagents`); pins the entry against idle eviction. Optional, like listBackgroundCommands. */hasRunningBackgroundSubagents?(): boolean;/** All live subagent child sessions of the Session's environment (core `Session.listBackgroundSubagents`). Optional, like listBackgroundCommands. */@@ -1389,6 +1392,20 @@ export class SessionManager {await this.entries.get(sessionId)?.session.probeBackgroundCommandServices?.();}+ /**+ * Hands one EXECUTING tool call of a loaded session back as a background task (core+ * `Session.detachToolCall`): the call closes with a registry handle, its work keeps+ * running, and the turn carries on. An unloaded session has nothing executing, so it+ * answers "not_running" like an unknown id.+ */+ detachToolCall(sessionId: string, toolCallId: string): ToolDetachResult {+ const entry = this.entries.get(sessionId);+ if (!entry) return "not_running";+ const result = entry.session.detachToolCall?.(toolCallId) ?? "not_running";+ if (result === "detached") entry.lastActivityMs = Date.now();+ return result;+ }+/** Kills one background command process of a loaded session; false when the session isn't loaded or the id is unknown. */killProcess(sessionId: string, processId: string): boolean {const entry = this.entries.get(sessionId);diff --git a/packages/server/test/session-processes.test.ts b/packages/server/test/session-processes.test.tsindex 478ff273..0352e749 100644--- a/packages/server/test/session-processes.test.ts+++ b/packages/server/test/session-processes.test.ts@@ -6,10 +6,18 @@* 204 removes it, 409 process_running while it still runs (stop is the kill route's* job — removal never signals a live process group), 404 for unknown ids and for* sessions whose runtime is gone (nothing left to remove either way);+ * - POST /api/sessions/:id/tool-calls/:tcid/background — hand an executing call back as a+ * background task: 204, 404 tool_call_not_found when nothing with that id is running,+ * 409 tool_not_detachable when the tool has no background form;* - 404 for foreign/unknown sessions (the shared resolveSession semantics).*/import { afterEach, beforeEach, describe, expect, it } from "vitest";-import type { BackgroundCommandInfo, OmniMessage, ApproveFn } from "@prismshadow/penguin-core";+import type {+ BackgroundCommandInfo,+ OmniMessage,+ ApproveFn,+ ToolDetachResult,+} from "@prismshadow/penguin-core";import type { SessionProcessesResponse } from "../src/api/types.js";import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";@@ -20,12 +28,23 @@ const SID = "session-2026-08-18-10-00-00-ccdd0031";const SID_UNLOADED = "session-2026-08-18-10-00-00-ccdd0032";const STARTED_AT = Date.UTC(2026, 7, 18, 12, 4, 0);+/**+ * What core's detach answers per tool_call_id in these tests: one executing call the user can+ * move to the background, one executing call whose tool has no background form. Any other id+ * is a call that is not running.+ */+const DETACH_ANSWERS = new Map<string, ToolDetachResult>([+ ["call_exec_1", "detached"],+ ["call_read_1", "not_detachable"],+]);+/** Fake Session backed by a mutable process array; kill removes the entry like core's registry. */function processesFakeSession(sessionId: string,procs: BackgroundCommandInfo[],kills: string[],probes?: string[],+ detaches?: string[],): RuntimeSession {return {sessionId,@@ -47,6 +66,11 @@ function processesFakeSession(procs.splice(i, 1);return true;},+ detachToolCall: (toolCallId: string) => {+ const answer = DETACH_ANSWERS.get(toolCallId) ?? "not_running";+ if (answer === "detached") detaches?.push(toolCallId);+ return answer;+ },};}@@ -57,6 +81,7 @@ describe("session processes routes", () => {let procs: BackgroundCommandInfo[];let kills: string[];let probes: string[];+ let detaches: string[];const sessionRow = (sessionId: string): SessionRow => ({sessionId,@@ -98,8 +123,12 @@ describe("session processes routes", () => {];kills = [];probes = [];+ detaches = [];t.deps.sessionsRepo.insert(sessionRow(SID));- t.deps.manager.adopt(sessionRow(SID), processesFakeSession(SID, procs, kills, probes));+ t.deps.manager.adopt(+ sessionRow(SID),+ processesFakeSession(SID, procs, kills, probes, detaches),+ );// A second session with no runtime entry: truthfully reports no processes.t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED));});@@ -196,12 +225,46 @@ describe("session processes routes", () => {expect(body.processes.map((p) => p.processId)).toEqual(["proc-22222222"]);});+ it("POST background moves an executing call to the background (204)", async () => {+ const res = await api.post(`/api/sessions/${SID}/tool-calls/call_exec_1/background`, {});+ expect(res.status).toBe(204);+ expect(detaches).toEqual(["call_exec_1"]);+ });++ it("POST background → 404 tool_call_not_found for a call that is not running, or an unloaded runtime", async () => {+ const gone = await api.post(`/api/sessions/${SID}/tool-calls/call_ghost/background`, {});+ expect(gone.status).toBe(404);+ expect(((await gone.json()) as { error: { code: string } }).error.code).toBe(+ "tool_call_not_found",+ );++ const unloaded = await api.post(+ `/api/sessions/${SID_UNLOADED}/tool-calls/call_exec_1/background`,+ {},+ );+ expect(unloaded.status).toBe(404);+ expect(detaches).toEqual([]);+ });++ it("POST background → 409 tool_not_detachable for a tool with no background form", async () => {+ const res = await api.post(`/api/sessions/${SID}/tool-calls/call_read_1/background`, {});+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(+ "tool_not_detachable",+ );+ expect(detaches).toEqual([]);+ });+it("foreign and unknown sessions → 404 (same auth semantics as the other session routes)", async () => {expect((await outsider.get(`/api/sessions/${SID}/processes`)).status).toBe(404);expect((await outsider.delete(`/api/sessions/${SID}/processes/proc-22222222`)).status).toBe(404,);expect((await api.delete(`/api/sessions/session-ghost/processes/proc-1`)).status).toBe(404);+ expect(+ (await outsider.post(`/api/sessions/${SID}/tool-calls/call_exec_1/background`, {})).status,+ ).toBe(404);expect(kills).toEqual([]);+ expect(detaches).toEqual([]);});});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 37fd38d6..f3d3606a 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -728,6 +728,17 @@ export const postApproval = ({ method: "POST", body },);+/**+ * Hands one EXECUTING tool call back as a background task, so the turn closes and the+ * conversation carries on (404 tool_call_not_found when the call already finished — a benign+ * race the caller just ignores; 409 tool_not_detachable when the tool has no background form).+ */+export const postToolCallBackground = (sessionId: string, toolCallId: string) =>+ apiFetch<void>(+ `/api/sessions/${encodeURIComponent(sessionId)}/tool-calls/${encodeURIComponent(toolCallId)}/background`,+ { method: "POST", body: {} },+ );+export const postAbort = (sessionId: string) =>apiFetch<void>(`/api/sessions/${encodeURIComponent(sessionId)}/abort`, {method: "POST",diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex d4b88091..f75fb685 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -1341,6 +1341,23 @@ export function ChatPage() {[selected, stream],);+ // "Move to background" on an executing tool call: the call returns a background handle and+ // the turn carries on. 404 means it finished in the click's race window and 409 that the+ // tool has no background form — the card settles on its own either way, so neither is worth+ // a toast; anything else is a real failure the user should see.+ const onSendToBackground = useCallback(+ async (toolCallId: string) => {+ if (!selected) return;+ try {+ await api.postToolCallBackground(selected.sessionId, toolCallId);+ } catch (e) {+ if (e instanceof ApiError && (e.status === 404 || e.status === 409)) return;+ toastError(apiErrorText(e));+ }+ },+ [selected],+ );+const onChangeApprovalMode = useCallback((mode: ApprovalMode) => {if (!selected || modeSaving) return;@@ -1512,6 +1529,7 @@ export function ChatPage() {const ctx: StreamRenderContext = {pendingApprovals: stream.pendingApprovals,onApprove,+ onSendToBackground,origin: [],// Any non-idle state (running / compacting) counts as "not yet stopped": compaction can// happen mid-turn, and if only running were checked, the trailing group would flash@@ -1893,14 +1911,19 @@ export function ChatPage() {/>{/* Right of the time, only while the conversation still owns backgroundwork — command processes past their yield window, background subagents- mid-round: their count, in the live-status green, the same figure and- glyph as the session row's mark and read live off the row. Bare ink like- the chips beside it, not a tinted pill: this is one more reading in the- stat row, not a badge that should out-weigh them. */}+ mid-round: their count, in the same tone, figure and glyph as the+ session row's mark and read live off the row. A count is what this+ reading is, and a glyph beside a number is how every other chip in this+ row says what its number counts. Bare ink like the chips beside it, not+ a tinted pill: this is one more reading in the stat row, not a badge+ that should out-weigh them. Muted rather than the live-status green:+ background work is a fact about the conversation, not the live run this+ row is otherwise reporting — and `muted` may recede here because the+ title names the count in words, so the colour carries nothing alone. */}{backgroundCount > 0 && (<spantitle={S.chat.backgroundTasks(backgroundCount)}- className={`flex shrink-0 items-center ${ICON_GAP.tight} font-mono text-xs ${toneInk.busy}`}+ className={`flex shrink-0 items-center ${ICON_GAP.tight} font-mono text-xs ${toneInk.muted}`}><GlyphIcon d={BACKGROUND_TASKS_ICON} />{backgroundCount}diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex ad3b4a7f..d3952f77 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -24,6 +24,13 @@ export interface StreamRenderContext {/** approvalKey(origin, toolCallId) → pending approval (disambiguates by origin when parent/child session tool_call_ids collide). */pendingApprovals: ReadonlyMap<string, PendingApproval>;onApprove: (toolCallId: string, decision: "allow" | "deny", origin: string[]) => Promise<void>;+ /**+ * "Move to background" on an executing tool call: the call hands its work back as a+ * background task and the turn carries on. Only honored on main-session items — a+ * subagent's call belongs to the child Session's environment, which the route does not+ * target (same rule as onRetryNow). The button does not render if this isn't wired up.+ */+ onSendToBackground?: (toolCallId: string) => Promise<void>;/** Origin chain at the current render level (empty array for the main session; subagent cards append one level each). */origin: string[];/**diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsxindex 7cd231f4..cef7b4c4 100644--- a/packages/web/src/features/chat/tool-call-card.tsx+++ b/packages/web/src/features/chat/tool-call-card.tsx@@ -15,6 +15,7 @@* approval block below the row is always on screen and names the tool and its arguments.*/import { useMemo, useRef, useState } from "react";+import { DETACHED_TOOL_NOTE_PREFIX } from "@prismshadow/penguin-core/interfaces";import { S } from "../../lib/strings";import { humanizeDuration } from "../../lib/format";import { toolDisplayName } from "../../lib/tool-alias";@@ -28,8 +29,7 @@ import {DISCLOSURE_ROW_STICKY_CLASS,} from "./disclosure-row";import { ZoomableImage } from "../../components/ui/image-zoom";-import { ICON_SIZE } from "../../lib/icon-scale";-import { BackgroundTasksMark } from "../../components/ui/session-activity-icon";+import { toneInk } from "../../lib/tone";import { StatusIcon } from "../../components/ui/status-icon";import type { RunState } from "../../components/ui/status-icon";import { ApprovalButtons } from "./approval-buttons";@@ -50,6 +50,13 @@ const DESCRIBED_TOOLS = new Set([/** The three file tools: previewed by their `file_path` argument. */const FILE_TOOLS = new Set(["read_file", "edit_file", "write_file"]);+/**+ * The tools whose running call can be handed back as a background task: the two that own a+ * registry the work can move into (a process_id, a subagent_id). The file tools have nothing+ * to hand back, and an MCP tool has no such concept — asking would be refused.+ */+const DETACHABLE_TOOLS = new Set(["exec_command", "run_subagent"]);+/*** Tool names Traces carried before `read_file` absorbed image reading (2026-09-02): their* image argument was `source`, previewed here like a file path so an old Trace's card still@@ -164,6 +171,37 @@ export function isBackgroundCall(argsJson: string): boolean {);}+/**+ * Whether a call was moved to the background by the user while it was executing: its output+ * carries the note the tool wrote on handing its work back. Read from the output rather than+ * remembered from the click, so the mark survives a reload — the click is nowhere in the+ * Trace, and the note is.+ */+export function isDetachedCall(output: string): boolean {+ return output.includes(DETACHED_TOOL_NOTE_PREFIX);+}++/**+ * Whether the header offers "move to background": only while the call is genuinely executing+ * (that is the whole window in which there is something to move), only for a tool that has a+ * background form, and only on a main-session card — a subagent's call lives in the child+ * Session's environment, which the route does not target.+ *+ * A call launched with `run_in_background` is excluded: its work is already back in the+ * registry, so there is nothing left to hand over, and the row would briefly carry the+ * background glyph twice — once as the action, once as the mark that call already wears.+ */+export function showsBackgroundAction(+ name: string,+ argsJson: string,+ executing: boolean,+ origin: readonly string[],+): boolean {+ return (+ executing && origin.length === 0 && DETACHABLE_TOOLS.has(name) && !isBackgroundCall(argsJson)+ );+}+/*** Decoded file-tool payload for the pending-approval block: the user is approving a* concrete rewrite (old_string/new_string/content), so the bare path is not enough — the@@ -304,6 +342,16 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRenconst denied =(item.decision === "deny" || item.decision === "forbidden") &&item.outputStopReason === "aborted";+ // Shared by the row and the chevron beside it: two buttons, one disclosure. Collapsing+ // while the row is stuck lands the view back on the row.+ const toggleOpen = (): void => {+ userToggled.current = true;+ const willClose = open;+ setOpen((v) => !v);+ if (willClose) {+ requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));+ }+ };const stateLabel = pending? S.chat.approvalWaiting: state === "running"@@ -341,64 +389,95 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRenalways on screen while one is pending — it names the tool, shows the arguments andcarries the Allow/Deny buttons — so the row would only repeat it. The amber hourglassStatusIcon (labeled) marks the wait, at every breakpoint. */}- <button- type="button"- aria-expanded={open}- onClick={() => {- userToggled.current = true;- const willClose = open;- setOpen((v) => !v);- if (willClose) {- requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));- }- }}- className={`${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}- >- <StatusIcon state={state} label={stateLabel} />- <span- title={nameTitle}- className="shrink-0 truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-300"+ <div className={`${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}>+ <button+ type="button"+ aria-expanded={open}+ onClick={toggleOpen}+ className="flex min-w-0 flex-1 items-center gap-2 self-stretch text-left">- {displayName || S.chat.unknownTool}- </span>- {/* Human-readable subtitle: the model-written call description (command/subagent tools) or the file path (file tools). */}- {subtitle && (- <span className="min-w-0 shrink truncate text-xs text-gray-500 dark:text-gray-400">- {subtitle}+ <StatusIcon state={state} label={stateLabel} />+ <span+ title={nameTitle}+ className="shrink-0 truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-300"+ >+ {displayName || S.chat.unknownTool}+ </span>+ {/* Human-readable subtitle: the model-written call description (command/subagent tools) or the file path (file tools). */}+ {subtitle && (+ <span className="min-w-0 shrink truncate text-xs text-gray-500 dark:text-gray-400">+ {subtitle}+ </span>+ )}+ <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">+ {item.durationMs !== undefined ? (+ humanizeDuration(item.durationMs)+ ) : executing ? (+ // Execution timer: argument-generation baseline + a live segment starting from approval grant (or from call completion if no approval was needed).+ <LiveDuration sinceMs={item.approvalAtMs ?? item.callStartedAtMs} offsetMs={genMs} />+ ) : pending ? (+ // No ticking while waiting on approval: frozen at the settled argument-generation segment.+ genMs > 0 ? (+ humanizeDuration(genMs)+ ) : null+ ) : item.callStreaming ? (+ // Generating arguments: live-ticking timer (falls back to a pulsing ellipsis when no start time is known).+ item.argStartedAtMs !== undefined ? (+ <LiveDuration sinceMs={item.argStartedAtMs} />+ ) : (+ <span className="animate-pulse">…</span>+ )+ ) : null}</span>- )}- <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">- {item.durationMs !== undefined ? (- humanizeDuration(item.durationMs)- ) : executing ? (- // Execution timer: argument-generation baseline + a live segment starting from approval grant (or from call completion if no approval was needed).- <LiveDuration sinceMs={item.approvalAtMs ?? item.callStartedAtMs} offsetMs={genMs} />- ) : pending ? (- // No ticking while waiting on approval: frozen at the settled argument-generation segment.- genMs > 0 ? (- humanizeDuration(genMs)- ) : null- ) : item.callStreaming ? (- // Generating arguments: live-ticking timer (falls back to a pulsing ellipsis when no start time is known).- item.argStartedAtMs !== undefined ? (- <LiveDuration sinceMs={item.argStartedAtMs} />- ) : (- <span className="animate-pulse">…</span>- )- ) : null}- </span>- {/* Right of the duration, on a call made with run_in_background: the same mark the- session list draws on the conversation, so a backgrounded call and the row that- counts it read as one thing. It sits after the duration rather than beside the- name so it never competes with the truncating subtitle, and the row's own status- icon keeps saying what the CALL did — this says where its work went. */}- {isBackgroundCall(item.argumentsText) && (- <BackgroundTasksMark label={S.chat.backgroundCall} size={ICON_SIZE.inlineGlyph} />- )}- <span className="min-w-0 flex-1" />- {/* Expand indicator on the right */}- <Chevron open={open} className="text-gray-400" />- </button>+ {/* Right of the duration, on a call made with run_in_background or moved there:+ a bracketed marker in the row's own mono type, the shape this row already used+ for an outcome that needs a word. A glyph here would be the session list's+ count-of-many mark doing duty for a single call, and it would say nothing to a+ reader who cannot spend a hover on it. It sits after the duration rather than+ beside the name so it never competes with the truncating subtitle, and the row's+ own status icon keeps saying what the CALL did — this says where its work went. */}+ {(isBackgroundCall(item.argumentsText) || isDetachedCall(item.output)) && (+ <span className={`shrink-0 font-mono text-xs ${toneInk.muted}`}>+ {S.chat.backgroundCall}+ </span>+ )}+ <span className="min-w-0 flex-1" />+ </button>+ {/* "Send to background" while the call executes: the tool hands its work back as a+ background task and the turn carries on. A sibling of the row button rather than a+ child — a <button> cannot nest another — with the hover tint on the whole row, so the+ two still read as one line. The app's inline text-action style: a real <button>+ (it acts, it navigates nowhere) painted as a link. Text at the row's own size and+ NO padding of its own, so a row carrying it measures exactly like one that does not+ — an action that changed the row's height would break the rhythm of a list of calls.++ No click guard: a second detach is a no-op on an already-fired controller, and once+ the call closes the action unmounts on its own — which is also the feedback. */}+ {showsBackgroundAction(item.name, item.argumentsText, executing, ctx.origin) &&+ ctx.onSendToBackground && (+ <button+ type="button"+ title={S.chat.sendToBackgroundHint}+ onClick={() => void ctx.onSendToBackground?.(item.toolCallId)}+ className="shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"+ >+ {S.chat.sendToBackground}+ </button>+ )}+ {/* Expand indicator on the right; clicking it toggles too (it is its own button, so the+ row's action above stays reachable). Named for what it DOES, the way every other+ chevron toggle here is: naming it after the tool would give the row two buttons under+ one name, which no row-scoped query could then tell apart. */}+ <button+ type="button"+ aria-expanded={open}+ aria-label={open ? S.nav.collapseGroup : S.nav.expandGroup}+ onClick={toggleOpen}+ className="flex shrink-0 items-center self-stretch"+ >+ <Chevron open={open} className="text-gray-400" />+ </button>+ </div>{/* Pending approval: always visible regardless of collapsed state — shows the tool name and arguments so the user knows what they're approving. */}{pending && (diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex f59201be..58e68446 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1757,8 +1757,13 @@ Scenarios:backgroundTasks: (n: number) => (n === 1 ? "1 background task" : `${n} background tasks`),/** The session row's alarm clock: at least one enabled scheduled task is bound to this conversation (a paused one draws no mark). */sessionScheduled: "Has a scheduled task still to fire",- /** The same mark on a tool row, where it stands for the ONE call made with `run_in_background` rather than for a count. */- backgroundCall: "Runs in the background",+ /** The tool row's marker for the ONE call whose work went to the background — launched with `run_in_background`, or moved there by the user — rather than for a count. Bracketed, like the row's other outcome markers. */+ backgroundCall: "[Background]",+ /** The tool row's inline text action, shown while the call is executing (also its accessible name). */+ sendToBackground: "Send to background",+ /** Its tooltip: what the click does to the call and to the conversation. */+ sendToBackgroundHint:+ "Send this call to the background; the conversation carries on, and its completion arrives as a background notice.",pendingApprovals: (n: number) => `${n} pending approval${n > 1 ? "s" : ""}`,jumpToLatest: "Jump to latest",/** Top-of-stream affordance while the previous history window is being fetched (scroll-up backfill). */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 48549eb4..7df20774 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1729,8 +1729,12 @@ Benchmark:backgroundTasks: (n: number) => `${n} 个后台任务`,/** The session row's alarm clock: at least one enabled scheduled task is bound to this conversation (a paused one draws no mark). */sessionScheduled: "有待触发的定时任务",- /** The same mark on a tool row, where it stands for the ONE call made with `run_in_background` rather than for a count. */- backgroundCall: "在后台运行",+ /** The tool row's marker for the ONE call whose work went to the background — launched with `run_in_background`, or moved there by the user — rather than for a count. Bracketed, like the row's other outcome markers. */+ backgroundCall: "[后台任务]",+ /** The tool row's inline text action, shown while the call is executing (also its accessible name). */+ sendToBackground: "转入后台执行",+ /** Its tooltip: what the click does to the call and to the conversation. */+ sendToBackgroundHint: "把这次调用转入后台执行,对话继续进行;它结束时会以后台任务通知送回。",pendingApprovals: (n: number) => `${n} 个待审批`,jumpToLatest: "回到最新消息",/** Top-of-stream affordance while the previous history window is being fetched (scroll-up backfill). */diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.tsindex 42c020bc..d5313345 100644--- a/packages/web/test/session-activity.test.ts+++ b/packages/web/test/session-activity.test.ts@@ -65,11 +65,12 @@ describe("sessionBackgroundTasks", () => {});/**- * The background-task mark: one glyph in the `muted` tone for both of its placements — a- * session row / the chat header, where it stands for a count, and a tool row, where it marks- * the single call made with `run_in_background`. Rendered only when there is background work- * to report (the caller's decision), and always naming what it means in the accessible name- * and tooltip, so the glyph is never the only carrier.+ * The background-task mark: one glyph in the `muted` tone, standing for a count in both of+ * its placements — a session row and the chat header. Rendered only when there is background+ * work to report (the caller's decision), and always naming what it means in the accessible+ * name and tooltip, so the glyph is never the only carrier. A tool row says the same thing in+ * words instead (S.chat.backgroundCall, covered by tool-call-preview.test.ts), because there+ * it marks one call rather than a count.*/describe("BackgroundTasksMark", () => {const render = (label: string, size: number) =>@@ -83,18 +84,9 @@ describe("BackgroundTasksMark", () => {expect(S.chat.backgroundTasks(3)).toContain("3");});- it("names one call where it marks one call, rather than a count of one", () => {- // The tool row marks a single run_in_background call: "1 background task" would be a- // count the row is not making, and would read as the conversation's total.- const markup = render(S.chat.backgroundCall, ICON_SIZE.inlineGlyph);- expect(markup).toContain(`aria-label="${S.chat.backgroundCall}"`);- expect(S.chat.backgroundCall).not.toBe(S.chat.backgroundTasks(1));- expect(S.chat.backgroundCall).not.toMatch(/\d/);- });-it("draws the activity trace in the muted tone, at the rung its caller passes", () => {- expect(render(S.chat.backgroundCall, ICON_SIZE.rowMark)).toMatch(/width="12"/);- expect(render(S.chat.backgroundCall, ICON_SIZE.inlineGlyph)).toMatch(/width="13"/);+ expect(render(S.chat.backgroundTasks(1), ICON_SIZE.rowMark)).toMatch(/width="12"/);+ expect(render(S.chat.backgroundTasks(1), ICON_SIZE.inlineGlyph)).toMatch(/width="13"/);const markup = render(S.chat.backgroundTasks(1), ICON_SIZE.rowMark);expect(markup).toContain(`d="${BACKGROUND_TASKS_ICON}"`);// Parked work is a fact about the Session, not a turn in progress: the mark recedes withdiff --git a/packages/web/test/tool-call-preview.test.ts b/packages/web/test/tool-call-preview.test.tsindex f783d0a0..f3e59198 100644--- a/packages/web/test/tool-call-preview.test.ts+++ b/packages/web/test/tool-call-preview.test.ts@@ -5,15 +5,20 @@* pendingFilePayload decodes the file-tool arguments so a pending approval shows the actual* rewrite. All must tolerate incomplete mid-stream JSON; headerSubtitle additionally holds a* still-streaming field back until its closing quote so the header never jitters (#137).+ * isDetachedCall and showsBackgroundAction decide the background mark and the "move to+ * background" button from the same row's facts.*/import { describe, expect, it } from "vitest";import {headerSubtitle,isBackgroundCall,+ isDetachedCall,pendingFilePayload,previewArguments,shortenPath,+ showsBackgroundAction,} from "../src/features/chat/tool-call-card";+import { S } from "../src/lib/strings";describe("previewArguments", () => {it("renders exec_command as $ <cmd>", () => {@@ -188,3 +193,68 @@ describe("isBackgroundCall", () => {expect(isBackgroundCall("")).toBe(false);});});++describe("isDetachedCall", () => {+ it("marks a call whose output carries the note the tool wrote on being moved to the background", () => {+ expect(+ isDetachedCall(+ "building…\n[moved to the background by the user with process_id proc-12ab34cd; its " ++ "completion will arrive as a user message — no need to poll.]",+ ),+ ).toBe(true);+ });++ it("leaves an ordinary or deadline-promoted call unmarked", () => {+ expect(isDetachedCall("done\n[exit code: 0]")).toBe(false);+ // The yield deadline promotes too, but nobody moved that one — it wears no mark today.+ expect(+ isDetachedCall("[process running with process_id proc-12ab34cd; use input_command …]"),+ ).toBe(false);+ expect(isDetachedCall("")).toBe(false);+ });+});++describe("showsBackgroundAction", () => {+ const EXEC = '{"cmd":"pnpm dev"}';++ it("offers the action while the two detachable tools execute on a main-session card", () => {+ expect(showsBackgroundAction("exec_command", EXEC, true, [])).toBe(true);+ expect(showsBackgroundAction("run_subagent", '{"prompt":"go"}', true, [])).toBe(true);+ });++ it("hides it once the call is no longer executing", () => {+ expect(showsBackgroundAction("exec_command", EXEC, false, [])).toBe(false);+ });++ it("hides it for tools with no background form", () => {+ expect(showsBackgroundAction("read_file", '{"file_path":"a.txt"}', true, [])).toBe(false);+ expect(showsBackgroundAction("input_command", '{"process_id":"proc-1"}', true, [])).toBe(false);+ expect(showsBackgroundAction("mcp__docs__search", "{}", true, [])).toBe(false);+ });++ it("hides it on a subagent-nested card: that call lives in the child Session's environment", () => {+ expect(showsBackgroundAction("exec_command", EXEC, true, ["session-child-12ab34cd"])).toBe(+ false,+ );+ });++ it("hides it on a call already launched with run_in_background: nothing left to hand over", () => {+ expect(+ showsBackgroundAction(+ "exec_command",+ '{"cmd":"pnpm dev","run_in_background":true}',+ true,+ [],+ ),+ ).toBe(false);+ });+});++describe("the tool row's background marker", () => {+ it("marks one call rather than a count of one", () => {+ // The row marks a single call whose work went to the background; "1 background task"+ // would be a count the row is not making, and would read as the conversation's total.+ expect(S.chat.backgroundCall).not.toBe(S.chat.backgroundTasks(1));+ expect(S.chat.backgroundCall).not.toMatch(/\d/);+ });+});