Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(agent-runtime): support background Bash in TaskList, TaskWait, and TaskStop

cauliflower76ffc3058550
diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
index 9b16001b6..856698b59 100644
--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
@@ -46,7 +46,7 @@ import {
delegationRoster,
delegationRosterOutcome,
delegationRosterSummary,
- lifecycleKindOf,
+ lifecycleKindOf, backgroundJobRowOf,
subagentOutcome,
type SubagentOutcome,
type SubagentTiming,
@@ -234,6 +234,7 @@ function HostToolRow({
// the agent names it reports on replace the bare delegation ids it was
// called with, and its badge rolls up their statuses (D268).
const lifecycle = action === "delegate" ? lifecycleKindOf(message) : null;
+ const jobRow = lifecycle ? backgroundJobRowOf(message) : null;
const roster = lifecycle ? delegationRoster(message) : [];
const rosterSummary = lifecycle ? delegationRosterSummary(roster) : "";
const rosterOutcome = lifecycle ? delegationRosterOutcome(roster) : null;
@@ -290,7 +291,13 @@ function HostToolRow({
// A lifecycle row never falls back to its arguments: while it is still
// running it has no roster yet, and `delegationIds` would otherwise reach the
// head as a JSON blob of UUIDs (D268).
- const summary = lifecycle ? rosterSummary : argSummary;
+ const summary = jobRow
+ ? [
+ rosterSummary, jobRow.command,
+ jobRow.count !== undefined && t("backgroundTasks.headerCount", { count: jobRow.count }),
+ jobRow.state && t(`backgroundTasks.${jobRow.state}`),
+ ].filter(Boolean).join(" · ")
+ : lifecycle ? rosterSummary : argSummary;
const statusLabel = creating
? t("chat.subagentCreating")
: outcome
@@ -473,14 +480,14 @@ function HostToolRow({
onClick={() => hasDetails && toggleRow()}
>
<span
- className={`tool-row-icon${lifecycle ? " is-subagent" : ""}`}
+ className={`tool-row-icon${lifecycle && !jobRow ? " is-subagent" : ""}`}
>
- <ToolActionIcon action={action} />
+ <ToolActionIcon action={jobRow ? (jobRow.kind === "list" ? "list" : "run") : action} />
</span>
<span
className={`tool-row-name ${status === "running" ? "running" : ""}`}
>
- {lifecycle
+ {jobRow ? rawName : lifecycle
? t(
(status === "running"
? LIFECYCLE_RUNNING_KEYS
diff --git a/apps/desktop/src/lib/subagent-topology.ts b/apps/desktop/src/lib/subagent-topology.ts
index 046c38868..13fd0dd9a 100644
--- a/apps/desktop/src/lib/subagent-topology.ts
+++ b/apps/desktop/src/lib/subagent-topology.ts
@@ -384,6 +384,30 @@ export function lifecycleKindOf(
return delegationLifecycleKind(message.toolName);
}
+/** New job controls share names with historical delegation-only rows. */
+export function backgroundJobRowOf(message: UiMessage) {
+ const kind = lifecycleKindOf(message);
+ if (!kind) return null;
+ const details = asRecord(toolResultPayload(message));
+ if (kind === "list") {
+ const jobs = asRecord(details?.backgroundJobs);
+ if (jobs?.supported === true && Array.isArray(jobs.tasks)) {
+ return { kind, count: jobs.tasks.length };
+ }
+ // While listing, the caller has not learned which jobs are present.
+ return message.toolStatus === "running" ? { kind } : null;
+ }
+ const snapshot = asRecord(details?.job);
+ const ref = asRecord(asRecord(message.toolArgs)?.job) ?? asRecord(snapshot?.job) ?? snapshot;
+ if (ref?.kind !== "bash") return null;
+ const state = snapshot?.state;
+ return {
+ kind, command: typeof snapshot?.command === "string" ? snapshot.command : "Bash",
+ state: state === "running" && snapshot?.stopRequested ? "stopping" as const :
+ state === "running" || state === "exited" || state === "failed" || state === "stopped" ? state : undefined,
+ };
+}
+
export function subagentOutcome(
message: UiMessage,
statuses?: ReadonlyMap<string, SubagentOutcome>,
diff --git a/apps/desktop/test/subagent-topology.test.mjs b/apps/desktop/test/subagent-topology.test.mjs
index 869954adb..5e05bdc0a 100644
--- a/apps/desktop/test/subagent-topology.test.mjs
+++ b/apps/desktop/test/subagent-topology.test.mjs
@@ -17,6 +17,7 @@ const {
delegationTimingBounds,
isDelegationActivityItem,
lifecycleKindOf,
+ backgroundJobRowOf,
subagentOutcome,
summarizeSubagentActivity,
} = await import("../src/lib/subagent-topology.ts");
@@ -426,6 +427,19 @@ test("a lifecycle row names the subagents it reports on (D268)", () => {
assert.equal(delegationRosterOutcome(roster), "failed");
});
+test("background controls describe the command, including pending stops and mixed lists", () => {
+ const ref = { kind: "bash", id: "process" };
+ const wait = lifecycle("TaskWait", { status: "timeout", job: ref }).message;
+ assert.equal(backgroundJobRowOf(wait).command, "Bash");
+ const pending = lifecycle("TaskStop", { job: { job: ref, command: "npm test", state: "running", stopRequested: true } }).message;
+ assert.deepEqual(backgroundJobRowOf(pending), { kind: "stop", command: "npm test", state: "stopping" });
+ const mixed = lifecycle("TaskList", { delegations: [{ delegationId: "d", agent: "reviewer" }], backgroundJobs: { supported: true, tasks: [ref] } }).message;
+ assert.equal(backgroundJobRowOf(mixed).count, 1);
+ assert.equal(delegationRosterSummary(delegationRoster(mixed)), "reviewer");
+ assert.equal(backgroundJobRowOf(lifecycle("TaskStop", { stopped: [] }).message), null);
+ assert.equal(backgroundJobRowOf({ ...wait, toolArgs: { job: ref }, toolResult: undefined, toolStatus: "running" }).command, "Bash");
+});
+
test("a repeated agent is counted, not listed twice", () => {
const list = lifecycle("TaskList", {
delegations: [
diff --git a/apps/desktop/test/subagent-transcript.test.mjs b/apps/desktop/test/subagent-transcript.test.mjs
index 4f7784482..f8c1487bf 100644
--- a/apps/desktop/test/subagent-transcript.test.mjs
+++ b/apps/desktop/test/subagent-transcript.test.mjs
@@ -102,7 +102,7 @@ test("a lifecycle row summarizes by agent name, never by delegation id", () => {
// A lifecycle row is presented as a subagent row, not as "Delegated".
assert.match(transcriptSource, /LIFECYCLE_RUNNING_KEYS\s*\n?\s*: LIFECYCLE_LABEL_KEYS\)\[lifecycle\]/);
// It never falls back to its own arguments, so a pending wait shows no ids.
- assert.match(transcriptSource, /const summary = lifecycle \? rosterSummary : argSummary;/);
+ assert.match(transcriptSource, /: lifecycle \? rosterSummary : argSummary;/);
// ...and it is still not a topology node.
assert.match(topologySource, /if \(isDelegationActivityItem\(item\)\) continue;/);
});
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rs
index 178662d24..e374720cf 100644
--- a/crates/host-core/src/background_tasks.rs
+++ b/crates/host-core/src/background_tasks.rs
@@ -13,7 +13,9 @@
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
-use std::time::Instant;
+use std::time::{Duration, Instant};
+
+pub(crate) mod jobs;
use crate::tools;
use serde::Serialize;
@@ -96,6 +98,16 @@ pub struct BackgroundTask {
pub started_at: Instant,
pub shared: Arc<Mutex<TaskShared>>,
stop: watch::Sender<bool>,
+ settled: watch::Sender<Option<Duration>>,
+}
+
+impl BackgroundTask {
+ fn elapsed_ms(&self) -> u64 {
+ self.settled
+ .borrow()
+ .unwrap_or_else(|| self.started_at.elapsed())
+ .as_millis() as u64
+ }
}
#[derive(Serialize)]
@@ -194,7 +206,7 @@ impl BackgroundTaskRegistry {
command: task.command.clone(),
command_shell_id: task.command_shell_id.clone(),
state,
- elapsed_ms: task.started_at.elapsed().as_millis() as u64,
+ elapsed_ms: task.elapsed_ms(),
exit_code,
}
})
@@ -331,6 +343,7 @@ fn register_spawned_task(
truncated: false,
})),
stop,
+ settled: watch::channel(None).0,
};
registry.order.push(task.id.clone());
registry.tasks.insert(task.id.clone(), task.clone());
@@ -367,6 +380,9 @@ async fn supervise(
// deadlock the readers, and disable recv after EOF to avoid a busy loop.
while exit.is_none() || !output_closed {
tokio::select! {
+ // An already observed exit takes precedence over a concurrent
+ // stop, and stopping takes precedence over a busy output pipe.
+ biased;
waited = &mut wait, if exit.is_none() => {
exit = Some(waited);
if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {
@@ -374,6 +390,15 @@ async fn supervise(
lifecycle_failed = true;
}
}
+ changed = stop_rx.changed(), if exit.is_none() && !stopping => {
+ if changed.is_err() || *stop_rx.borrow() {
+ stopping = true;
+ if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {
+ tracing::error!(task_id = %task.id, %error, "background task stop failed");
+ lifecycle_failed = true;
+ }
+ }
+ }
chunk = chunk_rx.recv(), if !output_closed => {
let Some((is_stdout, bytes)) = chunk else {
output_closed = true;
@@ -391,15 +416,6 @@ async fn supervise(
shared.truncated = true;
}
}
- changed = stop_rx.changed(), if !stopping => {
- if changed.is_err() || *stop_rx.borrow() {
- stopping = true;
- if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {
- tracing::error!(task_id = %task.id, %error, "background task stop failed");
- lifecycle_failed = true;
- }
- }
- }
}
}
for reader in [stdout_reader, stderr_reader] {
@@ -420,8 +436,7 @@ async fn supervise(
}
};
- let stopped = *stop_rx.borrow();
- let state = match (exit_code, stopped, lifecycle_failed) {
+ let state = match (exit_code, stopping, lifecycle_failed) {
(_, _, true) => BackgroundTaskState::Failed,
(_, true, false) => BackgroundTaskState::Stopped,
(Some(0), false, false) => BackgroundTaskState::Exited,
@@ -434,6 +449,7 @@ async fn supervise(
shared.truncated |= stdout_dropped || stderr_dropped;
shared.state = state;
shared.exit_code = exit_code;
+ task.settled.send_replace(Some(task.started_at.elapsed()));
}
on_changed();
}
@@ -467,14 +483,7 @@ pub async fn stop_task(registry: &BackgroundTaskRegistry, id: &str) -> Result<bo
let Some(task) = registry.tasks.get(id).cloned() else {
return Ok(false);
};
- let shared = task.shared.lock().await;
- // Idempotent: a task that already finished or is already stopping reports
- // "nothing to do" so a double click cannot queue a second kill.
- if shared.state != BackgroundTaskState::Running || *task.stop.borrow() {
- return Ok(false);
- }
- let _ = task.stop.send(true);
- Ok(true)
+ jobs::stop(&task).await
}
pub async fn task_output(
@@ -571,6 +580,9 @@ mod tests {
runner,
Arc::new(move || notify.notify_one()),
);
+ // On this current-thread runtime the stop is queued before the
+ // supervisor first polls the already-finished child.
+ assert!(jobs::stop(&task).await.unwrap());
tokio::time::timeout(Duration::from_secs(5), changed.notified())
.await
.expect("the process must settle after draining both pipes");
@@ -578,6 +590,13 @@ mod tests {
assert_eq!(output["state"], "exited");
assert_eq!(output["stdout"], "final-stdout");
assert_eq!(output["stderr"], "final-stderr");
+ let elapsed = jobs::snapshot(&task, false).await["elapsedMs"].clone();
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ assert_eq!(jobs::snapshot(&task, false).await["elapsedMs"], elapsed);
+ assert_eq!(
+ serde_json::json!(registry.summaries()[0].elapsed_ms),
+ elapsed
+ );
}
#[tokio::test]
diff --git a/crates/host-core/src/background_tasks/jobs.rs b/crates/host-core/src/background_tasks/jobs.rs
new file mode 100644
index 000000000..8e8c258db
--- /dev/null
+++ b/crates/host-core/src/background_tasks/jobs.rs
@@ -0,0 +1,145 @@
+//! Bounded model observations of an already-authorized, session-owned process.
+use super::*;
+use std::time::Duration;
+
+const MODEL_STREAM_BYTES: usize = 8 * 1024;
+
+pub(crate) fn find(
+ registry: &BackgroundTaskRegistry,
+ session_id: &str,
+ id: &str,
+) -> Option<BackgroundTask> {
+ registry
+ .tasks
+ .get(id)
+ .filter(|task| task.session_id == session_id)
+ .cloned()
+}
+
+fn tail(text: String, limit: usize) -> (String, bool) {
+ let mut start = text.len().saturating_sub(limit);
+ while !text.is_char_boundary(start) {
+ start += 1;
+ }
+ (text[start..].to_owned(), start > 0)
+}
+
+pub(crate) async fn snapshot(task: &BackgroundTask, output: bool) -> serde_json::Value {
+ let shared = task.shared.lock().await;
+ // List results must also have a budget; commands may contain large scripts.
+ let (command, _) = tail(task.command.clone(), 1024);
+ let mut result = serde_json::json!({
+ "job": { "kind": "bash", "id": task.id },
+ "command": command,
+ "state": shared.state,
+ "exitCode": shared.exit_code,
+ "elapsedMs": task.elapsed_ms(),
+ "stopRequested": *task.stop.borrow(),
+ });
+ if output {
+ let (stdout, stdout_cut) = tail(TaskShared::render(&shared.stdout), MODEL_STREAM_BYTES);
+ let (stderr, stderr_cut) = tail(TaskShared::render(&shared.stderr), MODEL_STREAM_BYTES);
+ result["stdout"] = stdout.into();
+ result["stderr"] = stderr.into();
+ result["truncated"] = (shared.truncated || stdout_cut || stderr_cut).into();
+ }
+ result
+}
+
+/// Each RPC waits at most one second. Abandoning a caller's wait never signals
+/// the process, and leaves at most this bounded observer on the Host.
+pub(crate) async fn wait(task: &BackgroundTask, timeout_ms: u64) {
+ let mut settled = task.settled.subscribe();
+ let _ = tokio::time::timeout(Duration::from_millis(timeout_ms), async {
+ settled.wait_for(Option::is_some).await
+ })
+ .await;
+}
+
+pub(crate) async fn stop(task: &BackgroundTask) -> Result<bool, String> {
+ let shared = task.shared.lock().await;
+ if shared.state != BackgroundTaskState::Running || *task.stop.borrow() {
+ return Ok(false);
+ }
+ task.stop
+ .send(true)
+ .map_err(|_| "background task supervisor unavailable".to_string())?;
+ Ok(true)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn task() -> (BackgroundTask, watch::Receiver<bool>) {
+ let (stop, receiver) = watch::channel(false);
+ (
+ BackgroundTask {
+ id: "process".into(),
+ session_id: "owner".into(),
+ command: "fixture".into(),
+ command_shell_id: "bash".into(),
+ started_at: Instant::now(),
+ shared: Arc::new(Mutex::new(TaskShared {
+ state: BackgroundTaskState::Running,
+ exit_code: None,
+ stdout: VecDeque::new(),
+ stderr: VecDeque::new(),
+ stdout_bytes: 0,
+ stderr_bytes: 0,
+ truncated: false,
+ })),
+ stop,
+ settled: watch::channel(None).0,
+ },
+ receiver,
+ )
+ }
+
+ #[test]
+ fn tail_preserves_unicode_and_exact_budget() {
+ assert_eq!(tail("ab中文".into(), 4), ("文".into(), true));
+ assert_eq!(tail("中文".into(), 6), ("中文".into(), false));
+ }
+
+ #[tokio::test]
+ async fn completed_before_wait_is_immediate_and_output_is_repeatable() {
+ let (task, _receiver) = task();
+ {
+ let mut shared = task.shared.lock().await;
+ shared.state = BackgroundTaskState::Failed;
+ shared.exit_code = Some(1);
+ shared.push_stdout(&"中".repeat(10000));
+ shared.push_stderr("final assertion error");
+ }
+ task.settled.send_replace(Some(task.started_at.elapsed()));
+ tokio::time::timeout(Duration::from_millis(100), wait(&task, 1000))
+ .await
+ .unwrap();
+ let first = snapshot(&task, true).await;
+ let second = snapshot(&task, true).await;
+ assert_eq!(first["stderr"], second["stderr"]);
+ assert_eq!(first["exitCode"], 1);
+ assert_eq!(first["truncated"], true);
+ assert!(first["stdout"].as_str().unwrap().len() <= MODEL_STREAM_BYTES);
+ assert!(!stop(&task).await.unwrap());
+ }
+
+ #[tokio::test]
+ async fn waiting_does_not_stop_and_foreign_ids_are_not_resolved() {
+ let (task, receiver) = task();
+ let mut registry = BackgroundTaskRegistry::default();
+ registry.tasks.insert(task.id.clone(), task.clone());
+ assert!(find(&registry, "foreign", "process").is_none());
+ assert!(find(&registry, "owner", "missing").is_none());
+ assert!(find(&registry, "owner", "process").is_some());
+ wait(&task, 0).await;
+ assert!(!*receiver.borrow());
+ assert!(stop(&task).await.unwrap());
+ assert!(*receiver.borrow());
+ assert!(!stop(&task).await.unwrap());
+ let observed = snapshot(&task, true).await;
+ assert_eq!(observed["state"], "running");
+ assert_eq!(observed["stopRequested"], true);
+ }
+}
diff --git a/crates/host-core/src/background_tasks/windows_tests.rs b/crates/host-core/src/background_tasks/windows_tests.rs
index 18cf87cbf..7a7663a62 100644
--- a/crates/host-core/src/background_tasks/windows_tests.rs
+++ b/crates/host-core/src/background_tasks/windows_tests.rs
@@ -89,11 +89,11 @@ async fn stop_terminates_the_command_the_runner_launched() {
}
assert!(
- wait_for_exit(nested_pid),
+ wait_for_exit(nested_pid).await,
"the command's own child must not survive stopping the task (#1805)"
);
assert!(
- wait_for_exit(command_pid),
+ wait_for_exit(command_pid).await,
"the launched command must not survive stopping the task (#1805)"
);
@@ -130,12 +130,14 @@ fn process_running(pid: u32) -> bool {
}
#[cfg(windows)]
-fn wait_for_exit(pid: u32) -> bool {
+async fn wait_for_exit(pid: u32) -> bool {
for _ in 0..120 {
if !process_running(pid) {
return true;
}
- std::thread::sleep(Duration::from_millis(50));
+ // The supervisor shares this Tokio test runtime; yield so it can stop
+ // and reap the process while we observe its exit.
+ tokio::time::sleep(Duration::from_millis(50)).await;
}
false
}
diff --git a/crates/host-core/src/rpc/background_jobs.rs b/crates/host-core/src/rpc/background_jobs.rs
new file mode 100644
index 000000000..64ea815d9
--- /dev/null
+++ b/crates/host-core/src/rpc/background_jobs.rs
@@ -0,0 +1,95 @@
+//! Session-scoped model access. Desktop's existing global RPCs stay outside
+//! the model-side proxy allowlist.
+use super::*;
+use crate::background_tasks::jobs;
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct Request {
+ session_id: String,
+ id: Option<String>,
+ #[serde(default)]
+ timeout_ms: u64,
+}
+
+fn authorize(st: &AppState, session_id: &str) -> Result<(), JsonRpcError> {
+ let mode = sessions::session_mode(&st.db, session_id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "task not found", "NOT_FOUND"))?;
+ if mode != "agent" {
+ return Err(rpc_err(
+ 1001,
+ "background job controls require Agent mode",
+ "PERMISSION_DENIED",
+ ));
+ }
+ if remote_tools::session_remote_workspace(st, session_id)?.is_some() {
+ return Err(rpc_err(
+ 1002,
+ "background job controls require a local workspace",
+ "INVALID_PARAMS",
+ ));
+ }
+ Ok(())
+}
+
+pub(super) async fn handle(
+ state: Arc<Mutex<AppState>>,
+ method: &str,
+ params: Value,
+) -> Result<Value, JsonRpcError> {
+ let request: Request = serde_json::from_value(params)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ if request.timeout_ms > 1000 {
+ return Err(rpc_err(
+ 1002,
+ "timeoutMs must be at most 1000",
+ "INVALID_PARAMS",
+ ));
+ }
+ let st = state.lock().await;
+ authorize(&st, &request.session_id)?;
+ match method {
+ "backgroundJobs.capabilities" => Ok(json!({"version": 1, "supported": true})),
+ "backgroundJobs.list" => {
+ let tasks: Vec<_> = st
+ .background_tasks
+ .tasks
+ .values()
+ .filter(|task| task.session_id == request.session_id)
+ .cloned()
+ .collect();
+ drop(st);
+ let mut tasks = tasks;
+ tasks.sort_by_key(|task| task.started_at);
+ let mut summaries = Vec::with_capacity(tasks.len());
+ for task in tasks {
+ summaries.push(jobs::snapshot(&task, false).await);
+ }
+ Ok(json!({"tasks": summaries}))
+ }
+ "backgroundJobs.wait" | "backgroundJobs.stop" => {
+ let id = request
+ .id
+ .as_deref()
+ .filter(|id| !id.is_empty())
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let task = jobs::find(&st.background_tasks, &request.session_id, id)
+ .ok_or_else(|| rpc_err(1007, "task not found", "NOT_FOUND"))?;
+ // Only a short signal operation may hold the state lock. Waiting
+ // for output/exit must leave other sessions and Stop responsive.
+ if method == "backgroundJobs.stop" {
+ jobs::stop(&task)
+ .await
+ .map_err(|e| rpc_err(1000, e, "INTERNAL"))?;
+ }
+ drop(st);
+ jobs::wait(&task, request.timeout_ms).await;
+ let st = state.lock().await;
+ authorize(&st, &request.session_id)?;
+ drop(st);
+ Ok(jobs::snapshot(&task, true).await)
+ }
+ _ => Err(rpc_err(-32601, "method not found", "METHOD_NOT_FOUND")),
+ }
+}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 3bd331bd4..7ecac98cd 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1,3 +1,4 @@
+mod background_jobs;
mod computer_rpc;
mod config_sync_rpc;
mod file_batches;
@@ -1967,6 +1968,10 @@ async fn handle_request(
.map_err(config_sync_rpc_err);
}
+ if method.starts_with("backgroundJobs.") {
+ return background_jobs::handle(state, method, params).await;
+ }
+
if method.starts_with("tools.fileBatch") {
return file_batches::handle(state, method, params).await;
}
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 9f67bf355..c14c0ef57 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -3004,6 +3004,7 @@ async fn tool_bash(
.await?;
return Ok(serde_json::json!({
"backgroundTaskId": started,
+ "job": { "kind": "bash", "id": started },
"command": command,
"commandShellId": options.command_shell_id,
}));
diff --git a/docs/adr/0089-proactive-background-subagent-delegation.md b/docs/adr/0089-proactive-background-subagent-delegation.md
index 79918f6d1..f4cb57827 100644
--- a/docs/adr/0089-proactive-background-subagent-delegation.md
+++ b/docs/adr/0089-proactive-background-subagent-delegation.md
@@ -126,3 +126,34 @@ runs 10 delegates, telling the model to wait or stop first.
must remember to set is a flag it forgets; a lifecycle with distinct tools
makes "start, work, converge" a sequence the model can follow and the prompt
can teach.
+
+
+## Amendment — session-owned job controls (2026-11-05)
+
+Background Bash already belongs to Host and exposes results to the desktop,
+but the model's controls only resolve runtime delegation IDs. Extending each
+tool independently would duplicate target selection and risk adding permanent
+servers to default delegation wait/stop sets.
+
+TaskWait/List/Stop therefore share explicit typed job references. Runtime
+routes delegation references to the existing delegation implementation and
+Bash references to session-scoped Host RPC. The controls are registered even
+without a subagent catalog. Existing identifier fields and implicit delegation
+targets remain compatible. Host checks ownership and operating mode and keeps
+process supervision; this decision does not move delegation reports or
+resumption chains into Rust.
+
+Bash waits use bounded, completion-aware Host observations. Cancelling a wait
+does not signal the process. Output tails are repeatable and independently
+bounded for stdout and stderr. This keeps desktop and model readers independent
+without introducing log files or stdin access. A full process-lifecycle
+migration would unnecessarily couple Host to runtime report delivery; a
+TaskWait-only special case would leave discovery and cancellation inconsistent.
+Completion notifications are deferred: Bash completion is queried explicitly,
+while delegate auto-delivery retains its existing behavior. Remote workspaces
+and older Hosts explicitly report unsupported Bash controls.
+
+Trade-offs include up to one observation per second during a long wait and
+finite Host output/history retention. A process does not gain durability across
+Host restart. Protocol, runtime and real-process tests cover the changed
+boundary; process-tree termination remains the existing supervisor's job.
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 3bfab39d1..b218fb4ca 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -746,8 +746,8 @@ submitted Markdown bytes in a new immutable
structured title/question in `plan_approvals`, and moves the live state to
`awaiting_approval`.
-Plan/Goal requests retain Write/Edit declarations and, when subagents are
-configured, the Task/TaskWait/TaskList/TaskStop declarations. They are marked
+Plan/Goal requests retain Write/Edit and TaskWait/TaskList/TaskStop declarations,
+plus Task when subagents are configured. They are marked
unavailable in the active mode. The execution allowlist remains unchanged:
prohibited calls are blocked before extension call hooks and handlers, and a
handler retained across a mode change rechecks that mode before executing.
@@ -964,9 +964,9 @@ not override the parent session by default: they follow `auto` completely
their normal approval behavior. An explicit builtin or user scope remains an
intentional override.
-**Tools (ADR 0089).** Delegation is a four-tool lifecycle, built only in Agent
-mode and only when the catalog is non-empty, and all four belong to the Agent
-core set rather than the on-demand catalog of §7.1:
+**Tools (ADR 0089).** Task requires a non-empty subagent catalog. The three
+job controls are always declared and belong to the Agent core set rather than
+the on-demand catalog of §7.1. Execution of all four is restricted to Agent mode:
- `Task(agent, task, description?, model?, resume?)` — validates its arguments (an
unknown `agent`, an empty `task`, an unresolvable model pin and a definition
@@ -1618,10 +1618,8 @@ execution activation rules:
- Agent: `Skill` whenever the skill catalog is non-empty (D404, ADR 0230) — the
`# Skills` section and a user-typed `/skill:<skill-id>` both ask the model to call
it, and a tool that is missing from the schema cannot be called at all
-- Agent: `Task`, `TaskWait`, `TaskList`, and `TaskStop` as well, whenever the
- subagent catalog is non-empty (§5f) — a capability the model has to go
- looking for is one it will not use, and the delegation lifecycle is worth
- the extra schemas per request
+- Agent: `TaskWait`, `TaskList` and `TaskStop` for session jobs, plus `Task`
+ when the subagent catalog is non-empty (§5f)
- Plan: `Read`, `Glob`, `Grep`, `BrowserPreview`, and `Bash`
- both modes: `ToolSearch` when at least one deferred capability exists
@@ -1962,3 +1960,44 @@ retries and images retain physical account/model attribution. Nested immediate
parent and owning Task remain distinct. The migration does not add coding-agent
AgentSession, Codemode or virtual routing. See the coding-agent design review for
future adoption conditions.
+
+
+### Session job controls
+
+Agent-mode TaskWait, TaskList and TaskStop are available even without configured
+subagents. Task itself still requires a subagent catalog. Plan/Goal retain the
+declarations for conversation compatibility and reject their execution.
+
+Bash background startup and Task startup return an additive `job: {kind, id}`
+reference, where kind is `bash` or `delegation`; their original identifiers
+remain available. TaskList preserves `delegations` and `resumable` and adds
+`backgroundJobs: {supported, tasks}`. Delegation summaries also include job
+references. Bash summaries contain no logs and bound command text to 1 KiB.
+
+TaskWait and TaskStop accept one explicit `job`. Combining it with
+`delegationIds`, `mode` or `minCompleted` is an error. Omitting it preserves
+the existing delegation defaults, including stop-all-delegates. A Bash job
+never joins those implicit target sets. A legacy backgroundTaskId can be
+addressed as `{kind: "bash", id: backgroundTaskId}`.
+
+For Bash, TaskWait returns a snapshot with state, nullable exitCode,
+stopRequested, separate stdout/stderr tails and truncated. Each stream is
+bounded to 8 KiB at UTF-8 boundaries; truncation also reflects Host ring loss.
+Reads are repeatable and do not consume desktop output. The wait defaults to
+600 seconds and accepts 1–900 seconds. `details.status` describes the wait
+(completed/timeout/interrupted), independently of the job's state. New input
+interrupts the wait; cancelling the parent releases it without stopping Bash.
+TaskStop returns completed or stopPending based on the actual snapshot. A
+stopRequested flag alone does not confirm termination.
+
+The wait deadline includes capability discovery and in-flight requests.
+On timeout the tool returns its last observed snapshot. If the first
+observation has not arrived, it returns the job reference with
+`snapshotAvailable: false` and no process state. Transcript rows identify
+explicit Bash targets and include background commands in mixed job lists.
+
+Bash is still owned by Host and does not auto-deliver completion or keep the
+parent turn open. Delegation report delivery and resumability retain their
+existing lifecycle. Runtime capability probing is connection-scoped; older
+Hosts and remote workspaces explicitly report Bash controls unavailable,
+while delegation controls remain usable. Transport and Host failures propagate.
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 2dbe87384..146865327 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -981,3 +981,21 @@ Naming:
before the trusted desktop executes the request. Plan/Goal remain denied even
under Auto. See [image generation](21-image-generation.md) for cancellation,
limits and result semantics.
+
+
+### Model access to background commands
+
+In Agent mode the model can list, wait for and stop its session's background
+Bash jobs through TaskList, TaskWait and TaskStop. The job's Host record is the
+same record read by the desktop. Runtime supplies its bound session identity;
+model arguments cannot select a different session. Host requires an existing
+local Agent-mode session and resolves both read and stop by (sessionId, id).
+Unknown and foreign IDs return the same NOT_FOUND error.
+
+Waiting never kills a process. A one-second bounded Host observation can be
+abandoned on input or cancellation, and no global AppState lock is held during
+the wait. Terminal notification follows output draining. Explicit stop reuses
+the supervisor's process-tree cleanup and reports its actual settled outcome
+or a still-running snapshot with stopRequested. The model's reads and desktop
+reads do not consume each other's logs. Retention and Host restart still bound
+how long a finished ID can be queried.
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index f01b1b614..3dee196b1 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1568,3 +1568,39 @@ both content and states untouched. Success persists each affected review state.
The old `review.rollback` contract remains unchanged. Both rollback methods
participate in Host file-resource exclusion and re-resolve the session root after
admission. Both new operations reject remote workspaces. See [ADR 0341](../../adr/0341-explicit-reviewed-file-actions.md).
+
+
+### Session-scoped background job RPC
+
+Only these model proxy methods are allowlisted. The desktop's global
+backgroundTasks methods remain outside the model proxy.
+
+| Method | Parameters | Result |
+| --- | --- | --- |
+| backgroundJobs.capabilities | sessionId | {version: 1, supported: true} |
+| backgroundJobs.list | sessionId | {tasks: BackgroundJobSummary[]} |
+| backgroundJobs.wait | sessionId, id, timeoutMs? | BackgroundJobSnapshot |
+| backgroundJobs.stop | sessionId, id, timeoutMs? | BackgroundJobSnapshot |
+
+Each method requires an existing local Agent-mode session. Foreign and missing
+job IDs both return NOT_FOUND. Invalid parameters return INVALID_PARAMS; a
+contract-mode session returns PERMISSION_DENIED. Calls never rebind an existing
+job. Session identity comes from the runtime rather than model tool arguments.
+
+timeoutMs is an integer in 0–1000, default 0. Wait observes a per-job completion
+signal without holding AppState. Stop signals the existing supervisor before
+observing completion. The returned state is authoritative; stopRequested is
+only an acknowledgement, and a running job may need another wait. Snapshot
+metadata includes job {kind: bash, id}, command (at most 1024 UTF-8 bytes),
+elapsedMs, state, nullable exitCode and stopRequested. Wait/stop additionally
+return stdout and stderr (each at most 8192 UTF-8 bytes), and truncated for
+either Host retention loss or this observation's clipping.
+
+Terminal state and final drained output share one snapshot lock. Reads do not
+consume output. An observer holds a job handle until the bounded request ends,
+so pruning cannot split an admitted read. After waiting the session is checked
+again. An abandoned RPC never stops a process. Capability absence is an older
+Host limitation; other failures must not be silently converted into an empty
+list. This additive protocol preserves the existing desktop RPC shapes.
+
+The supervisor gives an observed exit precedence over a pending stop and preserves that exit outcome while draining the pipes. Elapsed time freezes when the final state and output are published.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7a0131836..2fe9bc552 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -20008,3 +20008,26 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)
- Specs: ADR 0043; runtime RPC/storage specs; component spec Round review reader.
- Milestone: maintenance. Traceability: acceptance criteria 1–9 of the approved
native round-review enhancement map to this scenario and the tests above.
+
+
+### E2E-TOOLS-session-background-jobs
+
+- Entry: build shared/agent-runtime/host-runtime and Host, then run
+ `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-session-background-jobs.mjs`.
+- Environment: isolated Host data and workspace, production runtime and pi tool
+ loop, deterministic localhost HTTP provider. No external model account.
+- Sequence: start a background test, list it, wait for failure and Unicode
+ output tails; start a service, time out waiting, call default stop, then
+ explicitly stop and wait for the same job.
+- Expected: correct exit code and both final tails, per-stream UTF-8 limits,
+ cross-session list/read/stop isolation, timeout and default stop preserve Bash,
+ explicit stop reaches terminal state, repeated reads and desktop output agree.
+ Plan-mode access is rejected.
+- Runtime tests cover new input/parent abort during a pending Host wait, late
+ Host rejection, old Host/remote capability behavior, mixed selector rejection,
+ existing delegation controls and registration without a subagent catalog.
+- Host tests cover pre-settled observation, repeatable output, Unicode clipping,
+ ownership lookup, idempotent stop and stop acknowledgement before termination.
+ Existing Windows child/grandchild cleanup tests remain required; record native
+ failures separately from protocol success.
+- Exercise a late stop with an already reaped child before the supervisor drains the pipes. Verify the original exit outcome, final output and stable elapsed time across reads. Stall capability discovery or the first Host observation to exercise the overall wait deadline. The Electron transcript fixture renders a pending Bash stop and a mixed job list.
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index f243e7f26..db3ee758f 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -671,8 +671,8 @@ Frontmatter 新增 `permission: inherit | ask | accept-edits | auto`(默认
`ui-designer` 也默认继承父会话:`auto` 下跟随父会话自动放行,而 `ask` 和
`accept-edits` 仍保留各自的审批边界。显式声明的内置或用户作用域仍然是一次有意的覆盖。
-**工具(ADR 0089)。** 委托是四个工具的生命周期,仅在 Agent 模式下且目录
-非空时构建,四个工具都属于 Agent 核心集而不是第 7.1 节的按需目录:
+**工具(ADR 0089)。** Task 要求非空子代理目录,三个作业控制工具始终声明。
+它们属于 Agent 核心集,仅在 Agent 模式允许执行。
- `Task(agent, task, description?, model?)` — 验证其参数(未知的 `agent`、空的
`task`、无法解析的模型引脚以及工具全部不可用的定义,各自返回一个工具
@@ -1051,9 +1051,7 @@ sidecar 构建了一个完整的工具注册表,但它不会序列化每个工
- Agent:`Read`、`Bash`、`Edit` 和 `Write`(匹配 pi 的编码代理核心)
- Agent:只要技能目录非空,`Skill` 也在核心集中(D404、ADR 0230)——`# Skills`
段落与用户输入的 `/skill:<skill-id>` 都要求模型调用它,而模式中缺失的工具根本无法被调用
-- Agent:当子代理目录非空时,`Task`、`TaskWait`、`TaskList` 和
- `TaskStop` 也是如此 (§5f) — 模型必须寻找的能力是它不会使用的能力,
- 委托生命周期值得每个请求的额外模式
+- Agent:始终提供 `TaskWait`、`TaskList`、`TaskStop`,子代理目录非空时另提供 `Task`(§5f)。
- Plan:`Read`、`Glob`、`Grep`、`BrowserPreview` 和 `Bash`
- 两种模式:`ToolSearch`(当至少存在一种延迟功能时)
@@ -1305,3 +1303,17 @@ content. The durable transcript is unchanged and completed tools are not
re-executed. Other malformed context remains subject to strict validation.
Tool token estimates are optional telemetry: an invalid call identity must not
prevent the corresponding terminal tool event from being delivered.
+
+### 会话作业控制
+
+Agent 模式下,即使没有配置子代理,也提供 TaskWait、TaskList 和 TaskStop。Task 仍要求子代理目录。Plan/Goal 保留声明以兼容对话历史,执行时拒绝这些工具。
+
+后台 Bash 和 Task 的启动结果新增 `job: {kind, id}`,kind 为 bash 或 delegation,同时保留原 ID 字段。TaskList 保留 delegations 和 resumable,增加 backgroundJobs 的 supported 和 tasks;委派摘要也包含 job。Bash 列表不带日志,命令文字限制为 1 KiB。
+
+TaskWait/TaskStop 接受单个显式 job,与 delegationIds、mode、minCompleted 混用会报错。无 job 时保留原委派默认集合。旧 backgroundTaskId 可写成 `{kind: "bash", id: backgroundTaskId}`。
+
+Bash 等待返回状态、可空退出码、停止请求标记及分别最多 8 KiB 的 stdout/stderr 尾部,按 UTF-8 边界截断。truncated 同时表示 Host 历史丢失或本次截断。查询可重复且不消耗桌面日志。等待默认 600 秒,接受 1–900 秒;details.status 为 completed、timeout 或 interrupted,与作业状态独立。新输入或父回合取消只结束等待。停止返回 completed 或 stopPending,stopRequested 本身不代表进程已退出。
+
+Bash 由 Host 管理,完成后不自动投递结果或延长父回合。原委派报告交付和恢复规则继续生效。能力按连接探测;旧 Host 和远程工作区明确返回后台 Bash 控制不可用,委派操作仍可用。其他传输或 Host 错误会正常呈现。
+
+等待时限包含能力探测和在途请求。超时返回最近一次已观察的快照。如果首次观察尚未返回,工具返回作业引用和 `snapshotAvailable: false`,省略进程状态。聊天记录区分显式 Bash 目标,混合作业列表显示后台命令数量。
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index 8001292a5..279d30ce7 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -765,3 +765,9 @@ sidecar 不附加覆盖,委托使用会话的有效权限模式;因此父会
## 图片生成与编辑
`GenerateImages` 是仅供 Agent 使用的高风险能力,可信桌面执行请求前必须由 host-core 授权。即使处于 Auto,Plan/Goal 仍被拒绝。取消、限制和结果语义见[图片生成规格](/zh-CN/spec/03-runtime/21-image-generation)。
+
+### 模型访问后台命令
+
+Agent 模式下,模型通过 TaskList、TaskWait、TaskStop 管理本会话的后台 Bash,桌面和模型读取同一 Host 作业记录。runtime 带入已绑定会话身份,模型参数不能选择其他会话。Host 要求会话存在、属于本地并处于 Agent 模式,按 sessionId 与 id 校验读取和停止。未知与其他会话的 ID 均返回 NOT_FOUND。
+
+等待不会终止进程。单次 Host 观察最多一秒,可在新输入或取消时放弃,等待期间不持有全局状态锁。终态通知在输出收尾后发出。显式停止复用主管的进程树清理,并返回实际终态或带 stopRequested 的运行中快照。查询互不消耗日志。有限历史与 Host 重启仍限制旧 ID 可查询的时间。
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 5042c9b11..8735e6d81 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -1161,3 +1161,22 @@ tools.execute 增加可选 fileBatchTicket,绑定封存后的单次调用。
由 Host 决定,客户端不提供权威身份。工作区绑定变化返回 TOOL_CONTEXT_CHANGED;文件身份
或地址变化在写入前失败。Close/过期不能释放运行中的磁盘任务,不自动重放失败或结果不明
的写。生命周期和限制见 Host 文件准入 ADR。
+
+### 会话范围的后台作业 RPC
+
+模型代理仅放行下列接口,桌面的全局 backgroundTasks 接口不在代理白名单内。
+
+| 方法 | 参数 | 结果 |
+| --- | --- | --- |
+| backgroundJobs.capabilities | sessionId | {version: 1, supported: true} |
+| backgroundJobs.list | sessionId | {tasks: BackgroundJobSummary[]} |
+| backgroundJobs.wait | sessionId, id, timeoutMs? | BackgroundJobSnapshot |
+| backgroundJobs.stop | sessionId, id, timeoutMs? | BackgroundJobSnapshot |
+
+接口要求已存在的本地 Agent 会话。未知与其他会话作业均返回 NOT_FOUND;非法参数返回 INVALID_PARAMS;合约模式返回 PERMISSION_DENIED。作业归属不变,会话身份取自 runtime,模型工具参数不提供会话选择。
+
+timeoutMs 为 0–1000 的整数,默认 0。wait 观察单作业完成信号,释放全局锁;stop 先向已有主管发停止信号,再观察结果。返回 state 为实际状态,stopRequested 仅表示请求已发出。摘要含 job、最多 1024 UTF-8 字节的 command、elapsedMs、state、可空 exitCode 和 stopRequested。wait/stop 另含分别最多 8192 UTF-8 字节的 stdout/stderr,以及表示 Host 缓冲丢失或本次裁剪的 truncated。
+
+终态和最终输出在同一作业锁下读取。读操作不消耗输出,进行中的观察持有作业句柄直至有界请求结束,历史淘汰不会拆散这次读取。等待后重新校验会话。放弃请求不会停止进程。旧 Host 能力缺失会明确报告,其他错误不会转为空列表。桌面原 RPC 结构保持兼容。
+
+监管任务优先处理已观察到的进程退出,并在排空管道时保留退出结果。终态和最终输出发布时固定运行耗时。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index e2158e488..4ff89606f 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -10288,3 +10288,13 @@ Electron 一侧——工具自动签发、指示器、"停止"中止轮次、绘
回报成功。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)。
- **状态**:NOT RUN —— 需要真机运行。
+
+### E2E-TOOLS-session-background-jobs
+
+- 构建 shared、agent-runtime、host-runtime 与 Host 后,运行 `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-session-background-jobs.mjs`。
+- 使用隔离 Host 数据、工作目录、生产 runtime/pi 循环与本地 HTTP 模型夹具。
+- 后台启动测试,列举并等待失败结果;启动常驻命令,等待超时、无参停止,再显式停止并等待。
+- 验证退出码、两路末尾输出、UTF-8 上限、跨会话列表/读/停隔离、超时和无参停止保留 Bash、显式停止终态、重复查询及桌面输出一致;拒绝 Plan 模式。
+- runtime 测试补充新输入和父回合取消、延迟 RPC 错误、旧 Host/远程能力缺失、混合选择器拒绝、原委派控制及无子代理配置的工具注册。
+- Host 测试覆盖先完成后等待、重复读取、Unicode 截断、归属查找、幂等停止与停止请求待确认。Windows 子孙进程清理测试仍须执行,原生失败单独报告。
+- 在子进程已退出、监管任务尚未排空管道时请求停止,检查原退出结果、最终输出和重复读取的耗时。延迟能力探测或第一次 Host 观察,检查等待总时限。Electron 会话记录用例渲染尚待确认的 Bash 停止请求和混合作业列表。
diff --git a/packages/agent-runtime/src/background-job-tools.test.ts b/packages/agent-runtime/src/background-job-tools.test.ts
new file mode 100644
index 000000000..cc48efde4
--- /dev/null
+++ b/packages/agent-runtime/src/background-job-tools.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import { Type } from "@earendil-works/pi-ai";
+import { buildJobTools } from "./background-job-tools.js";
+import type { RuntimeHost } from "./host-client.js";
+
+afterEach(() => vi.useRealTimers());
+
+function fixture(remote = false) {
+ const delegate = (name: string): AgentTool => ({
+ name, label: name, description: name,
+ parameters: Type.Object({ delegationIds: Type.Optional(Type.Array(Type.String())) }),
+ execute: vi.fn(async () => ({ content: [{ type: "text" as const, text: "delegate report" }], details: { delegations: [] } })),
+ });
+ const delegates = { wait: delegate("TaskWait"), list: delegate("TaskList"), stop: delegate("TaskStop") };
+ const snapshot = { job: { kind: "bash", id: "process" }, state: "failed", exitCode: 1, stdout: "", stderr: "assertion failed", truncated: false };
+ const dispatch = vi.fn(async (method: string, _params: unknown): Promise<unknown> => {
+ if (method === "backgroundJobs.capabilities") return { version: 1, supported: true };
+ if (method === "backgroundJobs.list") return { tasks: [snapshot] };
+ return snapshot;
+ });
+ const host: RuntimeHost = { call: async <T>(method: string, params?: unknown) => await dispatch(method, params) as T };
+ const [wait, list, stop] = buildJobTools(delegates, {
+ host, sessionId: "owner", remote, defaultTimeoutSeconds: 600, maxTimeoutSeconds: 900,
+ wait: (run, signal) => run(signal ?? new AbortController().signal),
+ });
+ return { delegates, dispatch, snapshot, wait, list, stop };
+}
+
+describe("session job controls", () => {
+ it("lists, reads and stops the same explicit Bash job with the bound session", async () => {
+ const { list, wait, stop, dispatch, snapshot } = fixture();
+ const listed = await list.execute("list", {});
+ expect(listed.details).toMatchObject({ delegations: [], backgroundJobs: { supported: true, tasks: [snapshot] } });
+ expect((await wait.execute("wait", { job: snapshot.job })).details).toEqual({ status: "completed", job: snapshot });
+ expect((await stop.execute("stop", { job: snapshot.job, sessionId: "foreign" })).details).toEqual({ status: "completed", job: snapshot });
+ expect(dispatch).toHaveBeenLastCalledWith("backgroundJobs.stop", { sessionId: "owner", id: "process", timeoutMs: 1000 });
+ });
+
+ it("preserves default delegation targets and routes an explicit delegation", async () => {
+ const { wait, stop, dispatch, delegates } = fixture();
+ await wait.execute("wait", {});
+ await stop.execute("stop", {});
+ expect(dispatch).not.toHaveBeenCalled();
+ await wait.execute("one", { job: { kind: "delegation", id: "delegate" }, timeoutSeconds: 12 });
+ expect(delegates.wait.execute).toHaveBeenLastCalledWith("one", { job: undefined, delegationIds: ["delegate"], timeoutSeconds: 12 }, undefined, undefined);
+ await stop.execute("one", { job: { kind: "delegation", id: "delegate" } });
+ expect(delegates.stop.execute).toHaveBeenLastCalledWith("one", { delegationIds: ["delegate"] }, undefined, undefined);
+ });
+
+ it.each(["delegationIds", "mode", "minCompleted"])("rejects mixed selectors before dispatch (%s)", async key => {
+ const { wait, stop, dispatch } = fixture();
+ const args = { job: { kind: "bash", id: "process" }, [key]: [] };
+ await expect(wait.execute("wait", args)).rejects.toThrow("cannot be combined");
+ await expect(stop.execute("stop", args)).rejects.toThrow("cannot be combined");
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("returns running at the deadline and never requests a stop", async () => {
+ vi.useFakeTimers();
+ const { wait, dispatch, snapshot } = fixture();
+ dispatch.mockImplementation(async method => {
+ if (method.endsWith("capabilities")) return { version: 1, supported: true };
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ return { ...snapshot, state: "running", exitCode: null };
+ });
+ const result = wait.execute("wait", { job: snapshot.job, timeoutSeconds: 2 });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect((await result).details).toMatchObject({ status: "timeout", job: { state: "running", exitCode: null } });
+ expect(dispatch.mock.calls.map(call => call[0])).not.toContain("backgroundJobs.stop");
+ });
+
+ it("abandons an in-flight wait promptly without stopping, and observes a late failure", async () => {
+ const { wait, dispatch, snapshot } = fixture();
+ let fail: (error: Error) => void = () => {};
+ dispatch.mockImplementation(async method => method.endsWith("capabilities")
+ ? { version: 1, supported: true }
+ : new Promise((_, reject) => { fail = reject; }));
+ const controller = new AbortController();
+ const result = wait.execute("wait", { job: snapshot.job }, controller.signal);
+ const assertion = expect(result).rejects.toMatchObject({ errorCode: "TOOL_ABORTED" });
+ await vi.waitFor(() => expect(dispatch).toHaveBeenCalledWith("backgroundJobs.wait", expect.anything()));
+ controller.abort();
+ await assertion;
+ fail(new Error("late transport failure"));
+ await Promise.resolve();
+ expect(dispatch.mock.calls.map(call => call[0])).not.toContain("backgroundJobs.stop");
+ });
+
+ it.each(["capabilities", "wait"])("includes a stalled %s RPC in the first wait deadline", async stalled => {
+ vi.useFakeTimers();
+ const { wait, dispatch, snapshot } = fixture();
+ let rejectLate!: (error: Error) => void;
+ dispatch.mockImplementation(async method => method.endsWith(stalled)
+ ? new Promise((_, reject) => { rejectLate = reject; })
+ : { version: 1, supported: true });
+ const pending = wait.execute("wait", { job: snapshot.job, timeoutSeconds: 1 });
+ await vi.advanceTimersByTimeAsync(1000);
+ const result = await pending;
+ expect(result.details).toEqual({ status: "timeout", job: snapshot.job, snapshotAvailable: false });
+ rejectLate(new Error("late transport error"));
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(dispatch.mock.calls.map(([method]) => method)).toEqual(stalled === "capabilities"
+ ? ["backgroundJobs.capabilities"] : ["backgroundJobs.capabilities", "backgroundJobs.wait"]);
+ });
+
+ it("reports remote and older Hosts as unavailable while retaining delegation results", async () => {
+ for (const remote of [true, false]) {
+ const { list, wait, stop, dispatch, snapshot } = fixture(remote);
+ dispatch.mockRejectedValue({ code: -32601 });
+ expect((await list.execute("list", {})).details).toMatchObject({ delegations: [], backgroundJobs: { supported: false, tasks: [] } });
+ await expect(wait.execute("wait", { job: snapshot.job })).rejects.toThrow("does not support");
+ await expect(stop.execute("stop", { job: snapshot.job })).rejects.toThrow("does not support");
+ if (remote) expect(dispatch).not.toHaveBeenCalled();
+ }
+ });
+
+ it("propagates transport errors instead of presenting an empty list", async () => {
+ const { list, dispatch } = fixture();
+ dispatch.mockRejectedValue(new Error("connection lost"));
+ await expect(list.execute("list", {})).rejects.toThrow("connection lost");
+ });
+});
diff --git a/packages/agent-runtime/src/background-job-tools.ts b/packages/agent-runtime/src/background-job-tools.ts
new file mode 100644
index 000000000..dfe1c0ce5
--- /dev/null
+++ b/packages/agent-runtime/src/background-job-tools.ts
@@ -0,0 +1,171 @@
+/** Model job controls route to their existing owner; only Bash crosses Host RPC. */
+import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
+import type { TObject } from "typebox";
+import { Type } from "@earendil-works/pi-ai";
+import {
+ BACKGROUND_JOBS_VERSION,
+ type BackgroundJobSnapshot,
+ type BackgroundJobSummary,
+ type JobReference,
+} from "@pi-desktop/shared";
+import type { RuntimeHost } from "./host-client.js";
+
+const jobSchema = Type.Object({
+ kind: Type.Union([Type.Literal("bash"), Type.Literal("delegation")]),
+ id: Type.String({ minLength: 1 }),
+}, { additionalProperties: false, description: "An explicit job returned by Bash, Task or TaskList." });
+
+function record(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function target(params: unknown): JobReference | undefined {
+ if (!record(params) || params.job === undefined) return undefined;
+ const job = params.job;
+ if (!record(job) || (job.kind !== "bash" && job.kind !== "delegation") ||
+ typeof job.id !== "string" || !job.id.trim() || Object.keys(job).some(key => key !== "id" && key !== "kind")) {
+ throw new Error("job must contain a kind (bash or delegation) and a nonempty id");
+ }
+ if (["delegationIds", "mode", "minCompleted"].some(key => params[key] !== undefined)) {
+ throw new Error("job cannot be combined with delegationIds, mode or minCompleted");
+ }
+ return { kind: job.kind, id: job.id };
+}
+
+/** Observe late rejections and release the listener on either completion path. */
+function abortable<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const abort = () => reject(Object.assign(new Error("Job wait aborted"), { errorCode: "TOOL_ABORTED" }));
+ signal?.addEventListener("abort", abort, { once: true });
+ work.then(resolve, reject).finally(() => signal?.removeEventListener("abort", abort));
+ if (signal?.aborted) {
+ signal.removeEventListener("abort", abort);
+ abort();
+ }
+ });
+}
+
+type Result = AgentToolResult<unknown>;
+type Options = {
+ host: RuntimeHost;
+ sessionId: string;
+ remote: boolean;
+ defaultTimeoutSeconds: number;
+ maxTimeoutSeconds: number;
+ /** The runtime also interrupts this wait when new steering input arrives. */
+ wait: (run: (signal: AbortSignal) => Promise<Result>, signal?: AbortSignal) => Promise<Result>;
+};
+
+function observation(snapshot: BackgroundJobSnapshot, status: string): Result {
+ return {
+ content: [{ type: "text", text: JSON.stringify({ status, ...snapshot }) }],
+ details: { status, job: snapshot },
+ };
+}
+
+export function buildJobTools(
+ delegates: { wait: AgentTool; list: AgentTool; stop: AgentTool },
+ options: Options,
+): AgentTool[] {
+ let capability: Promise<boolean> | undefined;
+ const supported = () => capability ??= (async () => {
+ if (options.remote) return false;
+ try {
+ const response = await options.host.call("backgroundJobs.capabilities", { sessionId: options.sessionId });
+ return record(response) && response.version === BACKGROUND_JOBS_VERSION && response.supported === true;
+ } catch (error) {
+ if (record(error) && (error.code === -32601 || error.errorCode === "METHOD_NOT_FOUND" ||
+ (record(error.rpc) && error.rpc.code === -32601))) return false;
+ capability = undefined;
+ throw error;
+ }
+ })();
+
+ const requireSupported = async () => {
+ if (!await supported()) throw new Error("This Host/workspace does not support background Bash job controls.");
+ };
+ const call = <T>(method: string, params: Record<string, unknown> = {}) =>
+ options.host.call<T>(method, { ...params, sessionId: options.sessionId });
+
+ const wait: AgentTool = {
+ ...delegates.wait,
+ description: `${delegates.wait.description}\nFor a background Bash command, pass its job reference ({kind: "bash", id: backgroundTaskId}). Returns state, exitCode and bounded stdout/stderr tails. Timeout or interrupted waiting leaves the process running. Bash completion is not automatically delivered; call TaskWait again when needed. Omit job to keep the existing subagent defaults.`,
+ parameters: Type.Object({ ...(delegates.wait.parameters as TObject).properties, job: Type.Optional(jobSchema) }),
+ execute: async (id, input, signal, update) => {
+ const params = record(input) ? input : {};
+ const job = target(params);
+ if (!job) return delegates.wait.execute(id, params, signal, update);
+ if (job.kind === "delegation") {
+ return delegates.wait.execute(id, { ...params, job: undefined, delegationIds: [job.id] }, signal, update);
+ }
+ const seconds = params.timeoutSeconds ?? options.defaultTimeoutSeconds;
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds < 1 || seconds > options.maxTimeoutSeconds) {
+ throw new Error(`timeoutSeconds must be between 1 and ${options.maxTimeoutSeconds}`);
+ }
+ return options.wait(async waitSignal => {
+ if (waitSignal.aborted) throw Object.assign(new Error("Job wait aborted"), { errorCode: "TOOL_ABORTED" });
+ const budgetMs = Math.ceil(seconds * 1000);
+ const deadline = performance.now() + budgetMs;
+ const timerAbort = new AbortController();
+ const signal = AbortSignal.any([waitSignal, timerAbort.signal]);
+ const timer = setTimeout(() => timerAbort.abort(), budgetMs);
+ let snapshot: BackgroundJobSnapshot | undefined;
+ try {
+ await abortable(requireSupported(), signal);
+ while (!signal.aborted && performance.now() < deadline) {
+ // Read once immediately so a deadline during a later long poll
+ // can return the last observed state.
+ const timeoutMs = snapshot ? Math.min(1000, Math.ceil(deadline - performance.now())) : 0;
+ snapshot = await abortable(call<BackgroundJobSnapshot>("backgroundJobs.wait", {
+ id: job.id, timeoutMs: Math.max(0, timeoutMs),
+ }), signal);
+ if (snapshot.state !== "running") return observation(snapshot, "completed");
+ }
+ } catch (error) {
+ if (!timerAbort.signal.aborted || waitSignal.aborted ||
+ !record(error) || error.errorCode !== "TOOL_ABORTED") throw error;
+ } finally {
+ clearTimeout(timer);
+ }
+ if (snapshot) return observation(snapshot, "timeout");
+ const result = { status: "timeout", job, snapshotAvailable: false };
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: result };
+ }, signal);
+ },
+ };
+ const list: AgentTool = {
+ ...delegates.list,
+ description: `${delegates.list.description}\nAlso lists this session's retained background Bash jobs when supported. Use the returned job reference with TaskWait or TaskStop. Finished Bash history is bounded and expires when the Host restarts.`,
+ execute: async (...args) => {
+ const result = await delegates.list.execute(...args);
+ const available = await supported();
+ const tasks = available ? (await call<{ tasks: BackgroundJobSummary[] }>("backgroundJobs.list")).tasks : [];
+ const details = record(result.details) ? result.details : {};
+ return {
+ ...result,
+ content: [...result.content, { type: "text", text: available
+ ? `Background Bash jobs: ${JSON.stringify(tasks)}`
+ : "Background Bash job controls are unavailable on this Host/workspace." }],
+ details: { ...details, backgroundJobs: { supported: available, tasks } },
+ };
+ },
+ };
+ const stop: AgentTool = {
+ ...delegates.stop,
+ description: `${delegates.stop.description}\nPass job to stop one explicit Bash or delegation job. Omitting job never stops Bash processes. A Bash stopRequested flag acknowledges a request; only the returned terminal state confirms the outcome.`,
+ parameters: Type.Object({ ...(delegates.stop.parameters as TObject).properties, job: Type.Optional(jobSchema) }),
+ execute: async (id, input, signal, update) => {
+ const params = record(input) ? input : {};
+ const job = target(params);
+ if (!job) return delegates.stop.execute(id, params, signal, update);
+ if (job.kind === "delegation") {
+ return delegates.stop.execute(id, { delegationIds: [job.id] }, signal, update);
+ }
+ await requireSupported();
+ if (signal?.aborted) throw Object.assign(new Error("Job stop aborted before dispatch"), { errorCode: "TOOL_ABORTED" });
+ const snapshot = await call<BackgroundJobSnapshot>("backgroundJobs.stop", { id: job.id, timeoutMs: 1000 });
+ return observation(snapshot, snapshot.state === "running" ? "stopPending" : "completed");
+ },
+ };
+ return [wait, list, stop];
+}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 1e6e76ef8..02aa22a62 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -3825,6 +3825,9 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {
"Skill",
"EnterPlanMode",
"EnterGoalMode",
+ "TaskWait",
+ "TaskList",
+ "TaskStop",
"new_context",
"ToolSearch",
]);
@@ -14430,3 +14433,63 @@ describe("parallel policy tool provenance", () => {
} finally { internal.extensionRunner = undefined; await runtime.dispose(); }
});
});
+
+
+describe("background Bash job waits in the production runtime", () => {
+ it.each(["steer", "abort"] as const)("releases a wait on %s without stopping the process", async action => {
+ let entered!: () => void;
+ const waiting = new Promise<void>(resolve => { entered = resolve; });
+ let finish!: (value: unknown) => void;
+ const host = { call: vi.fn(async (method: string) => {
+ if (method === "backgroundJobs.capabilities") return { version: 1, supported: true };
+ if (method === "backgroundJobs.wait") {
+ entered();
+ return new Promise(resolve => { finish = resolve; });
+ }
+ return {};
+ }) };
+ const runtime = createRuntime({ host, subagents: [] });
+ const requests: AgentMessage[][] = [];
+ const internals = runtime as unknown as {
+ models: { streamSimple: (model: unknown, context: { messages: AgentMessage[] }) => ReturnType<typeof createAssistantMessageEventStream> };
+ };
+ internals.models = { streamSimple: (_model, context) => {
+ requests.push([...context.messages]);
+ const first = requests.length === 1;
+ const message = assistantMessage({
+ content: first
+ ? [{ type: "toolCall", id: "wait-bash", name: "TaskWait", arguments: { job: { kind: "bash", id: "process" } } }]
+ : [{ type: "text", text: "Handled new input." }],
+ stopReason: first ? "toolUse" : "stop",
+ }) as unknown as AssistantMessage;
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: message });
+ stream.push({ type: "done", reason: first ? "toolUse" : "stop", message });
+ stream.end(message);
+ });
+ return stream;
+ } };
+ const running = runtime.prompt("Wait for the background test.", "user", "job-turn");
+ try {
+ await waiting;
+ if (action === "steer") {
+ runtime.steer({ text: "Handle this correction." }, "job-turn", {
+ id: "new-user", role: "user", content: "Handle this correction.",
+ createdAt: "2026-11-05T00:00:00.000Z", steering: true,
+ });
+ } else {
+ await runtime.abort();
+ }
+ await running;
+ if (action === "steer") {
+ expect(JSON.stringify(requests.at(-1))).toContain("Interrupted by new user input");
+ expect(JSON.stringify(requests.at(-1))).toContain("Handle this correction.");
+ }
+ expect(host.call.mock.calls.some(([method]) => method === "backgroundJobs.stop")).toBe(false);
+ finish({ state: "running" });
+ } finally {
+ await runtime.dispose();
+ }
+ });
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 379630f24..1d48ee542 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1,3 +1,4 @@
+import { buildJobTools } from "./background-job-tools.js";
import {
MAX_MUTATION_RECOVERY_FAILURES, BASH_PATCH_FAILURE_KEY,
RECOVERABLE_MUTATION_ERROR_CODES, mutationFailureKey, isPatchCommand,
@@ -1382,7 +1383,7 @@ function commandShellToolDescription(
shellSyntaxGuidance(shell),
`The session scratch directory variable is ${shellScratchVariable(shell)}.`,
`An optional timeout from 1 to ${MAX_COMMAND_TIMEOUT_SECONDS} seconds may be supplied; without it, the command defaults to a 60-second timeout.`,
- `Set runInBackground: true for long-lived processes the user needs after the turn ends (dev servers, watchers, builds). A background call returns a backgroundTaskId immediately, survives turn aborts and timeouts, and its output is visible in the composer's running-tasks bar; do not set it for commands whose output the current turn depends on.`,
+ `Set runInBackground: true for long-lived processes the user needs after the turn ends (dev servers, watchers, builds). A background call returns a backgroundTaskId immediately, survives turn aborts and timeouts, and its output is visible in the composer's running-tasks bar. In Agent mode on supported local Hosts, use TaskList to find it, TaskWait with its job reference to read results, and TaskStop with that reference to stop it. Background completion does not automatically resume the model.`,
...(formattedScratch ? [`The session scratch directory is ${formattedScratch}.`] : []),
].join(" ");
}
@@ -4087,18 +4088,41 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.mode === "agent"
? [this.buildEnterModeTool("plan"), this.buildEnterModeTool("goal")]
: [this.buildSubmitTool(this.mode)];
- // Keep configured delegation declarations stable across mode changes.
- // Contract modes reject execution before handlers can spawn/control a
- // delegate; publishing a schema never grants delegation permission.
- const subagentTools =
- this.subagents.length
- ? [
- this.buildSubagentTool(),
- this.buildSubagentWaitTool(),
- this.buildSubagentListTool(),
- this.buildSubagentStopTool(),
- ]
- : [];
+ // Job controls are available without subagents. Contract modes retain
+ // declarations for history but reject execution before these handlers.
+ const subagentTools = [
+ ...(this.subagents.length ? [this.buildSubagentTool()] : []),
+ ...buildJobTools({
+ wait: this.buildSubagentWaitTool(),
+ list: this.buildSubagentListTool(),
+ stop: this.buildSubagentStopTool(),
+ }, {
+ host: this.host,
+ sessionId: this.sessionId,
+ remote: Boolean(this.remoteWorkspace),
+ defaultTimeoutSeconds: TASKWAIT_DEFAULT_TIMEOUT_SECONDS,
+ maxTimeoutSeconds: TASKWAIT_MAX_TIMEOUT_SECONDS,
+ wait: async (run, signal) => {
+ const steeringAbort = new AbortController();
+ this.steeringWaitAbort = steeringAbort;
+ if (this.pendingSteering.size) steeringAbort.abort();
+ try {
+ return await run(signal ? AbortSignal.any([signal, steeringAbort.signal]) : steeringAbort.signal);
+ } catch (error) {
+ const interruptedByInput = isRecord(error) && error.errorCode === "TOOL_ABORTED" &&
+ steeringAbort.signal.aborted && !signal?.aborted &&
+ !this.runCancelled && !this.disposed && !this.turnHadError;
+ if (!interruptedByInput) throw error;
+ return {
+ content: [{ type: "text", text: "Interrupted by new user input. The background command keeps running; handle the user's message before waiting again." }],
+ details: { status: "interrupted" },
+ };
+ } finally {
+ if (this.steeringWaitAbort === steeringAbort) this.steeringWaitAbort = undefined;
+ }
+ },
+ }),
+ ];
for (const tool of subagentTools) this.builtinTools.add(tool);
const contextTools = this.compactionEnabled
? [this.buildContextCompactionTool()]
@@ -5168,11 +5192,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
content: [
{
type: "text",
- text: `Delegation ${delegationId} started: the ${definition.name} subagent is working in the background${label ? ` (${label})` : ""}. Continue your own independent work, then call TaskWait with this delegationId to converge, or TaskStop to stop it.`,
+ text: `Delegation ${delegationId} started: the ${definition.name} subagent is working in the background${label ? ` (${label})` : ""}. Continue your own independent work, then call TaskWait with this delegationId to converge, or TaskStop to stop it. Job reference: ${JSON.stringify({ kind: "delegation", id: delegationId })}.`,
},
],
details: {
delegationId,
+ job: { kind: "delegation", id: delegationId },
agent: definition.name,
status: "running",
startedAt,
@@ -5873,7 +5898,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
delegations.length === 0
? "No subagents have been started in this session."
: delegations
- .map((record) => `- ${formatDelegationHeartbeat(record)}`)
+ .map((record) => `- ${formatDelegationHeartbeat(record)}; job=${JSON.stringify({ kind: "delegation", id: record.delegationId })}`)
.join("\n"),
this.delegationChains.resumableBlock({ runningDelegationIds }),
]
@@ -5882,7 +5907,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
return {
content: [{ type: "text", text }],
details: {
- delegations: delegations.map(delegationSummary),
+ delegations: delegations.map(record => ({ ...delegationSummary(record), job: { kind: "delegation", id: record.delegationId } })),
resumable: resumable.map((chain) => ({
agent: chain.agentName,
delegationId: chain.latestDelegationId,
diff --git a/packages/host-runtime/src/agent-sidecar.ts b/packages/host-runtime/src/agent-sidecar.ts
index 59e9ab08f..eefe0c471 100644
--- a/packages/host-runtime/src/agent-sidecar.ts
+++ b/packages/host-runtime/src/agent-sidecar.ts
@@ -50,6 +50,10 @@ export type VendorAuthResolver = (input: {
// session, so it cannot reach a credential the session was not launched with.
const HOST_PROXY_ALLOWED = new Set([
"tools.execute",
+ "backgroundJobs.capabilities",
+ "backgroundJobs.list",
+ "backgroundJobs.wait",
+ "backgroundJobs.stop",
"tools.fileBatchCapabilities",
"tools.fileBatchRegister",
"tools.fileBatchSeal",
diff --git a/packages/host-runtime/src/file-batch-bridge.test.ts b/packages/host-runtime/src/file-batch-bridge.test.ts
index cd57f3e29..b98d7e831 100644
--- a/packages/host-runtime/src/file-batch-bridge.test.ts
+++ b/packages/host-runtime/src/file-batch-bridge.test.ts
@@ -25,3 +25,19 @@ it("forwards only the explicit file batch methods through the production sidecar
await expect(sidecar.call("probe", { method: "settings.set", params: {} })).rejects.toMatchObject({ code: -32601 });
expect(calls).toHaveLength(5);
});
+
+
+it("allows session job methods but denies global desktop process access", async () => {
+ sidecar = new AgentSidecar({ launch: { command: process.execPath, args: ["-e", source] }, onStderr: () => {} });
+ const host: SidecarHostLink = {
+ call: async <T>() => ({ ok: true }) as T,
+ onNotification: () => () => {}, onExit: () => () => {},
+ };
+ sidecar.setHost(host);
+ for (const method of ["capabilities", "list", "wait", "stop"]) {
+ await expect(sidecar.call("probe", { method: `backgroundJobs.${method}`, params: { sessionId: "owner" } })).resolves.toEqual({ ok: true });
+ }
+ for (const method of ["list", "output", "stop"]) {
+ await expect(sidecar.call("probe", { method: `backgroundTasks.${method}`, params: { id: "foreign" } })).rejects.toMatchObject({ code: -32601 });
+ }
+});
diff --git a/packages/shared/src/background-jobs.ts b/packages/shared/src/background-jobs.ts
new file mode 100644
index 000000000..0f5706442
--- /dev/null
+++ b/packages/shared/src/background-jobs.ts
@@ -0,0 +1,19 @@
+/** Model-facing references preserve the execution owner's native identifier. */
+export type JobReference = { kind: "bash" | "delegation"; id: string };
+
+export type BackgroundJobSummary = {
+ job: JobReference;
+ command: string;
+ state: "running" | "exited" | "failed" | "stopped";
+ elapsedMs: number;
+ exitCode: number | null;
+ stopRequested: boolean;
+};
+
+export type BackgroundJobSnapshot = BackgroundJobSummary & {
+ stdout: string;
+ stderr: string;
+ truncated: boolean;
+};
+
+export const BACKGROUND_JOBS_VERSION = 1;
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 17cb048b2..4dd78b868 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,6 +1,7 @@
export * from "./activation.js";
export * from "./protocol.js";
export * from "./file-batches.js";
+export * from "./background-jobs.js";
export * from "./errors.js";
export * from "./rpc-error.js";
export * from "./certificate-errors.js";
diff --git a/scripts/e2e-session-background-jobs.mjs b/scripts/e2e-session-background-jobs.mjs
new file mode 100644
index 000000000..1eaa5276b
--- /dev/null
+++ b/scripts/e2e-session-background-jobs.mjs
@@ -0,0 +1,168 @@
+// Deterministic local provider -> production agent loop -> real Host/processes.
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { dirname, delimiter, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { createSession, configureSession, beginTurn, endTurn } from "./e2e/session.mjs";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+const artifacts = join(root, ".cache", "session-background-jobs");
+await mkdir(artifacts, { recursive: true });
+const scratch = await mkdtemp(join(artifacts, "run-"));
+const workspace = join(scratch, "workspace");
+await mkdir(workspace);
+await writeFile(join(workspace, "failure.cjs"), `
+process.stdout.write('中文'.repeat(100000) + '\\nstdout-final\\n');
+process.stderr.write('错误'.repeat(100000) + '\\nassertion-failed-final\\n');
+process.exitCode = 1;
+`);
+await writeFile(join(workspace, "service.cjs"), `
+console.log('service-ready');
+setInterval(() => {}, 1000);
+`);
+const host = new Host(resolveHostBinary(), join(scratch, "data"), {
+ quiet: true,
+ env: { PATH: [dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter) },
+});
+let round = 0;
+let failedJob, serviceJob, foreign;
+let fixtureFailure;
+const calls = [];
+const toolResult = (body, id) => {
+ const message = body.messages.find(message => message.role === "tool" && message.tool_call_id === id);
+ assert(message, `missing tool result ${id}`);
+ return message.content;
+};
+const parseResult = (body, id) => JSON.parse(toolResult(body, id));
+const server = createServer(async (req, res) => {
+ try {
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ const body = JSON.parse(raw);
+ let name, args;
+ switch (round++) {
+ case 0:
+ name = "Bash"; args = { command: "node failure.cjs", runInBackground: true };
+ break;
+ case 1:
+ failedJob = parseResult(body, "call-1").job;
+ assert.equal(failedJob.kind, "bash");
+ name = "TaskList"; args = {};
+ break;
+ case 2:
+ assert(toolResult(body, "call-2").includes(failedJob.id));
+ name = "TaskWait"; args = { job: failedJob, timeoutSeconds: 20 };
+ break;
+ case 3: {
+ const result = parseResult(body, "call-3");
+ assert.equal(result.state, "failed");
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.truncated, true);
+ assert(result.stdout.endsWith("stdout-final\n"));
+ assert(result.stderr.endsWith("assertion-failed-final\n"));
+ for (const stream of [result.stdout, result.stderr]) {
+ assert(Buffer.byteLength(stream) <= 8192);
+ assert(!stream.includes("\uFFFD"));
+ }
+ name = "Bash"; args = { command: "node service.cjs", runInBackground: true };
+ break;
+ }
+ case 4:
+ serviceJob = parseResult(body, "call-4").job;
+ for (const method of ["wait", "stop"]) {
+ await assert.rejects(host.call(`backgroundJobs.${method}`, { sessionId: foreign.id, id: serviceJob.id }), error => error.errorCode === "NOT_FOUND");
+ await assert.rejects(host.call(`backgroundJobs.${method}`, { sessionId: foreign.id, id: "missing" }), error => error.errorCode === "NOT_FOUND");
+ }
+ assert.deepEqual((await host.call("backgroundJobs.list", { sessionId: foreign.id })).tasks, []);
+ // A pending wait must leave the Host available for another request.
+ let observed = false;
+ const pending = host.call("backgroundJobs.wait", { sessionId: owner.id, id: serviceJob.id, timeoutMs: 1000 })
+ .then(result => { observed = true; return result; });
+ await host.call("backgroundJobs.capabilities", { sessionId: owner.id });
+ assert.equal(observed, false, "waiting must release the global Host lock");
+ assert.equal((await pending).state, "running");
+ name = "TaskWait"; args = { job: serviceJob, timeoutSeconds: 1 };
+ break;
+ case 5:
+ assert.equal(parseResult(body, "call-5").status, "timeout");
+ assert.equal(parseResult(body, "call-5").state, "running");
+ name = "TaskStop"; args = {};
+ break;
+ case 6:
+ assert.equal((await host.call("backgroundJobs.wait", { sessionId: owner.id, id: serviceJob.id })).state, "running");
+ name = "TaskStop"; args = { job: serviceJob };
+ break;
+ case 7:
+ assert.equal(parseResult(body, "call-7").stopRequested, true);
+ name = "TaskWait"; args = { job: serviceJob, timeoutSeconds: 20 };
+ break;
+ case 8:
+ assert.equal(parseResult(body, "call-8").state, "stopped");
+ break;
+ default: throw new Error("Unexpected provider round");
+ }
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const delta = (value, finish = null) => res.write(`data: ${JSON.stringify({
+ id: `fixture-${round}`, object: "chat.completion.chunk", created: 1,
+ model: body.model, choices: [{ index: 0, delta: value, finish_reason: finish }],
+ })}\n\n`);
+ if (name) {
+ calls.push(name);
+ delta({ role: "assistant", tool_calls: [{ index: 0, id: `call-${round}`, type: "function", function: { name, arguments: JSON.stringify(args) } }] });
+ delta({}, "tool_calls");
+ } else {
+ delta({ role: "assistant", content: "Verified test failure and stopped service." });
+ delta({}, "stop");
+ }
+ res.end("data: [DONE]\n\n");
+ } catch (error) {
+ fixtureFailure = error;
+ res.writeHead(400);
+ res.end(String(error));
+ }
+});
+await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+let runtime, owner, turnId;
+const events = [];
+try {
+ await host.start();
+ owner = await createSession(host, workspace, "Job owner");
+ foreign = await createSession(host, workspace, "Other session");
+ for (const session of [owner, foreign]) await configureSession(host, session, "agent", "auto");
+ if (process.platform === "win32") await host.call("settings.set", { defaultCommandShell: "cmd" });
+ const { effective: shell } = await host.call("commandShells.list");
+ turnId = await beginTurn(host, owner.id);
+ runtime = new DesktopAgentRuntime({
+ host, sessionId: owner.id, turnId, mode: "agent", projectPath: workspace,
+ provider: {
+ id: "fixture", name: "Local fixture", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,
+ modelId: "fixture", apiKey: "", authKind: "none", apiStyle: "chat_completions",
+ supportsReasoning: false, supportedThinkingLevels: ["off"],
+ },
+ commandShell: shell, thinkingLevel: "off", subagents: [],
+ onEvent: envelope => events.push(envelope.event),
+ });
+ await runtime.prompt("Run the background fixtures and inspect their outcomes.", "fixture-user", turnId);
+ if (fixtureFailure) throw fixtureFailure;
+ assert.equal(round, 9);
+ assert.equal(events.some(event => event.type === "error"), false);
+ const repeated = await host.call("backgroundJobs.wait", { sessionId: owner.id, id: failedJob.id });
+ assert.equal(repeated.exitCode, 1);
+ assert(repeated.stderr.endsWith("assertion-failed-final\n"));
+ const desktop = await host.call("backgroundTasks.output", { id: failedJob.id });
+ assert.equal(desktop.exitCode, repeated.exitCode);
+ assert(desktop.stderr.endsWith(repeated.stderr));
+ await endTurn(host, turnId);
+ turnId = undefined;
+ await configureSession(host, owner, "plan", "auto");
+ await assert.rejects(host.call("backgroundJobs.wait", { sessionId: owner.id, id: failedJob.id }), error => error.errorCode === "PERMISSION_DENIED");
+ console.log(JSON.stringify({ ok: true, calls, rounds: round, shell: shell.id, checks: ["real model tool loop", "no subagents configured", "failure and bounded Unicode output", "cross-session read/stop denied", "wait releases Host lock", "timeout preserves process", "default stop preserves Bash", "explicit stop settles", "repeated reads", "desktop parity", "plan mode denied"] }, null, 2));
+} finally {
+ await runtime?.dispose();
+ if (turnId) await endTurn(host, turnId, "aborted").catch(() => {});
+ await host.stop();
+ await new Promise(resolve => server.close(resolve));
+}
diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsx
index d1fb47a19..1c8d90736 100644
--- a/scripts/e2e/transcript-render.tsx
+++ b/scripts/e2e/transcript-render.tsx
@@ -548,6 +548,37 @@ globalThis.transcriptRenderProbe = async () => {
"a standalone Bash row must not render an activity group",
);
+ // A stop acknowledgement can arrive while the command is still running.
+ // Verify the transcript head, where a completed tool call used to say
+ // "Stopped subagents" even when there were no delegates.
+ const job = { kind: "bash", id: "background-command" };
+ render([
+ message("jobs-user", "user", "Check the background test"),
+ message("jobs-stop", "tool", "", {
+ toolName: "TaskStop", toolCallId: "jobs-stop", toolStatus: "success",
+ toolArgs: { job },
+ toolResult: { details: { status: "stopPending", job: {
+ job, command: "npm test", state: "running", stopRequested: true,
+ } } },
+ }),
+ message("jobs-list", "tool", "", {
+ toolName: "TaskList", toolCallId: "jobs-list", toolStatus: "success",
+ toolResult: { details: {
+ delegations: [{ agent: "reviewer", delegationId: "review", status: "running" }],
+ backgroundJobs: { supported: true, tasks: [{ job }] },
+ } },
+ }),
+ ]);
+ const jobHead = (id: string, selector = ".tool-row-header") => container.querySelector(
+ `[data-message-id="${id}"] ${selector}`,
+ )?.textContent;
+ assert(jobHead("jobs-stop", ".tool-row-name") === "Task Stop",
+ "the Bash stop title must not report a completed subagent stop");
+ assert(jobHead("jobs-stop")?.includes("npm test") && jobHead("jobs-stop")?.includes("Stopping"),
+ "the acknowledged Bash stop must identify a command that is still stopping");
+ assert(jobHead("jobs-list")?.includes("reviewer") && jobHead("jobs-list")?.includes("1 background"),
+ "the mixed job list must identify both its delegate and its background command count");
+
// Keep Task's own message stable: a later lifecycle result must still
// update its terminal status and timing (#238), unlike unrelated text.
const start = Date.now() - 12_000;