Skip to content

Commit eb1da0c

Browse files
wpfleger96Duncan
authored andcommitted
fix(desktop): resolve bundled sidecar on cheap path and bound login-shell spawns (block#6904)
## Why PR block#6330 split agent harness/runtime detection into a cheap (cache-only) path and a forced (spawning) path. Two regressions followed, both surfacing as every harness showing "(not installed)" / "CLI missing" across the agent create/edit picker, Agents > Agent defaults, and Settings > Agents — blocking agent create/edit until the user clicked Install in Settings > Agents. ## Root cause One underlying bug, two victims: - **Boot false-negative.** The resolve cache is in-memory, so it starts cold on every launch. `resolve_command_cached` (the cheap path) consulted only the Buzz-managed shim dirs plus that cold cache, and `buzz_managed_command_path`'s allowlist structurally excludes `buzz-agent`. The bundled sidecar could therefore never resolve on the cheap path until a forced pass warmed the cache, so cheap-path surfaces rendered all-missing at boot. App setup never warms the cache. - **"Check again" hang.** `run_in_login_shell` used an untimeouted `Command::output()`; a wedged login shell froze the whole forced pipeline, leaving "Check again" spinning forever. ## What - `resolve_command_cached` now also calls `resolve_workspace_command`, resolving the bundled sidecar via a filesystem stat (no spawn) — the same class of work the managed-shim check already performs. `buzz-agent` can no longer report missing, even inside the boot warm window. - New `discovery/bounded_command.rs` runs any discovery child under a hard wall-clock deadline, polling with `try_wait` rather than blocking on `wait()`. Stdout and stderr are piped to two drain threads whose buffers share an aggregate `CAPTURE_LIMIT`; a breach fails closed (kill the tree, return `None`), so a noisy or hostile probe can force neither unbounded memory nor disk fill. Tree teardown runs on every exit path — timeout, error, cap breach, *and* success — because a login-shell rc file or auth CLI can legitimately background a descendant that would otherwise outlive discovery. Ownership is deliberately asymmetric: - **Unix:** the child leads its own process group (`process_group(0)`); teardown is `SIGTERM` → bounded grace → `SIGKILL` on the group. A descendant that leaves the group (`setsid`/`setpgid`) while holding a pipe is not owned and may survive one probe, but can never hang or unbound the helper: the Unix drains read nonblocking and end on `WouldBlock` once teardown sets the stop flag, so the join returns promptly without waiting on an escaped writer's EOF. - **Windows:** the child is spawned `CREATE_SUSPENDED`, assigned to a kill-on-close Job Object while frozen, then resumed. The job owns the root before any descendant can exist and is created without breakaway, so no writer can escape — a hard whole-tree guarantee, and closing the job reaps the tree even after the root has exited. Any failure to create, assign, or resume is fail-closed: the child is terminated and reaped and the spawn returns `None` (discovery treats it as command-not-found) rather than running unowned. - Each login-shell candidate is bounded by a 10s timeout via that helper, falling through to the next candidate on timeout instead of aborting the resolve. The login-shell path cache is generation-aware: a probe that loses to a concurrent refresh or lands mid-refresh returns the authoritative cached value (or re-probes under the new generation) rather than its own rejected local result, so a losing thread can never settle the UI with a PATH-missing catalog while the cache holds a fresh success. - Warm the ACP runtime catalog once at `AppShell` mount and gate the cheap-path surfaces on that pass. A module-level boot-warm state (`idle` → `pending` → `settled`/`failed`, deduped per launch) lets `useAcpRuntimesQuery` present a cold catalog as *loading* while the first forced pass runs and as a *retryable error* (carrying the probe's real reason) if it fails, instead of blessing "every harness not installed" as authoritative. A non-empty catalog always wins, so a revalidation or later failure never blanks a good list; the gate only overlays once the warm has started, so onboarding (which renders before the warm) is unaffected. Deduping per launch also fixes the previous per-remount re-fire. ## Verification Unix teardown and the drain contract are runtime-proven by `#[ignore]`-free tests that record a backgrounded descendant's real PID and assert the helper returns promptly on both the success and timeout paths without blocking on that writer. The generation-aware login-shell cache is covered by deterministic tests through a `cfg(test)` injectable probe seam that assert the function's return value under both concurrent-refresh interleavings — the losing caller returns the peer's committed success, and a mid-probe refresh forces a re-probe to the fresh value. The Windows ownership contract has no CI lane, so `bounded_command.rs` carries two `#[ignore]`-gated tests (spawn/assign race, looped; and the timeout path) for a sanctioned run on a Windows host. The boot-warm gate is covered by unit tests for the pure overlay and the `startBootWarm` failure → retry → settle lifecycle. Origin: [Buzz thread](buzz://message?channel=5ef5d5bb-643f-4b87-bbf4-e8b64585ffeb&id=a4b1c4485de4d35cff0f914d4f4211c796f44f670e76de2ef9431f7e882c906e) Fixes block#6872 Related block#6662 --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent a24fe40 commit eb1da0c

14 files changed

Lines changed: 1850 additions & 135 deletions

‎desktop/src-tauri/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ user-idle = { version = "0.6", default-features = false }
6363
plist = "1"
6464

6565
[target.'cfg(windows)'.dependencies]
66-
windows-sys = { version = "0.61", features = ["Win32_Security", "Win32_Storage_FileSystem", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_Threading", "Win32_Foundation"] }
66+
windows-sys = { version = "0.61", features = ["Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_Threading", "Win32_Foundation"] }
6767
keyring = { version = "3.6.3", default-features = false, features = ["windows-native", "vendored"], optional = true }
6868
user-idle = { version = "0.6", default-features = false }
6969

‎desktop/src-tauri/src/managed_agents/discovery.rs‎

Lines changed: 24 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
use std::io::Read;
21
use std::path::{Path, PathBuf};
32
use std::process::Command;
43
use std::sync::OnceLock;
5-
use std::time::{Duration, Instant};
4+
use std::time::Duration;
65

76
use crate::managed_agents::{
87
buzz_managed_command_path, buzz_managed_node_bin_dir, buzz_managed_npm_bin_dir,
98
AcpAvailabilityStatus, AcpRuntimeCatalogEntry, AuthStatus, CommandAvailabilityInfo,
109
HarnessSource,
1110
};
1211
mod auth_status_cache;
12+
mod bounded_command;
1313
mod login_shell;
1414
mod presets;
1515
mod runtime_metadata;
@@ -593,6 +593,16 @@ pub fn resolve_command_cached(command: &str) -> Option<PathBuf> {
593593
if let Some(managed) = resolve_buzz_managed_command(command) {
594594
return Some(managed);
595595
}
596+
// Bundled sidecars (e.g. `buzz-agent`) ship next to the app executable, so
597+
// `resolve_workspace_command` finds them with a filesystem stat and no
598+
// login-shell spawn — the same class of work the managed-shim check above
599+
// already performs. Without this the cheap path could never see the sidecar
600+
// until a forced discovery warmed the resolve cache, so `buzz-agent` (which
601+
// cannot legitimately be missing) reported "not installed" at every cold
602+
// launch across the create/edit and agent-defaults surfaces.
603+
if let Some(workspace) = resolve_workspace_command(command) {
604+
return Some(workspace);
605+
}
596606
resolve_cache()
597607
.lock()
598608
.ok()
@@ -822,10 +832,9 @@ pub(crate) fn is_npm_global_install(cmd: &str) -> bool {
822832

823833
/// Run a CLI auth probe with a 10-second process-level timeout.
824834
///
825-
/// Spawns the probe CLI as a child process. Stdout and stderr are drained on
826-
/// background threads to prevent pipe-buffer deadlock. On timeout the child is
827-
/// killed and `Unknown` is returned; no orphaned threads or processes are left
828-
/// behind. Returns `Unknown` on timeout.
835+
/// On timeout or spawn failure the child is killed and `Unknown` is returned;
836+
/// no orphaned threads or processes are left behind (see
837+
/// [`bounded_command::output_with_timeout`]).
829838
fn probe_auth_status(binary_path: &Path, probe_args: &[&str]) -> AuthStatus {
830839
use crate::managed_agents::readiness::cli_probe;
831840

@@ -836,81 +845,17 @@ fn probe_auth_status(binary_path: &Path, probe_args: &[&str]) -> AuthStatus {
836845
if let Some(ref path) = augmented_path {
837846
command.env("PATH", path);
838847
}
839-
command
840-
.stdin(std::process::Stdio::null())
841-
.stdout(std::process::Stdio::piped())
842-
.stderr(std::process::Stdio::piped());
843-
crate::util::configure_no_window(&mut command);
844-
845-
let mut child = match command.spawn() {
846-
Ok(c) => c,
847-
Err(_) => return AuthStatus::Unknown,
848+
// Window suppression is owned by `output_with_timeout`'s spawn
849+
// (`BOUNDED_CREATION_FLAGS` carries `CREATE_NO_WINDOW`); a
850+
// `configure_no_window` call here would be clobbered by that later
851+
// `creation_flags` set, so it is deliberately omitted.
852+
853+
let Some(output) = bounded_command::output_with_timeout(command, Duration::from_secs(10))
854+
else {
855+
return AuthStatus::Unknown;
848856
};
849857

850-
// Drain stdout/stderr on background threads to prevent pipe-buffer deadlock.
851-
let stdout_pipe = child.stdout.take();
852-
let stderr_pipe = child.stderr.take();
853-
854-
let stdout_thread = std::thread::spawn(move || {
855-
let mut buf = Vec::new();
856-
if let Some(mut pipe) = stdout_pipe {
857-
let _ = pipe.read_to_end(&mut buf);
858-
}
859-
});
860-
let stderr_thread = std::thread::spawn(move || {
861-
let mut buf = Vec::new();
862-
if let Some(mut pipe) = stderr_pipe {
863-
let _ = pipe.read_to_end(&mut buf);
864-
}
865-
buf
866-
});
867-
868-
// Save PID for kill-on-timeout before moving child into the wait thread.
869-
let child_pid = child.id();
870-
let (tx, rx) = std::sync::mpsc::channel();
871-
let wait_thread = std::thread::spawn(move || {
872-
let _ = tx.send(child.wait());
873-
});
874-
875-
// 10-second timeout for auth probes.
876-
let deadline = Instant::now() + Duration::from_secs(10);
877-
let exit_status = loop {
878-
let remaining = deadline.saturating_duration_since(Instant::now());
879-
if remaining.is_zero() {
880-
#[cfg(unix)]
881-
unsafe {
882-
libc::kill(child_pid as i32, libc::SIGTERM);
883-
}
884-
#[cfg(not(unix))]
885-
let _ = child_pid;
886-
drop(rx);
887-
let _ = wait_thread.join();
888-
let _ = stdout_thread.join();
889-
let _ = stderr_thread.join();
890-
return AuthStatus::Unknown;
891-
}
892-
match rx.recv_timeout(Duration::from_millis(100).min(remaining)) {
893-
Ok(Ok(status)) => break status,
894-
Ok(Err(_)) => {
895-
let _ = wait_thread.join();
896-
let _ = stdout_thread.join();
897-
let _ = stderr_thread.join();
898-
return AuthStatus::Unknown;
899-
}
900-
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
901-
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
902-
let _ = stdout_thread.join();
903-
let _ = stderr_thread.join();
904-
return AuthStatus::Unknown;
905-
}
906-
}
907-
};
908-
909-
let _ = wait_thread.join();
910-
let _ = stdout_thread.join();
911-
let stderr_bytes = stderr_thread.join().unwrap_or_default();
912-
913-
match cli_probe::classify_probe_output(&stderr_bytes, exit_status.success()) {
858+
match cli_probe::classify_probe_output(&output.stderr, output.status.success()) {
914859
cli_probe::ProbeOutcome::LoggedIn => AuthStatus::LoggedIn,
915860
cli_probe::ProbeOutcome::LoggedOut => AuthStatus::LoggedOut,
916861
cli_probe::ProbeOutcome::ConfigInvalid { stderr_excerpt } => AuthStatus::ConfigInvalid {

0 commit comments

Comments
 (0)