Skip to content

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

feat(tools): yield long-running Bash after the initial wait

cauliflower5b82f16e9621
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rs
index 84aa46006..4daf96bda 100644
--- a/crates/host-core/src/background_tasks.rs
+++ b/crates/host-core/src/background_tasks.rs
@@ -365,13 +365,31 @@ fn register_spawned_task(
runner: tools::SpawnedToolRunner,
on_changed: Arc<dyn Fn() + Send + Sync>,
) -> BackgroundTask {
+ let (task, stop_rx) = register_task(
+ registry,
+ session_id,
+ command,
+ command_shell_id,
+ Instant::now(),
+ );
+ tokio::spawn(supervise(task.clone(), runner, stop_rx, on_changed));
+ task
+}
+
+fn register_task(
+ registry: &mut BackgroundTaskRegistry,
+ session_id: &str,
+ command: &str,
+ command_shell_id: &str,
+ started_at: Instant,
+) -> (BackgroundTask, watch::Receiver<bool>) {
let (stop, stop_rx) = watch::channel(false);
let task = BackgroundTask {
id: uuid::Uuid::new_v4().to_string(),
session_id: session_id.to_string(),
command: command.to_string(),
command_shell_id: command_shell_id.to_string(),
- started_at: Instant::now(),
+ started_at,
shared: Arc::new(Mutex::new(TaskShared {
state: BackgroundTaskState::Running,
exit_code: None,
@@ -387,8 +405,82 @@ fn register_spawned_task(
registry.order.push(task.id.clone());
registry.tasks.insert(task.id.clone(), task.clone());
registry.prune_finished();
- tokio::spawn(supervise(task.clone(), runner, stop_rx, on_changed));
- task
+ (task, stop_rx)
+}
+
+/// Publish an already-executing command only while its session still owns it.
+pub(crate) async fn register_yielded_task(
+ state: &Mutex<crate::state::AppState>,
+ session_id: &str,
+ command: &str,
+ shell_id: &str,
+ started_at: Instant,
+ cancellation: Option<&watch::Receiver<bool>>,
+ initial_output: [(String, bool); 2],
+) -> Result<Option<(BackgroundTask, watch::Receiver<bool>, serde_json::Value)>, String> {
+ let mut st = state.lock().await;
+ if st.shutting_down
+ || cancellation.is_some_and(|receiver| *receiver.borrow())
+ || crate::sessions::tool_policy(&st.db, session_id).map_err(|err| err.to_string())?
+ != Some(crate::sessions::ToolPolicy::Agent)
+ || st.background_tasks.running_count_for(session_id) >= MAX_RUNNING_TASKS_PER_SESSION
+ || st.background_tasks.running_count() >= MAX_RUNNING_TASKS_TOTAL
+ {
+ return Ok(None);
+ }
+ let (task, stop_rx) = register_task(
+ &mut st.background_tasks,
+ session_id,
+ command,
+ shell_id,
+ started_at,
+ );
+ // While holding the registry lock, the newly created task cell is private.
+ // Seed and snapshot it before publishing the registration to other callers.
+ let [(stdout, out_truncated), (stderr, err_truncated)] = initial_output;
+ task.append_yielded_output(true, &stdout, out_truncated)
+ .await;
+ task.append_yielded_output(false, &stderr, err_truncated)
+ .await;
+ let snapshot = jobs::snapshot(&task, true).await;
+ bump_change_counter();
+ Ok(Some((task, stop_rx, snapshot)))
+}
+
+impl BackgroundTask {
+ pub(crate) async fn append_yielded_output(&self, is_stdout: bool, text: &str, truncated: bool) {
+ if text.is_empty() && !truncated {
+ return;
+ }
+ let mut shared = self.shared.lock().await;
+ let mut offset = text.len().saturating_sub(RING_MAX_BYTES);
+ while !text.is_char_boundary(offset) {
+ offset += 1;
+ }
+ let dropped = if is_stdout {
+ shared.push_stdout(&text[offset..])
+ } else {
+ shared.push_stderr(&text[offset..])
+ };
+ shared.truncated |= truncated || dropped || offset > 0;
+ }
+
+ pub(crate) async fn finish_yielded(
+ &self,
+ state: BackgroundTaskState,
+ exit_code: Option<i32>,
+ error: Option<&str>,
+ ) {
+ if let Some(error) = error {
+ self.append_yielded_output(false, &format!("\n{error}\n"), false)
+ .await;
+ }
+ let mut shared = self.shared.lock().await;
+ shared.state = state;
+ shared.exit_code = exit_code;
+ self.settled.send_replace(Some(self.started_at.elapsed()));
+ bump_change_counter();
+ }
}
/// Drain pipes into the shared rings, honour the stop signal, and record the
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 4e353a8ba..3b9d7e206 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -4986,6 +4986,12 @@ async fn handle_request(
output_tx: Some(tx.clone()),
extra_env: worktree_env.clone(),
run_in_background: p.run_in_background,
+ yield_after_initial_wait: p.yield_after_initial_wait
+ && p.turn_id.is_some()
+ && p.delegation_id.is_none()
+ && p.permission_scope.is_none()
+ && p.mode_gate.is_none()
+ && remote_workspace.is_none(),
continuation_turn_id: if notify_on_exit {
p.turn_id.clone()
} else {
diff --git a/crates/host-core/src/rpc/remote_tools.rs b/crates/host-core/src/rpc/remote_tools.rs
index 47b07eaf9..4b73f644f 100644
--- a/crates/host-core/src/rpc/remote_tools.rs
+++ b/crates/host-core/src/rpc/remote_tools.rs
@@ -343,6 +343,7 @@ pub(super) async fn handle(
// Remote workspaces are never isolated (ADR 0329).
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
})
diff --git a/crates/host-core/src/rpc/worktree_rpc/tests.rs b/crates/host-core/src/rpc/worktree_rpc/tests.rs
index 267a2b181..d33c57afe 100644
--- a/crates/host-core/src/rpc/worktree_rpc/tests.rs
+++ b/crates/host-core/src/rpc/worktree_rpc/tests.rs
@@ -140,6 +140,7 @@ async fn isolated_session_user_path_from_create_to_delete() {
output_tx: None,
extra_env: env,
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
})),
diff --git a/crates/host-core/src/session_worktrees/lifecycle.rs b/crates/host-core/src/session_worktrees/lifecycle.rs
index 08b4d4e62..2f657a9be 100644
--- a/crates/host-core/src/session_worktrees/lifecycle.rs
+++ b/crates/host-core/src/session_worktrees/lifecycle.rs
@@ -438,6 +438,7 @@ pub(super) async fn run_setup(
output_tx: None,
extra_env: env_for(&row, Some(&project_path)),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
}),
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 83484cd97..efeed3896 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -4,7 +4,7 @@ use regex::RegexBuilder;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::fs::File;
-use std::future::pending;
+use std::future::{pending, poll_fn, Future};
use std::io::{self, BufRead, BufReader, ErrorKind, Read};
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
@@ -12,12 +12,15 @@ use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
+use std::task::Poll;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[cfg(not(test))]
use tokio::io::AsyncWriteExt;
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::process::{ChildStderr, ChildStdin, ChildStdout, Command};
-use tokio::sync::{mpsc, watch};
+use tokio::sync::{mpsc, oneshot, watch};
+
+use crate::background_tasks::{BackgroundTask, BackgroundTaskState};
use crate::workspace::{
resolve_tool_path_with_external, simple_canonicalize, ContainedRoots, ToolRoot,
@@ -51,6 +54,7 @@ pub const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
pub const MIN_BASH_TIMEOUT_MS: u64 = 1_000;
pub const MAX_BASH_TIMEOUT_MS: u64 = 21_600_000;
pub const DEFAULT_BASH_TIMEOUT_MS: u64 = 60_000;
+const BASH_INITIAL_WAIT_MS: u64 = 5_000;
pub const INTERNAL_TOOL_RUNNER_FLAG: &str = "--internal-tool-runner";
// Windows inherits the parent process' Job Object unless the child is created
// with CREATE_BREAKAWAY_FROM_JOB. The hidden runner is immediately assigned to
@@ -690,6 +694,8 @@ pub struct ToolsExecuteParams {
pub expected_command_shell_dialect: Option<String>,
#[serde(default)]
pub run_in_background: bool,
+ #[serde(default)]
+ pub yield_after_initial_wait: bool,
pub timeout_ms: Option<u64>,
/// Action names that may run in Plan or Goal mode (ADR 0211). When
/// set and non-empty, host-core admits this `plugin_*` tool in
@@ -899,6 +905,7 @@ pub struct BashExecutionOptions {
/// Start as a background task detached from the turn: no timeout, no
/// abort wiring. The caller owns the registry; see `background_tasks`.
pub run_in_background: bool,
+ pub yield_after_initial_wait: bool,
pub continuation_turn_id: Option<String>,
/// Host state the background spawn registers into. Present for RPC-driven
/// calls; `None` for test/`local` constructions that never go background.
@@ -916,6 +923,7 @@ impl BashExecutionOptions {
output_tx: None,
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
}
@@ -2768,17 +2776,27 @@ where
}
}
-fn process_output_chunk(
+async fn process_output_chunk(
chunk: OutputChunk,
stdout: &mut CapturedOutput,
stderr: &mut CapturedOutput,
notifier: &mut OutputNotifier,
+ job: Option<&BackgroundTask>,
) {
let decoded = match chunk.stream {
OutputStream::Stdout => stdout.push(&chunk.bytes),
OutputStream::Stderr => stderr.push(&chunk.bytes),
};
- notifier.push(chunk.stream, decoded);
+ if let Some(job) = job {
+ job.append_yielded_output(
+ matches!(chunk.stream, OutputStream::Stdout),
+ &decoded,
+ false,
+ )
+ .await;
+ } else {
+ notifier.push(chunk.stream, decoded);
+ }
}
async fn wait_for_cancellation(receiver: &mut Option<watch::Receiver<bool>>) -> bool {
@@ -2964,6 +2982,7 @@ async fn drain_output(
stdout: &mut CapturedOutput,
stderr: &mut CapturedOutput,
notifier: &mut OutputNotifier,
+ job: Option<&BackgroundTask>,
stdout_task: &mut tokio::task::JoinHandle<()>,
stderr_task: &mut tokio::task::JoinHandle<()>,
pid: u32,
@@ -2972,7 +2991,7 @@ async fn drain_output(
) -> Result<(), String> {
let drain = async {
while let Some(chunk) = output_rx.recv().await {
- process_output_chunk(chunk, stdout, stderr, notifier);
+ process_output_chunk(chunk, stdout, stderr, notifier, job).await;
}
*output_closed = true;
};
@@ -3078,6 +3097,45 @@ async fn tool_bash(
env_path: shell::user_login_path().map(str::to_string),
extra_env: options.extra_env.clone(),
};
+ let (early, mut early_result) = oneshot::channel();
+ let mut execution = Box::pin(run_foreground_bash(
+ config,
+ scratch.map(Path::to_path_buf),
+ command.to_owned(),
+ options,
+ timeout_ms,
+ early,
+ ));
+ let yielded = poll_fn(|cx| {
+ // Observe the handoff in the same poll that performs it. Dropping an
+ // outstanding request must not strand a registered job with no owner.
+ if let Poll::Ready(result) = execution.as_mut().poll(cx) {
+ return Poll::Ready(Err(result));
+ }
+ match std::pin::Pin::new(&mut early_result).poll(cx) {
+ Poll::Ready(Ok(result)) => Poll::Ready(Ok(result)),
+ Poll::Ready(Err(_)) | Poll::Pending => Poll::Pending,
+ }
+ })
+ .await;
+ match yielded {
+ Ok(result) => {
+ // The same future retains the process, pipes and original deadline.
+ tokio::spawn(execution);
+ Ok(result)
+ }
+ Err(finished) => finished,
+ }
+}
+
+async fn run_foreground_bash(
+ config: ToolRunnerStartConfig,
+ scratch: Option<PathBuf>,
+ command: String,
+ options: BashExecutionOptions,
+ timeout_ms: u64,
+ early: oneshot::Sender<Value>,
+) -> Result<Value, (String, String)> {
let SpawnedToolRunner {
pid,
mut ownership,
@@ -3094,8 +3152,15 @@ async fn tool_bash(
let stderr_task = tokio::spawn(read_pipe(stderr, OutputStream::Stderr, chunk_tx.clone()));
drop(chunk_tx);
+ let started_at = Instant::now();
let timeout_future = tokio::time::sleep(Duration::from_millis(timeout_ms));
tokio::pin!(timeout_future);
+ let initial_wait = tokio::time::sleep(Duration::from_millis(BASH_INITIAL_WAIT_MS));
+ tokio::pin!(initial_wait);
+ let mut may_yield = options.yield_after_initial_wait && timeout_ms > BASH_INITIAL_WAIT_MS;
+ let mut early = Some(early);
+ let mut job: Option<BackgroundTask> = None;
+ let mut background_stop = None;
let mut cancellation = options.cancellation.clone();
let mut stdout = CapturedOutput::default();
let mut stderr = CapturedOutput::default();
@@ -3105,32 +3170,64 @@ async fn tool_bash(
let stop = loop {
tokio::select! {
+ biased;
waited = &mut wait_task => {
break BashStop::Exited(waited);
}
- chunk = output_rx.recv(), if !output_closed => {
- match chunk {
- Some(chunk) => process_output_chunk(chunk, &mut stdout, &mut stderr, &mut notifier),
- None => output_closed = true,
+ _ = &mut timeout_future => {
+ match kill_and_reap(pid, &mut ownership, &mut control, &mut wait_task).await {
+ Ok(()) => break BashStop::TimedOut,
+ Err(error) => break BashStop::LifecycleFailed(error),
}
}
- _ = output_tick.tick() => {
- notifier.flush_due();
+ _ = wait_for_cancellation(&mut cancellation) => {
+ match kill_and_reap(pid, &mut ownership, &mut control, &mut wait_task).await {
+ Ok(()) => break BashStop::Aborted,
+ Err(error) => break BashStop::LifecycleFailed(error),
+ }
}
- _ = &mut timeout_future => {
+ _ = wait_for_cancellation(&mut background_stop), if job.is_some() => {
match kill_and_reap(pid, &mut ownership, &mut control, &mut wait_task).await {
- Ok(()) => break BashStop::TimedOut,
+ Ok(()) => break BashStop::Aborted,
Err(error) => break BashStop::LifecycleFailed(error),
}
}
- cancelled = wait_for_cancellation(&mut cancellation) => {
- if cancelled {
- match kill_and_reap(pid, &mut ownership, &mut control, &mut wait_task).await {
- Ok(()) => break BashStop::Aborted,
- Err(error) => break BashStop::LifecycleFailed(error),
+ _ = &mut initial_wait, if may_yield => {
+ may_yield = false;
+ let Some(state) = options.app_state.as_ref() else { continue };
+ let Some(early) = early.take() else { continue };
+ match crate::background_tasks::register_yielded_task(
+ state, &options.session_id, &command, &options.command_shell_id,
+ started_at, cancellation.as_ref(), [stdout.result(), stderr.result()],
+ ).await {
+ Ok(Some((task, stop_rx, mut result))) => {
+ // The foreground result interpreter expects exitCode only on completion.
+ if let Some(fields) = result.as_object_mut() {
+ fields.remove("exitCode");
+ }
+ result["backgroundTaskId"] = json!(task.id);
+ result["commandShellId"] = json!(options.command_shell_id);
+ result["message"] = json!("Bash is still running. Use TaskWait with its job reference before relying on the result.");
+ background_stop = Some(stop_rx);
+ job = Some(task);
+ notifier.finish();
+ notifier.tx = None;
+ let _ = early.send(result);
+ tokio::task::yield_now().await;
}
+ Ok(None) => {}
+ Err(error) => tracing::warn!(%error, "Bash could not publish a job; continuing to wait"),
+ }
+ }
+ chunk = output_rx.recv(), if !output_closed => {
+ match chunk {
+ Some(chunk) => process_output_chunk(chunk, &mut stdout, &mut stderr, &mut notifier, job.as_ref()).await,
+ None => output_closed = true,
}
}
+ _ = output_tick.tick(), if job.is_none() => {
+ notifier.flush_due();
+ }
}
};
@@ -3142,6 +3239,7 @@ async fn tool_bash(
&mut stdout,
&mut stderr,
&mut notifier,
+ job.as_ref(),
&mut stdout_task,
&mut stderr_task,
pid,
@@ -3153,10 +3251,57 @@ async fn tool_bash(
Ok(()) => stop,
Err(error) => BashStop::LifecycleFailed(error),
};
- notifier.push(OutputStream::Stdout, stdout.finish());
- notifier.push(OutputStream::Stderr, stderr.finish());
- notifier.finish();
+ let stdout_tail = stdout.finish();
+ let stderr_tail = stderr.finish();
+ if let Some(job) = job.as_ref() {
+ job.append_yielded_output(true, &stdout_tail, false).await;
+ job.append_yielded_output(false, &stderr_tail, false).await;
+ } else {
+ notifier.push(OutputStream::Stdout, stdout_tail);
+ notifier.push(OutputStream::Stderr, stderr_tail);
+ notifier.finish();
+ }
+ let was_stopped = matches!(stop, BashStop::Aborted);
+ let result = finish_foreground_bash(
+ stop,
+ timeout_ms,
+ stdout,
+ stderr,
+ scratch.as_deref(),
+ &options.command_shell_id,
+ );
+ if let Some(job) = job {
+ let (state, exit_code, error) = match &result {
+ Ok(value) => {
+ let code = value["exitCode"]
+ .as_i64()
+ .and_then(|code| i32::try_from(code).ok());
+ let state = if code == Some(0) {
+ BackgroundTaskState::Exited
+ } else {
+ BackgroundTaskState::Failed
+ };
+ (state, code, None)
+ }
+ Err((_, error)) if was_stopped => {
+ (BackgroundTaskState::Stopped, None, Some(error.as_str()))
+ }
+ Err((_, error)) => (BackgroundTaskState::Failed, None, Some(error.as_str())),
+ };
+ job.finish_yielded(state, exit_code, error).await;
+ }
+ result
+}
+
+fn finish_foreground_bash(
+ stop: BashStop,
+ timeout_ms: u64,
+ stdout: CapturedOutput,
+ stderr: CapturedOutput,
+ scratch: Option<&Path>,
+ command_shell_id: &str,
+) -> Result<Value, (String, String)> {
match stop {
BashStop::TimedOut => Err((
"TOOL_TIMEOUT".into(),
@@ -3205,7 +3350,7 @@ async fn tool_bash(
"stdout": stdout,
"stderr": stderr,
"truncated": trunc_out || trunc_err,
- "commandShellId": options.command_shell_id,
+ "commandShellId": command_shell_id,
}))
}
}
@@ -5155,6 +5300,7 @@ mod tests {
output_tx: None,
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
}),
@@ -5200,6 +5346,7 @@ mod tests {
output_tx: None,
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
}),
@@ -5240,6 +5387,7 @@ mod tests {
output_tx: None,
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
}),
@@ -5313,6 +5461,7 @@ mod tests {
output_tx: Some(tx),
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
};
@@ -5342,6 +5491,7 @@ mod tests {
output_tx: None,
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
};
@@ -5433,6 +5583,7 @@ mod tests {
output_tx: None,
extra_env: Vec::new(),
run_in_background: false,
+ yield_after_initial_wait: false,
continuation_turn_id: None,
app_state: None,
};
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 70bfde7cd..4fa2affd4 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -637,6 +637,14 @@ Host execution baseline:
- A command that exits non-zero returns `ok: false`, `isError: true`, and
`errorCode: TOOL_FAILED` while preserving its `exitCode`, stdout, and stderr
in `content` so the agent can diagnose the command without blindly retrying.
+- For a parent Agent's ordinary local Bash call at the end of a tool batch,
+ wait up to 5s for the first response. If the command is still running and the
+ session has background capacity, return a `running` snapshot with bounded
+ output and a Bash job reference. Host keeps the same process and its original
+ timeout, and the agent can use `TaskWait` before consuming its results or
+ `TaskStop` after handoff to stop it. No continuation is registered. Gates,
+ patch commands, delegated calls, earlier calls in a batch, and native remote
+ workspaces keep waiting for completion.
- `runInBackground: true` detaches the command from the turn: the call returns
`backgroundTaskId` as soon as the shell starts, no timeout applies, and the
process survives `tools.abort` and `agent.abort`. The host owns the process
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 893996af3..b4526390a 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1624,6 +1624,15 @@ backgroundTasks methods remain outside the model proxy.
| backgroundJobs.wait | sessionId, id, timeoutMs? | BackgroundJobSnapshot |
| backgroundJobs.stop | sessionId, id, timeoutMs? | BackgroundJobSnapshot |
+For a local parent Agent, the runtime can send `yieldAfterInitialWait: true`
+on a `tools.execute` Bash request when no later tool in the same batch is
+waiting behind it. If the process is still running at the 5s wait boundary,
+Host can return a `running` background-job snapshot without an `exitCode`.
+The snapshot also contains `backgroundTaskId` and `commandShellId`. The
+existing `backgroundJobs.*` methods observe and stop the same process. The
+original command timeout still applies, and a timeout after handoff appears
+as a failed job with the timeout diagnostic in its stderr tail.
+
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
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d8fbb21d7..84a5099a9 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -368,6 +368,13 @@ E2E-196b, E2E-196c, and E2E-200 (Quality, M6+).
---
+The session background jobs E2E (`scripts/e2e-session-background-jobs.mjs`)
+also covers ordinary Bash with a real Host and a deterministic local provider.
+A short command returns its original exit code. A longer command returns a
+running job, allows another tool call, and runs exactly once before
+`TaskWait` receives the terminal output and exit code. The original deadline
+and explicit stop are exercised after the initial return.
+
## 9. How AI Must Update This Doc
When adding or changing a feature that affects user-visible or protocol-visible behavior:
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index aa174d98c..c30c17716 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1474,7 +1474,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. 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. By default, background completion does not automatically resume the model. If notifyOnExit is available in the schema, it may arrange completion-triggered continuation for finite tests/builds.`,
+ `In a local Agent session, ordinary Bash can return a running job after a short wait. Do independent work if useful, then use TaskWait with the job reference before relying on the exit code or any files the command produces. The command keeps its original time limit. 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. By default, background completion does not automatically resume the model. If notifyOnExit is available in the schema, it may arrange completion-triggered continuation for finite tests/builds.`,
...(formattedScratch ? [`The session scratch directory is ${formattedScratch}.`] : []),
].join(" ");
}
@@ -2077,6 +2077,7 @@ export class DesktopAgentRuntime {
private progressTurnRerunAttempted = false;
private progressTurnRerunInProgress = false;
private suppressProgressTurnRunEnd = false;
+ private bashYieldCalls = new Set<string>();
private activeToolCalls = new Map<
string,
{ toolName: string; args: unknown; startedAt: number }
@@ -2792,12 +2793,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
if (this.deferredToolNames.has(context.toolCall.name) && !this.activeDeferredToolNames.has(context.toolCall.name)) {
return { block: true, reason: `Call ${TOOL_SEARCH_NAME} to activate ${context.toolCall.name} before using it. A tool declaration does not grant execution permission.` };
}
- const toolCalls = (context.assistantMessage.content as Array<{ type?: string }>).filter(
- (block) => block.type === "toolCall",
- );
+ const toolCalls = context.assistantMessage.content.filter((block) => block.type === "toolCall");
const transition = MODE_TRANSITION_TOOL_NAMES.has(context.toolCall.name);
const transitionInBatch = toolCalls.some((block) =>
- MODE_TRANSITION_TOOL_NAMES.has((block as { name?: string }).name ?? ""),
+ MODE_TRANSITION_TOOL_NAMES.has(block.name),
);
if (transitionInBatch && toolCalls.length !== 1) {
return {
@@ -2814,6 +2813,13 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
await this.preparePathToolCall(context);
// Composer prefetches run serially outside the assistant's tool batches.
if (!this.fileLineReadCalls.has(context.toolCall.id)) await this.registerBatchCall(context);
+ // A later tool in the same model response may depend on Bash finishing.
+ // Yield only when the next action can see and respond to the running job.
+ if (context.toolCall.name === "Bash" && this.mode === "agent"
+ && !this.remoteWorkspace && !this.delegateToolCalls.has(context.toolCall.id)
+ && toolCalls.at(-1)?.id === context.toolCall.id) {
+ this.bashYieldCalls.add(context.toolCall.id);
+ }
return undefined;
}
const enterKind = enterToolKind(context.toolCall.name);
@@ -3686,6 +3692,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
)
: undefined;
const isBash = toolName === "Bash";
+ const yieldAfterInitialWait = isBash && this.bashYieldCalls.delete(toolCallId)
+ && !this.delegateToolCalls.has(toolCallId)
+ && !this.modeGateCalls.has(toolCallId)
+ && !(isRecord(params) && (params.runInBackground === true || isPatchCommand(params.command)));
const timeoutMs = isBash ? commandTimeoutMs(params) : undefined;
let progress = "";
let progressDirty = false;
@@ -3854,6 +3864,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
expectedCommandShellId: this.commandShell.id,
expectedCommandShellDialect: this.commandShell.dialect,
timeoutMs,
+ ...(yieldAfterInitialWait ? { yieldAfterInitialWait } : {}),
...(isRecord(params) && params.runInBackground === true
? { runInBackground: true }
: {}),
@@ -9245,6 +9256,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const endedAt = Date.now();
const activeTool = this.activeToolCalls.get(event.toolCallId);
this.activeToolCalls.delete(event.toolCallId);
+ this.bashYieldCalls.delete(event.toolCallId);
if (
this.activeToolCalls.size === 0 &&
!this.disposed &&
@@ -10098,6 +10110,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.pendingMutationTermination = undefined;
this.terminatingToolCalls.clear();
this.delegateToolCalls.clear();
+ this.bashYieldCalls.clear();
this.appendedDelegationRowIds.clear();
this.gracefulStopRequested = false;
this.hostCloseUnsubscribe?.();
diff --git a/scripts/e2e-session-background-jobs.mjs b/scripts/e2e-session-background-jobs.mjs
index c64b3583a..897b744cd 100644
--- a/scripts/e2e-session-background-jobs.mjs
+++ b/scripts/e2e-session-background-jobs.mjs
@@ -1,7 +1,7 @@
// 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 { mkdir, mkdtemp, readFile, 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";
@@ -23,12 +23,28 @@ await writeFile(join(workspace, "service.cjs"), `
console.log('service-ready');
setInterval(() => {}, 1000);
`);
+await writeFile(join(workspace, "yield.cjs"), `
+const { existsSync, appendFileSync } = require("node:fs");
+appendFileSync("starts.txt", "start\\n");
+console.log("before-yield");
+const timer = setInterval(() => {
+ if (!existsSync("release.txt")) return;
+ clearInterval(timer);
+ console.log("after-yield");
+ process.exitCode = 7;
+}, 50);
+`);
+await writeFile(join(workspace, "independent.txt"), "work while Bash runs");
+await writeFile(join(workspace, "quick.cjs"), "process.exitCode = 4;\n");
+await writeFile(join(workspace, "batch.cjs"), `
+setTimeout(() => require("node:fs").writeFileSync("batch.txt", "Bash settled"), 6250);
+`);
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, failedSnapshot;
+let failedJob, serviceJob, foreign, failedSnapshot, yieldedJob;
let fixtureFailure;
const calls = [];
const toolResult = (body, id) => {
@@ -42,7 +58,7 @@ const server = createServer(async (req, res) => {
let raw = "";
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
- let name, args;
+ let name, args, laterCall;
switch (round++) {
case 0:
name = "Bash"; args = { command: "node failure.cjs", runInBackground: true };
@@ -128,6 +144,76 @@ const server = createServer(async (req, res) => {
break;
case 13:
assert.equal(parseResult(body, "call-13").state, "stopped");
+ name = "Bash"; args = { command: "node quick.cjs" };
+ break;
+ case 14: {
+ const quick = parseResult(body, "call-14");
+ assert.equal(quick.exitCode, 4);
+ assert.equal(quick.job, undefined);
+ name = "Bash"; args = { command: "node yield.cjs", timeout: 25 };
+ break;
+ }
+ case 15: {
+ const running = parseResult(body, "call-15");
+ assert.equal(running.state, "running");
+ assert.equal(running.exitCode, undefined);
+ assert.match(running.stdout, /before-yield/);
+ assert.equal(running.job.kind, "bash");
+ assert.equal(running.backgroundTaskId, running.job.id);
+ yieldedJob = running.job;
+ name = "Read"; args = { path: "independent.txt" };
+ break;
+ }
+ case 16:
+ assert.match(toolResult(body, "call-16"), /work while Bash runs/);
+ assert.equal((await host.call("backgroundJobs.wait", { sessionId: owner.id, id: yieldedJob.id })).state, "running");
+ await writeFile(join(workspace, "release.txt"), "");
+ name = "TaskWait"; args = { job: yieldedJob, timeoutSeconds: 10 };
+ break;
+ case 17: {
+ const finished = parseResult(body, "call-17");
+ assert.equal(finished.state, "failed");
+ assert.equal(finished.exitCode, 7);
+ assert.equal(finished.stdout.replaceAll("\r", ""), "before-yield\nafter-yield\n");
+ assert.equal(await readFile(join(workspace, "starts.txt"), "utf8"), "start\n");
+ name = "Bash"; args = { command: "node service.cjs", timeout: 8 };
+ break;
+ }
+ case 18: {
+ const running = parseResult(body, "call-18");
+ assert.equal(running.state, "running");
+ name = "TaskWait"; args = { job: running.job, timeoutSeconds: 15 };
+ break;
+ }
+ case 19: {
+ const timedOut = parseResult(body, "call-19");
+ assert.equal(timedOut.state, "failed");
+ assert.equal(timedOut.exitCode, null);
+ assert.match(timedOut.stderr, /timed out after 8000ms/);
+ assert(timedOut.elapsedMs < 12500, "the original timeout must include the first wait");
+ name = "Bash"; args = { command: "node service.cjs", timeout: 25 };
+ break;
+ }
+ case 20: {
+ const running = parseResult(body, "call-20");
+ assert.equal(running.state, "running");
+ yieldedJob = running.job;
+ name = "TaskStop"; args = { job: yieldedJob };
+ break;
+ }
+ case 21:
+ assert.equal(parseResult(body, "call-21").stopRequested, true);
+ name = "TaskWait"; args = { job: yieldedJob, timeoutSeconds: 10 };
+ break;
+ case 22:
+ assert.equal(parseResult(body, "call-22").state, "stopped");
+ name = "Bash"; args = { command: "node batch.cjs", timeout: 20 };
+ laterCall = { name: "Read", arguments: JSON.stringify({ path: "batch.txt" }) };
+ break;
+ case 23:
+ assert.equal(parseResult(body, "call-23").exitCode, 0);
+ assert.equal(parseResult(body, "call-23").job, undefined);
+ assert.match(toolResult(body, "call-23-later"), /Bash settled/);
break;
default: throw new Error("Unexpected provider round");
}
@@ -138,7 +224,12 @@ const server = createServer(async (req, res) => {
})}\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) } }] });
+ const toolCalls = [{ index: 0, id: `call-${round}`, type: "function", function: { name, arguments: JSON.stringify(args) } }];
+ if (laterCall) {
+ toolCalls.push({ index: 1, id: `call-${round}-later`, type: "function", function: laterCall });
+ calls.push(laterCall.name);
+ }
+ delta({ role: "assistant", tool_calls: toolCalls });
delta({}, "tool_calls");
} else {
delta({ role: "assistant", content: "Verified test failure and stopped service." });
@@ -174,7 +265,7 @@ try {
});
await runtime.prompt("Run the background fixtures and inspect their outcomes.", "fixture-user", turnId);
if (fixtureFailure) throw fixtureFailure;
- assert.equal(round, 14);
+ assert.equal(round, 24);
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);
@@ -186,7 +277,7 @@ try {
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", "plain job wait/timeout/stop", "redundant defaults wait/timeout/stop", "explicit stop settles", "repeated reads", "desktop parity", "plan mode denied"] }, null, 2));
+ 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", "plain job wait/timeout/stop", "redundant defaults wait/timeout/stop", "explicit stop settles", "repeated reads", "desktop parity", "plan mode denied", "quick Bash remains synchronous", "yielded Bash runs once and allows independent tools", "yielded Bash keeps the original deadline", "explicit stop settles a yielded Bash", "later tool in the same batch waits for Bash"] }, null, 2));
} finally {
await runtime?.dispose();
if (turnId) await endTurn(host, turnId, "aborted").catch(() => {});