From d05444604e60e4c22cbc33ec41d8976d6a103999 Mon Sep 17 00:00:00 2001 From: omesser Date: Sun, 13 Sep 2026 23:24:26 +0300 Subject: [PATCH 1/2] fix(harness): Tell a missing CLI from a dead child The spawn's ENOENT now reaches `attach` as its own condition, so a binary `PATH` has not got skips the respawn ladder and Settings names the file that was looked for - `argv[0]`, which is `npx` and not `codex` for the presets whose two argvs disagree. #659. Co-Authored-By: Claude Opus 5 --- src-tauri/src/acp_wire.rs | 99 ++++++++++++++++++++++------------- src-tauri/src/harness.rs | 107 ++++++++++++++++++++++++++++++++------ src-tauri/src/settings.rs | 50 +++++++++++++++--- 3 files changed, 197 insertions(+), 59 deletions(-) diff --git a/src-tauri/src/acp_wire.rs b/src-tauri/src/acp_wire.rs index 976ceee09..f5bcc57a7 100644 --- a/src-tauri/src/acp_wire.rs +++ b/src-tauri/src/acp_wire.rs @@ -180,6 +180,27 @@ pub enum TurnError { Failed(String), } +/// Why no wire came back from a spawn. +/// +/// `Missing` is the one no respawn can mend: `PATH` has no such file, so there +/// is no child to wait for and the backoff ladder would only re-time the same +/// failure every five minutes (#659). Told apart by `ErrorKind`, never by the +/// text - `(os error 2)` is the platform's wording and the user's locale's. +#[derive(Debug)] +pub enum SpawnError { + Missing, + Failed(String), +} + +impl SpawnError { + fn start(why: std::io::Error) -> Self { + match why.kind() { + std::io::ErrorKind::NotFound => Self::Missing, + _ => Self::Failed(format!("could not start: {why}")), + } + } +} + enum Msg { Open { load: Option, @@ -214,23 +235,27 @@ pub struct Wire { impl Wire { /// Spawn `command`, connect, and `initialize`. Blocks for at most /// `timeout`; the thread lives on for as long as the child does. - pub fn spawn(command: Command, timeout: Duration, on_event: OnEvent) -> Result { + pub fn spawn( + command: Command, + timeout: Duration, + on_event: OnEvent, + ) -> Result { let (tx, rx) = mpsc::unbounded_channel(); let (ready_tx, ready_rx) = sync_mpsc::channel(); let (done_tx, done) = sync_mpsc::channel(); thread::Builder::new() .name("acp-wire".into()) .spawn(move || run(command, rx, ready_tx, done_tx, on_event)) - .map_err(|why| format!("could not start the wire thread: {why}"))?; + .map_err(|why| SpawnError::Failed(format!("could not start the wire thread: {why}")))?; let handshake = match ready_rx.recv_timeout(timeout) { Ok(Ok(handshake)) => handshake, Ok(Err(why)) => return Err(why), Err(RecvTimeoutError::Timeout) => { let _ = tx.send(Msg::Shutdown); - return Err("did not answer initialize".to_string()); + return Err(SpawnError::Failed("did not answer initialize".to_string())); } Err(RecvTimeoutError::Disconnected) => { - return Err("exited before initialize".to_string()) + return Err(SpawnError::Failed("exited before initialize".to_string())) } }; Ok(Self { @@ -348,7 +373,7 @@ impl Drop for Wire { fn run( command: Command, rx: mpsc::UnboundedReceiver, - ready: sync_mpsc::Sender>, + ready: sync_mpsc::Sender>, // Held, never sent on, and dropped when this function returns: that drop // is what `wait_for_exit` waits for. _done: sync_mpsc::Sender<()>, @@ -357,37 +382,36 @@ fn run( let runtime = match tokio::runtime::Builder::new_current_thread().build() { Ok(runtime) => runtime, Err(why) => { - let _ = ready.send(Err(format!("no runtime for the wire: {why}"))); + let _ = ready.send(Err(SpawnError::Failed(format!( + "no runtime for the wire: {why}" + )))); return; } }; runtime.block_on(async move { #[cfg(windows)] - let mut child = match windows_job::spawn_in_job(command) { - Ok(child) => child, - Err(why) => { - let _ = ready.send(Err(format!("could not start: {why}"))); - return; - } - }; + let spawned = windows_job::spawn_in_job(command); #[cfg(not(windows))] - let mut child = { + let spawned = { let mut async_command = async_process::Command::from(command); async_command .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::inherit()); - match async_command.spawn() { - Ok(child) => child, - Err(why) => { - let _ = ready.send(Err(format!("could not start: {why}"))); - return; - } + async_command.spawn() + }; + // Both platforms hand back the spawn's own `io::Error`, so the missing + // file is read off its kind in one place rather than two (#659). + let mut child = match spawned { + Ok(child) => child, + Err(why) => { + let _ = ready.send(Err(SpawnError::start(why))); + return; } }; let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else { - let _ = ready.send(Err("no pipes to the child".to_string())); + let _ = ready.send(Err(SpawnError::Failed("no pipes to the child".to_string()))); return; }; // What the Harness sends us, routed off the SDK's dispatch loop and @@ -432,8 +456,9 @@ fn run( }); let failed = handshake.is_err(); if let Some(ready) = ready.take() { - let _ = ready - .send(handshake.map_err(|why| format!("initialize: {}", why.message))); + let _ = ready.send(handshake.map_err(|why| { + SpawnError::Failed(format!("initialize: {}", why.message)) + })); } if !failed { serve(&cx, rx, incoming_rx, &on_event).await; @@ -443,10 +468,10 @@ fn run( ) .await; if let Some(ready) = ready.take() { - let _ = ready.send(Err(match outcome { + let _ = ready.send(Err(SpawnError::Failed(match outcome { Ok(()) => "exited before initialize".to_string(), Err(why) => why.message, - })); + }))); } // The Harness may have been started through `npx`, which does not // reliably die on stdin EOF; kill the process group rather than @@ -1158,7 +1183,7 @@ mod windows_job { /// closing the post-spawn race. pub(super) fn spawn_in_job( mut command: std::process::Command, - ) -> Result { + ) -> Result { use std::os::windows::process::CommandExt; let job = unsafe { @@ -1196,9 +1221,11 @@ mod windows_job { let mut child = match async_command.spawn() { Ok(child) => child, - Err(e) => { + // Handed on as it came: `SpawnError::start` reads the kind, and a + // `format!` around it would turn a missing file into prose (#659). + Err(why) => { unsafe { CloseHandle(job) }; - return Err(format!("spawn failed: {e}")); + return Err(why); } }; @@ -1211,9 +1238,9 @@ mod windows_job { eprintln!("harness: OpenProcess failed for pid {pid}; resuming without job"); if resume_primary_thread(pid).is_err() { let _ = child.kill(); - return Err(format!( + return Err(std::io::Error::other(format!( "OpenProcess failed and resume failed for pid {pid}; child killed" - )); + ))); } return Ok(child); } @@ -1228,7 +1255,7 @@ mod windows_job { ); if resume_primary_thread(pid).is_err() { let _ = child.kill(); - return Err(format!("AssignProcessToJobObject failed and resume failed for pid {pid}; child killed")); + return Err(std::io::Error::other(format!("AssignProcessToJobObject failed and resume failed for pid {pid}; child killed"))); } return Ok(child); } @@ -1236,9 +1263,9 @@ mod windows_job { if let Err(why) = resume_primary_thread(pid) { CloseHandle(job); let _ = child.kill(); - return Err(format!( + return Err(std::io::Error::other(format!( "ResumeThread failed for pid {pid}: {why}; child killed" - )); + ))); } match JOBS.lock() { @@ -1321,16 +1348,14 @@ mod windows_job { fn spawn_fallback_no_job( command: std::process::Command, why: &str, - ) -> Result { + ) -> Result { eprintln!("harness: {why}; spawning without Job Object (grandchildren may linger)"); let mut async_command = async_process::Command::from(command); async_command .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::inherit()); - async_command - .spawn() - .map_err(|e| format!("fallback spawn failed: {e}")) + async_command.spawn() } pub(super) fn terminate_job(pid: u32) { diff --git a/src-tauri/src/harness.rs b/src-tauri/src/harness.rs index 0bb6d944f..3e6b74559 100644 --- a/src-tauri/src/harness.rs +++ b/src-tauri/src/harness.rs @@ -25,7 +25,9 @@ use ai_buddy_core::director::{Completer, Reply, Wake, WakeRequest}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use crate::acp_wire::{Event, Handshake, McpChoice, McpLaunch, OpenError, TurnError, Wire}; +use crate::acp_wire::{ + Event, Handshake, McpChoice, McpLaunch, OpenError, SpawnError, TurnError, Wire, +}; use crate::action_log; pub use crate::acp_wire::PermissionAsk; @@ -235,6 +237,10 @@ pub struct HarnessInspect { /// Whether `initialize` offered HTTP MCP. #166 branches on it. pub mcp_http: bool, pub alive: bool, + /// The binary `PATH` has not got, when that is why nothing is running. + /// Told apart from a child that died because no respawn mends it and the + /// sentence a user needs is a different one (#659). + pub missing: Option, /// What the last turn came back with, when it came back with an error, and /// `None` once a turn answers. A Harness that refuses every prompt is /// attached, alive and authenticated, so nothing else here tells it apart @@ -768,6 +774,21 @@ impl Session { self.charge_loss(state); } + /// Record - and say - that the binary we spawn is not on `PATH`. + /// + /// The name is `argv[0]`, the file that was actually looked for, and never + /// the preset: `codex` attaches through `npx` and logs in through `codex`, + /// so `npx` can be there while the vendor CLI is not. Naming the preset + /// would accuse whichever of the two happens to be installed (#659). + fn note_missing(&self) -> String { + let command = self.launch.argv[0].clone(); + self.update_inspect(|inspect| { + inspect.alive = false; + inspect.missing = Some(command.clone()); + }); + not_installed(&command) + } + /// The user's answer to a forwarded permission request. Never chosen here. pub fn answer_permission(&self, request: &str, option: &str) { let Some(wire) = self.current_wire() else { @@ -831,7 +852,12 @@ impl Session { } match self.spawn_and_initialize(&mut state) { Ok(wire) => wire, - Err(why) => { + // A file `PATH` has not got is not a child that might come + // back, so the ladder buys nothing but a slower way to say + // the same thing - and leaves the next wake refused for up + // to five minutes after the user installs the CLI (#659). + Err(SpawnError::Missing) => return Err(self.note_missing()), + Err(SpawnError::Failed(why)) => { self.charge_loss(&mut state); return Err(why); } @@ -853,9 +879,9 @@ impl Session { Ok((wire, id)) } - fn spawn_and_initialize(&self, state: &mut State) -> Result, String> { + fn spawn_and_initialize(&self, state: &mut State) -> Result, SpawnError> { std::fs::create_dir_all(&self.dir) - .map_err(|why| format!("{}: {why}", self.dir.display()))?; + .map_err(|why| SpawnError::Failed(format!("{}: {why}", self.dir.display())))?; let dir = self.dir.clone(); let forward = Arc::clone(&self.forward); let wire = Wire::spawn( @@ -863,7 +889,12 @@ impl Session { self.attach_timeout(), Box::new(move |event| note_event(&dir, &forward, event)), ) - .map_err(|why| format!("`{}` {why}", self.launch.line()))?; + .map_err(|why| match why { + SpawnError::Missing => SpawnError::Missing, + SpawnError::Failed(why) => { + SpawnError::Failed(format!("`{}` {why}", self.launch.line())) + } + })?; state.handshake = wire.handshake().clone(); // A fresh process is a fresh chance to sign in: the gate belonged to // the one that died. @@ -873,18 +904,20 @@ impl Session { inspect.agent = state.handshake.agent.clone(); inspect.mcp_http = state.handshake.mcp_http; inspect.alive = true; + // Installed after all, so the row must stop saying otherwise. + inspect.missing = None; }); let wire = Arc::new(wire); if !self.wanted.load(Ordering::SeqCst) { wire.shutdown(); - return Err("harness detached".to_string()); + return Err(SpawnError::Failed("harness detached".to_string())); } if let Ok(mut slot) = self.wire.lock() { *slot = Some(Arc::clone(&wire)); } if !self.wanted.load(Ordering::SeqCst) { self.shutdown(); - return Err("harness detached".to_string()); + return Err(SpawnError::Failed("harness detached".to_string())); } Ok(wire) } @@ -1344,6 +1377,13 @@ fn not_authenticated(command: &str) -> String { format!("harness not authenticated: run `{command}`") } +/// A Harness is the user's to install and never ours to ship (ADR-0018), so +/// the only fix is one the user makes outside the app - which is the same +/// shape as `not_authenticated`, and for the same reason. +fn not_installed(command: &str) -> String { + format!("`{command}` is not installed; ai-buddy does not bundle a Harness") +} + /// The command that logs the user in. The table outranks the handshake: /// adapters describe an `authMethods` entry in prose ("Use Claude /// subscription", "ChatGPT") because ACP never asked for a command. Only a @@ -2747,9 +2787,9 @@ mod tests { session.shutdown(); } - /// #437: the count `a_missing_binary_backs_off_instead_of_respawning` - /// exercises is shared with every other way a wake goes unserved, so a - /// Harness that dies is not respawned on the very next wake. + /// #437: one count is shared by every way a wake goes unserved that leaves + /// a child which might come back, so a Harness that dies is not respawned + /// on the very next wake. #[test] fn a_death_under_a_turn_buys_the_same_wait_a_failed_spawn_does() { let (fx, session) = Fixture::new("die"); @@ -2908,24 +2948,59 @@ mod tests { session.shutdown(); } + /// #659, and the reversal of what this test used to pin. A binary `PATH` + /// has not got was charged the respawn ladder, so a Harness this machine + /// never had was retried every five minutes as though the child might come + /// back, and every surface got an errno instead of a sentence. The ladder + /// itself is untouched, which the three `backoff` reads below still hold. #[test] - fn a_missing_binary_backs_off_instead_of_respawning() { + fn a_missing_binary_says_so_instead_of_backing_off() { + const NOPE: &str = "/nonexistent/ai-buddy-no-such-harness"; let dir = std::env::temp_dir().join(format!("ai-buddy-harness-{}", uuid::Uuid::new_v4())); let launch = Launch { name: "nope".into(), - argv: vec!["/nonexistent/ai-buddy-no-such-harness".into()], + argv: vec![NOPE.into()], }; let session = Session::new(launch, dir.clone(), silent()); - let first = session.complete(&asking("hi")).unwrap_err(); - assert!(first.contains("could not start"), "{first}"); - let second = session.complete(&asking("hi")).unwrap_err(); - assert!(second.contains("retrying in"), "{second}"); + assert_eq!( + session.complete(&asking("hi")), + Err(not_installed(NOPE)), + "the wake was answered with an errno" + ); + assert!( + session.state.lock().unwrap().spawn_wait_until.is_none(), + "a binary that is not there was charged a respawn wait" + ); + // No wait means the next wake asks again rather than being refused, so + // installing the CLI is picked up without a relaunch. + assert_eq!( + session.complete(&asking("hi")), + Err(not_installed(NOPE)), + "the second wake was refused by a backoff" + ); + let inspect = session.inspect(); + assert_eq!(inspect.missing.as_deref(), Some(NOPE)); + assert!(!inspect.alive); assert_eq!(session.backoff(1), BACKOFF_FIRST); assert_eq!(session.backoff(2), Duration::from_secs(10)); assert_eq!(session.backoff(40), BACKOFF_CAP); let _ = std::fs::remove_dir_all(dir); } + /// #659's subtle half: `codex` attaches through `npx` and logs in through + /// `codex`, so `argv[0]` being present says nothing about the vendor CLI + /// and the two argvs can disagree about what this machine has got. What is + /// named is the file that was looked for, never the preset. + #[test] + fn a_missing_launcher_is_not_a_missing_vendor_cli() { + let launch = launch(Some("codex")).unwrap(); + assert_eq!(launch.argv[0], "npx", "the codex preset stopped using npx"); + let dir = std::env::temp_dir().join(format!("ai-buddy-harness-{}", uuid::Uuid::new_v4())); + let session = Session::new(launch, dir, silent()); + assert_eq!(session.note_missing(), not_installed("npx")); + assert_eq!(session.inspect().missing.as_deref(), Some("npx")); + } + /// ADR-0016's newest-wins, at the Harness seam: the Poke that arrives /// under a turn takes it rather than being refused (#472). #[test] diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index c2a445f82..582a5414f 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -232,12 +232,23 @@ fn harness_state(harness: Option<&crate::harness::HarnessInspect>) -> String { // retry is the Session's own, and the row above moves the handle // now rather than at the next launch, so the wait is bounded by // the user rather than by a relaunch. - None if !attached.alive => format!( - "{} is set but not running, so the AI runs on static weights until it \ - answers. It stays the AI brain while it is set; Model API above hands the HTTP \ - endpoint back, and takes effect at once.", - attached.name - ), + // #659 splits the first of those: a machine that never had the + // CLI is waiting for an install, not for an answer, and an errno + // is not a sentence that says so. + None if !attached.alive => match &attached.missing { + Some(command) => format!( + "`{command}` is not installed, so {} is not running and the AI runs on \ + static weights. ai-buddy does not bundle a Harness - install it, or Model \ + API above hands the HTTP endpoint back.", + attached.name + ), + None => format!( + "{} is set but not running, so the AI runs on static weights until it \ + answers. It stays the AI brain while it is set; Model API above hands the \ + HTTP endpoint back, and takes effect at once.", + attached.name + ), + }, None => match &attached.session_id { Some(id) => format!("{} attached, session {id}.", attached.name), None => format!("{} attached; no session opened yet.", attached.name), @@ -3713,6 +3724,33 @@ mod tests { ); } + /// #659: the machine has not got the CLI, which is not the same state as a + /// child that stopped answering. The line has to say so in words a user can + /// act on - an errno is not one of them - and name the binary that was + /// looked for, since ai-buddy bundles no Harness (ADR-0018). + #[test] + fn a_harness_this_machine_has_not_got_names_the_command_not_an_errno() { + let missing = crate::harness::HarnessInspect { + name: "codex".to_string(), + command: "npx -y @agentclientprotocol/codex-acp@latest".to_string(), + missing: Some("npx".to_string()), + alive: false, + ..Default::default() + }; + let line = harness_state(Some(&missing)); + assert!(line.contains("not installed"), "got {line:?}"); + assert!(line.contains("`npx`"), "got {line:?}"); + assert!(line.contains("does not bundle"), "got {line:?}"); + assert!( + !line.contains("os error") && !line.to_lowercase().contains("no such file"), + "an errno is not a sentence, got {line:?}" + ); + assert!( + line.contains("Model API above"), + "the line has to name the way back, got {line:?}" + ); + } + /// #469: the handle stays authoritative while it is set, so the rows #452 /// kept live are a way back and not a live switch — handing a dead session /// to the HTTP Completer mid-run is the second mind ADR-0008 refuses. From 3ed675c8c7d8830f08a3f39b5d080bde71d75da2 Mon Sep 17 00:00:00 2001 From: omesser Date: Sun, 13 Sep 2026 23:38:57 +0300 Subject: [PATCH 2/2] fix(harness): Stop saying "not installed" about a CLI that is installed A spawn that failed for any other reason left `missing` as an earlier wake recorded it, so the Settings row kept naming a command the user had since installed and never named the adapter that actually failed. Co-Authored-By: Claude Opus 5 --- src-tauri/src/harness.rs | 43 +++++++++++++++++++++++++++++++++++----- src/chat-status.js | 13 +++++++----- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/src-tauri/src/harness.rs b/src-tauri/src/harness.rs index 3e6b74559..816448a83 100644 --- a/src-tauri/src/harness.rs +++ b/src-tauri/src/harness.rs @@ -884,12 +884,21 @@ impl Session { .map_err(|why| SpawnError::Failed(format!("{}: {why}", self.dir.display())))?; let dir = self.dir.clone(); let forward = Arc::clone(&self.forward); - let wire = Wire::spawn( + let spawned = Wire::spawn( self.launch.command(&self.dir), self.attach_timeout(), Box::new(move |event| note_event(&dir, &forward, event)), - ) - .map_err(|why| match why { + ); + // Anything but `Missing` means `PATH` had the file to run, so this is + // the one place that knows whether the CLI is installed - and it has + // to answer on the failing edge too. A machine that installs the CLI + // and then fails to initialize kept the old `missing`, so Settings + // told the user to install what they had just installed, and said + // nothing about the adapter that actually failed (#659). + if !matches!(spawned, Err(SpawnError::Missing)) { + self.update_inspect(|inspect| inspect.missing = None); + } + let wire = spawned.map_err(|why| match why { SpawnError::Missing => SpawnError::Missing, SpawnError::Failed(why) => { SpawnError::Failed(format!("`{}` {why}", self.launch.line())) @@ -904,8 +913,6 @@ impl Session { inspect.agent = state.handshake.agent.clone(); inspect.mcp_http = state.handshake.mcp_http; inspect.alive = true; - // Installed after all, so the row must stop saying otherwise. - inspect.missing = None; }); let wire = Arc::new(wire); if !self.wanted.load(Ordering::SeqCst) { @@ -1807,6 +1814,9 @@ mod tests { }; let id = message.get("id").cloned().unwrap_or(Value::Null); match message.get("method").and_then(Value::as_str) { + // A child that starts and then fails: the spawn is not + // `Missing`, which is what #659 turns on. + Some("initialize") if script == "die-initializing" => std::process::exit(3), Some("initialize") => say(json!({"jsonrpc": "2.0", "id": id, "result": { "protocolVersion": 1, "agentInfo": {"name": "fake-agent", "version": "0"}, @@ -2987,6 +2997,29 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// #659's other half: `missing` has to be cleared by a spawn that fails, + /// not only by one that works. A machine that installs the CLI and then + /// fails to initialize used to keep the old `missing`, so the Settings row + /// told the user to install what they had just installed and never named + /// the real failure. + #[test] + fn a_spawn_that_fails_for_another_reason_stops_saying_not_installed() { + let (fx, session) = Fixture::new("die-initializing"); + session.note_missing(); + let reply = session.complete(&asking("hi")); + assert!( + reply.as_ref().is_err_and(|why| why.contains("initialize")), + "{reply:?}" + ); + let inspect = session.inspect(); + assert_eq!(inspect.missing, None, "the row still says not installed"); + assert!(!inspect.alive); + // The child did start, so the ladder is still the right answer for it. + assert!(session.state.lock().unwrap().spawn_wait_until.is_some()); + session.shutdown(); + let _ = std::fs::remove_dir_all(&fx.dir); + } + /// #659's subtle half: `codex` attaches through `npx` and logs in through /// `codex`, so `argv[0]` being present says nothing about the vendor CLI /// and the two argvs can disagree about what this machine has got. What is diff --git a/src/chat-status.js b/src/chat-status.js index d02071d23..c7fca228f 100644 --- a/src/chat-status.js +++ b/src/chat-status.js @@ -165,11 +165,14 @@ function cleanName(raw) { // to press. // // The branches are `settings::harness_state`'s, in its order, so the two -// windows cannot disagree — and the order is what makes it honest. A Harness -// that is set and never came up is the state the user cannot otherwise see, -// and it is named before the session that a live one would show. The login -// command for an attached-but-not-signed-in Harness is named once here and -// never run; ADR-0010's seventh rule covers the endpoint's key. +// windows cannot disagree about a state this one is given — and the order is +// what makes it honest. #659 gave Settings one more: a Harness `PATH` has not +// got reads as `not running` here, because the Chat payload carries no +// `missing` to tell it apart, until #661 sends one. A Harness that is set and +// never came up is the state the user cannot otherwise see, and it is named +// before the session that a live one would show. The login command for an +// attached-but-not-signed-in Harness is named once here and never run; +// ADR-0010's seventh rule covers the endpoint's key. export function mindLine(opening) { if (!opening) { return "";