Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(tools): use a ten-second Bash wait within architecture limits
cauliflower0ec2417d71bf
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rsindex 4daf96bda..ce2b4ef33 100644--- a/crates/host-core/src/background_tasks.rs+++ b/crates/host-core/src/background_tasks.rs@@ -17,6 +17,7 @@ use std::time::{Duration, Instant};pub(crate) mod continuations;pub(crate) mod jobs;+pub(crate) mod yielded;use crate::tools;use serde::Serialize;@@ -408,81 +409,6 @@ fn register_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/// terminal state. Detached from any turn: only a stop request or host/// shutdown ends it.diff --git a/crates/host-core/src/background_tasks/yielded.rs b/crates/host-core/src/background_tasks/yielded.rsnew file mode 100644index 000000000..3bef4f548--- /dev/null+++ b/crates/host-core/src/background_tasks/yielded.rs@@ -0,0 +1,84 @@+//! Publish and observe foreground Bash commands that outlive their initial wait.++use std::time::Instant;+use tokio::sync::{watch, Mutex};++use super::{+ bump_change_counter, jobs, register_task, BackgroundTask, BackgroundTaskState,+ MAX_RUNNING_TASKS_PER_SESSION, MAX_RUNNING_TASKS_TOTAL, RING_MAX_BYTES,+};++/// 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();+ }+}diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex efeed3896..575bc3324 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -54,7 +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;+const BASH_INITIAL_WAIT_MS: u64 = 10_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@@ -3196,7 +3196,7 @@ async fn run_foreground_bash(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(+ match crate::background_tasks::yielded::register_yielded_task(state, &options.session_id, &command, &options.command_shell_id,started_at, cancellation.as_ref(), [stdout.result(), stderr.result()],).await {diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 4fa2affd4..f2fa19201 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -638,7 +638,7 @@ Host execution baseline:`errorCode: TOOL_FAILED` while preserving its `exitCode`, stdout, and stderrin `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+ wait up to 10s for the first response. If the command is still running and thesession has background capacity, return a `running` snapshot with boundedoutput and a Bash job reference. Host keeps the same process and its originaltimeout, and the agent can use `TaskWait` before consuming its results ordiff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex b4526390a..285ac11fc 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -1626,7 +1626,7 @@ backgroundTasks methods remain outside the model proxy.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,+waiting behind it. If the process is still running at the 10s wait boundary,Host can return a `running` background-job snapshot without an `exitCode`.The snapshot also contains `backgroundTaskId` and `commandShellId`. Theexisting `backgroundJobs.*` methods observe and stop the same process. Thediff --git a/scripts/e2e-session-background-jobs.mjs b/scripts/e2e-session-background-jobs.mjsindex 897b744cd..a674f6ffb 100644--- a/scripts/e2e-session-background-jobs.mjs+++ b/scripts/e2e-session-background-jobs.mjs@@ -37,7 +37,7 @@ const timer = setInterval(() => {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);+setTimeout(() => require("node:fs").writeFileSync("batch.txt", "Bash settled"), 11250);`);const host = new Host(resolveHostBinary(), join(scratch, "data"), {quiet: true,@@ -156,6 +156,7 @@ const server = createServer(async (req, res) => {case 15: {const running = parseResult(body, "call-15");assert.equal(running.state, "running");+ assert(running.elapsedMs >= 10_000, "the first wait must use the ten-second window");assert.equal(running.exitCode, undefined);assert.match(running.stdout, /before-yield/);assert.equal(running.job.kind, "bash");@@ -176,7 +177,7 @@ const server = createServer(async (req, res) => {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 };+ name = "Bash"; args = { command: "node service.cjs", timeout: 13 };break;}case 18: {@@ -189,8 +190,8 @@ const server = createServer(async (req, res) => {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");+ assert.match(timedOut.stderr, /timed out after 13000ms/);+ assert(timedOut.elapsedMs < 20000, "the original timeout must include the first wait");name = "Bash"; args = { command: "node service.cjs", timeout: 25 };break;}