Skip to main content

cli_stream/
process.rs

1//! Generic streaming subprocess engine — the shared core behind every
2//! process-backed harness (bob, Claude Code, Codex, …).
3//!
4//! Spawns a child, pipes stdout/stderr line-by-line through a callback
5//! as [`ProcessEvent`]s, augments PATH so Node-based CLIs resolve even
6//! from a Finder-launched `.app`, and hands back a [`ProcessHandle`] for
7//! cancellation (SIGTERM → SIGKILL). No harness-trait or bob knowledge —
8//! purely subprocess streaming.
9//!
10//! Cancellation is the wrinkle: a run needs to be stoppable mid-stream
11//! when the user closes the tab or hits "stop". `ProcessHandle::cancel()`
12//! sends SIGTERM (with a SIGKILL fallback) and flips an atomic
13//! `cancelled` flag the reader threads use to short-circuit.
14
15use crate::error::StreamError;
16use serde::Serialize;
17use std::io::{BufRead, BufReader, Read};
18use std::path::{Path, PathBuf};
19use std::process::{Child, Command, Stdio};
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{mpsc, Arc, Mutex, OnceLock};
22use std::thread;
23use std::time::Duration;
24
25/// Raw events emitted to the caller's callback during a streaming run.
26/// JSON-tagged so axum SSE and Tauri Channel render identical payloads
27/// on the wire. Harness-neutral: a process-backed adapter parses the
28/// `Stdout` lines into a normalized event vocabulary (e.g. `agent-harness`'s `RunEvent`).
29#[derive(Debug, Clone, Serialize)]
30#[serde(tag = "kind", rename_all = "camelCase")]
31// New lifecycle events can be added without breaking downstream matches —
32// consumers must carry a `_` arm. (Construction of existing variants is
33// unaffected, so it's still ergonomic to build them.)
34#[non_exhaustive]
35pub enum ProcessEvent {
36    /// First event. Sent before the child has produced any output so the
37    /// UI can show a "thinking…" state.
38    Started { run_id: String },
39    /// Raw stdout line. Process-backed CLIs emit one JSON object per line
40    /// in their streaming mode. The caller parses.
41    Stdout { run_id: String, line: String },
42    /// Raw stderr line. Warnings + the occasional error.
43    Stderr { run_id: String, line: String },
44    /// Spawn / IO failure. Terminal — followed by `Exited`.
45    Error { run_id: String, message: String },
46    /// Process exited. Always sent exactly once at the end.
47    Exited {
48        run_id: String,
49        exit_code: Option<i32>,
50        /// True iff `cancel()` was called before exit.
51        cancelled: bool,
52    },
53}
54
55/// Handle to an in-flight streaming run. Caller stores it (e.g. in a
56/// runId-keyed map) so a later `cancel()` can find it.
57///
58/// Dropping the handle does NOT cancel the run — the reader threads +
59/// wait thread continue independently. Use `cancel()` explicitly when
60/// the user closes the connection.
61#[derive(Clone, Debug)]
62pub struct ProcessHandle {
63    inner: Arc<HandleInner>,
64}
65
66#[derive(Debug)]
67struct HandleInner {
68    child: Mutex<Option<Child>>,
69    cancelled: AtomicBool,
70}
71
72impl ProcessHandle {
73    /// SIGTERM the process, then SIGKILL after 1.5s if it's still alive.
74    /// The CLI is supposed to flush a final result on SIGTERM but we
75    /// don't trust it to do so forever.
76    pub fn cancel(&self) -> Result<(), StreamError> {
77        self.inner.cancelled.store(true, Ordering::SeqCst);
78        let mut guard = self
79            .inner
80            .child
81            .lock()
82            .map_err(|_| StreamError::CancelLockPoisoned)?;
83        let Some(child) = guard.as_mut() else {
84            // Already exited.
85            return Ok(());
86        };
87        // Best-effort SIGTERM. On Unix, kill() sends SIGKILL by default;
88        // we use libc::kill for SIGTERM, falling back to child.kill() if
89        // the libc call fails. On Windows there's only TerminateProcess
90        // via .kill().
91        #[cfg(unix)]
92        {
93            let pid = child.id() as i32;
94            // SAFETY: pid is the child's PID owned by this Child; sending
95            // SIGTERM is well-defined.
96            unsafe { libc::kill(pid, libc::SIGTERM) };
97            // Spawn the SIGKILL fallback inline to avoid holding the mutex
98            // while sleeping.
99            let inner = Arc::clone(&self.inner);
100            thread::spawn(move || {
101                thread::sleep(Duration::from_millis(1500));
102                if let Ok(mut guard) = inner.child.lock() {
103                    if let Some(child) = guard.as_mut() {
104                        let _ = child.kill();
105                    }
106                }
107            });
108        }
109        #[cfg(not(unix))]
110        {
111            let _ = child.kill();
112        }
113        Ok(())
114    }
115
116    /// Whether `cancel()` was called. Tagged on the final `Exited` event.
117    pub fn was_cancelled(&self) -> bool {
118        self.inner.cancelled.load(Ordering::SeqCst)
119    }
120}
121
122/// Spawn an arbitrary streaming child process — the generic engine behind
123/// every process-backed harness (bob, Claude Code, Codex).
124///
125/// Pipes stdout/stderr line-by-line through `callback` using the raw
126/// [`ProcessEvent`] vocabulary (Started / Stdout / Stderr / Error /
127/// Exited). `env` supplies per-harness secrets (each harness's API-key
128/// var, or none for self-authenticating CLIs). PATH is augmented so
129/// Node-based CLIs find `node`. Returns a [`ProcessHandle`] for
130/// cancellation.
131///
132/// `callback` is invoked from three threads (stdout reader, stderr
133/// reader, exit watcher); the `Clone` bound lets us hand a copy to each.
134/// `run_id` is opaque — the caller chooses it and uses it to correlate
135/// events with the handle.
136///
137/// ```no_run
138/// use cli_stream::{spawn_streaming, ProcessEvent};
139/// use std::path::PathBuf;
140///
141/// # fn main() -> Result<(), cli_stream::StreamError> {
142/// let handle = spawn_streaming(
143///     PathBuf::from("echo"),
144///     vec!["hello".to_owned()],
145///     Vec::new(),                      // extra env vars (key, value)
146///     std::env::current_dir().unwrap(),
147///     "run-1".to_owned(),              // your correlation id
148///     |event| match event {
149///         ProcessEvent::Stdout { line, .. } => println!("{line}"),
150///         ProcessEvent::Exited { exit_code, .. } => eprintln!("exit {exit_code:?}"),
151///         _ => {}
152///     },
153/// )?;
154/// // `handle.cancel()` stops it early; dropping the handle does not.
155/// let _ = handle;
156/// # Ok(())
157/// # }
158/// ```
159pub fn spawn_streaming<F>(
160    program: PathBuf,
161    args: Vec<String>,
162    env: Vec<(String, String)>,
163    cwd: PathBuf,
164    run_id: String,
165    callback: F,
166) -> Result<ProcessHandle, StreamError>
167where
168    F: FnMut(ProcessEvent) + Send + Sync + Clone + 'static,
169{
170    // PATH augmentation: Node-based CLIs (bob, claude, codex) expect
171    // `node` (and often `npm`, `git`) on PATH. A desktop app launched
172    // from Finder/Launchpad inherits only the minimal launchd PATH
173    // (`/usr/bin:/bin:/usr/sbin:/sbin`), so an nvm-installed node is
174    // invisible and the child exits 127 ("command not found").
175    //
176    // Fix: prepend the program's parent dir (where node also lives in an
177    // nvm install) to the child's PATH. Added, not replaced, so a PATH
178    // the user explicitly set still wins on later lookups.
179    //
180    // A bare program name is resolved to its absolute path FIRST (see
181    // `resolve_program`), so the prepended dir is the program's real home —
182    // pairing a node CLI with the exact `node` it was installed under,
183    // regardless of which node version leads the inherited PATH.
184    let program = resolve_program(program);
185    let augmented_path = augment_path_for_node(&program);
186
187    let mut command = Command::new(&program);
188    command
189        .args(&args)
190        .current_dir(&cwd)
191        .env("PATH", augmented_path)
192        .stdin(Stdio::null())
193        .stdout(Stdio::piped())
194        .stderr(Stdio::piped());
195    for (key, value) in &env {
196        command.env(key, value);
197    }
198    let mut child = command.spawn().map_err(|source| StreamError::Spawn {
199        program: program.display().to_string(),
200        source,
201    })?;
202
203    let stdout = child
204        .stdout
205        .take()
206        .ok_or(StreamError::PipeNotCaptured { stream: "stdout" })?;
207    let stderr = child
208        .stderr
209        .take()
210        .ok_or(StreamError::PipeNotCaptured { stream: "stderr" })?;
211
212    let inner = Arc::new(HandleInner {
213        child: Mutex::new(Some(child)),
214        cancelled: AtomicBool::new(false),
215    });
216    let handle = ProcessHandle { inner: Arc::clone(&inner) };
217
218    // Emit Started immediately so the caller doesn't wait on the first
219    // output line for a UI signal.
220    let mut started_cb = callback.clone();
221    started_cb(ProcessEvent::Started { run_id: run_id.clone() });
222
223    // Reader threads. Each owns its own callback clone — the Clone bound
224    // is the whole point.
225    let stdout_cb = callback.clone();
226    let stdout_run_id = run_id.clone();
227    let stdout_handle = thread::spawn(move || {
228        pump_lines(stdout, stdout_run_id, true, stdout_cb);
229    });
230
231    let stderr_cb = callback.clone();
232    let stderr_run_id = run_id.clone();
233    let stderr_handle = thread::spawn(move || {
234        pump_lines(stderr, stderr_run_id, false, stderr_cb);
235    });
236
237    // Exit watcher — emits the terminal Exited event with the cancellation
238    // flag. It must NOT hold the child lock across a blocking `wait()`:
239    // `cancel()` needs that same lock to signal the child, so a held lock
240    // would block cancel until the process exited on its own (defeating it).
241    // Instead poll `try_wait()`, locking only for each non-blocking check and
242    // releasing between polls so `cancel()` can acquire the lock mid-run.
243    let exit_inner = Arc::clone(&inner);
244    let mut exit_cb = callback;
245    let exit_run_id = run_id;
246    thread::spawn(move || {
247        let wait_result = loop {
248            {
249                let mut guard = match exit_inner.child.lock() {
250                    Ok(guard) => guard,
251                    Err(_) => return, // poisoned — nothing safe to do
252                };
253                match guard.as_mut() {
254                    Some(child) => match child.try_wait() {
255                        Ok(Some(status)) => break Ok(status),
256                        Ok(None) => {}            // still running; poll again
257                        Err(err) => break Err(err),
258                    },
259                    None => return, // already reaped
260                }
261            } // lock released before sleeping, so cancel() can acquire it
262            thread::sleep(Duration::from_millis(50));
263        };
264        let _ = stdout_handle.join();
265        let _ = stderr_handle.join();
266        let cancelled = exit_inner.cancelled.load(Ordering::SeqCst);
267
268        match wait_result {
269            Ok(status) => exit_cb(ProcessEvent::Exited {
270                run_id: exit_run_id.clone(),
271                exit_code: status.code(),
272                cancelled,
273            }),
274            Err(err) => exit_cb(ProcessEvent::Error {
275                run_id: exit_run_id.clone(),
276                message: format!("wait failed: {err}"),
277            }),
278        }
279
280        // Drop the child handle so subsequent cancel() calls
281        // short-circuit cleanly.
282        if let Ok(mut guard) = exit_inner.child.lock() {
283            *guard = None;
284        }
285    });
286
287    Ok(handle)
288}
289
290fn pump_lines<R, F>(reader: R, run_id: String, is_stdout: bool, mut callback: F)
291where
292    R: Read,
293    F: FnMut(ProcessEvent),
294{
295    let buffered = BufReader::new(reader);
296    for line in buffered.lines() {
297        match line {
298            Ok(text) => {
299                let event = if is_stdout {
300                    ProcessEvent::Stdout { run_id: run_id.clone(), line: text }
301                } else {
302                    ProcessEvent::Stderr { run_id: run_id.clone(), line: text }
303                };
304                callback(event);
305            }
306            Err(err) => {
307                callback(ProcessEvent::Error {
308                    run_id: run_id.clone(),
309                    message: format!("stream read failed: {err}"),
310                });
311                return;
312            }
313        }
314    }
315}
316
317/// Compose a PATH for the spawned process that always includes the
318/// directory containing the program — where `node`, `npm`, and friends
319/// usually live in an nvm install. The user's existing PATH stays as a
320/// fallback after our prepended directory.
321fn augment_path_for_node(program: &Path) -> String {
322    prepend_program_dir(program, &augmented_node_path())
323}
324
325/// Resolve a bare program name (`bob`, `claude`) to its absolute path on the
326/// augmented PATH, so the spawn and the node pairing agree on *one* location.
327///
328/// Without this, a bare name splits the brain: the OS resolves the *program*
329/// against the parent process's PATH, while the child's `#!/usr/bin/env node`
330/// shebang resolves *node* against the PATH we set — and
331/// [`prepend_program_dir`] can't pair the program with its sibling node
332/// because a bare name has no parent dir. Concretely: an nvm-installed `bob`
333/// found under `v24/bin` could re-exec on a `v20` node that happened to lead
334/// the inherited PATH, and die on a v24-only flag ("exited with code 9").
335/// Resolving to the absolute path first means the program's own directory —
336/// holding the exact `node` it was installed with — is prepended and wins.
337///
338/// A program given with an explicit path is returned untouched; a bare name
339/// that can't be found is also returned untouched, so the spawn still fails
340/// with the clear "No such file" error rather than a synthetic one here.
341pub fn resolve_program(program: PathBuf) -> PathBuf {
342    if program.parent().is_some_and(|p| !p.as_os_str().is_empty()) {
343        return program; // explicit path — caller's choice wins
344    }
345    resolve_on_path(&program, &augmented_node_path()).unwrap_or(program)
346}
347
348/// Walk `path_env`'s entries for the first executable file named `name`.
349/// Pure with respect to env/spawn (filesystem only) so it's unit-testable.
350fn resolve_on_path(name: &Path, path_env: &str) -> Option<PathBuf> {
351    path_env
352        .split(':')
353        .filter(|dir| !dir.is_empty())
354        .map(|dir| Path::new(dir).join(name))
355        .find(|candidate| is_executable_file(candidate))
356}
357
358#[cfg(unix)]
359fn is_executable_file(path: &Path) -> bool {
360    use std::os::unix::fs::PermissionsExt;
361    std::fs::metadata(path)
362        .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
363        .unwrap_or(false)
364}
365
366#[cfg(not(unix))]
367fn is_executable_file(path: &Path) -> bool {
368    path.is_file()
369}
370
371/// Prepend the directory containing `program` (where `node` also lives in an
372/// nvm install) to `base_path`, so the resolved binary's own dir is searched
373/// first. Pure (no env / no spawn) so it's unit-tested directly.
374fn prepend_program_dir(program: &Path, base_path: &str) -> String {
375    match program
376        .parent()
377        .map(|p| p.display().to_string())
378        .filter(|s| !s.is_empty())
379    {
380        Some(dir) => format!("{dir}:{base_path}"),
381        None => base_path.to_owned(),
382    }
383}
384
385/// A PATH that resolves Node-based CLIs (bob, claude, codex) even from a
386/// process launched by Finder/Launchpad, which inherits only the minimal
387/// launchd PATH (`/usr/bin:/bin:/usr/sbin:/sbin`) rather than the user's
388/// shell PATH.
389///
390/// Strategy: keep the process's own PATH first (an explicit PATH still wins),
391/// then append the user's **real** PATH as resolved by their login shell —
392/// which sources their rc, so it knows where nvm / pnpm / volta / asdf / fnm /
393/// Homebrew put `node`, with no guessing. If the shell query is unavailable
394/// (no `$SHELL`, a timeout, a sandboxed app that can't spawn, …) we fall back
395/// to a hardcoded best-effort list, so we're never worse than before.
396///
397/// Used by the run path (which prepends the resolved binary's own dir on top
398/// of this) and by readiness probes that locate `claude`/`codex` via a bare
399/// `Command::new(name)`. Computed once and cached for the process — the
400/// (bounded) shell spawn happens at most once per launch, lazily on the first
401/// readiness/run/login, never at construction.
402pub fn augmented_node_path() -> String {
403    static CACHED: OnceLock<String> = OnceLock::new();
404    CACHED.get_or_init(compute_augmented_node_path).clone()
405}
406
407fn compute_augmented_node_path() -> String {
408    let mut parts: Vec<String> = Vec::new();
409    // The process's own PATH first — anything explicitly set still wins.
410    if let Ok(existing) = std::env::var("PATH") {
411        if !existing.is_empty() {
412            parts.push(existing);
413        }
414    }
415    // The user's real PATH (nvm/pnpm/volta/asdf/Homebrew) via their login
416    // shell; a hardcoded best-effort list if that's unavailable.
417    parts.push(login_shell_path().unwrap_or_else(hardcoded_node_dirs));
418    keep_absolute_entries(&parts.join(":"))
419}
420
421/// Keep only **absolute** PATH entries, dropping relative or empty ones (`.`,
422/// `""`, a direnv-style `node_modules/.bin`). Security: we spawn with
423/// `current_dir` set to the user's workspace — where the agent itself writes
424/// files and synced/downloaded content lands — so a relative/empty PATH entry
425/// (which resolves against that cwd) could run a planted `node`/`claude`. An
426/// empty entry is the classic implicit-cwd vector. Absolute dirs only.
427fn keep_absolute_entries(path: &str) -> String {
428    path.split(':')
429        .filter(|entry| entry.starts_with('/'))
430        .collect::<Vec<_>>()
431        .join(":")
432}
433
434/// Resolve PATH by asking the user's login + interactive shell — it sources
435/// their rc, so it knows wherever any node manager (nvm / pnpm / volta / asdf /
436/// fnm / Homebrew) put `node`, without us guessing. Bounded by a timeout so a
437/// slow or interactive rc can't hang us; returns `None` (→ hardcoded fallback)
438/// on any failure: no `$SHELL`, spawn refused (e.g. a sandboxed app), timeout,
439/// or no PATH in the output. Reads PATH from `env` (OS colon format,
440/// shell-agnostic — works for fish too) rather than expanding `$PATH`.
441///
442/// This *executes the user's shell rc*, exactly as opening a terminal does —
443/// their own shell, on their own machine. It is not a privilege/auth step: no
444/// "login session" is created; `-l`/`-i` only select which startup files are
445/// sourced (login profiles + the interactive rc where nvm usually lives).
446/// Printed on its own line right before `env`, so the parser can skip any
447/// shell-init chatter / terminal escape sequences (e.g. iTerm2 shell
448/// integration's `]1337;…` OSC codes) the interactive shell emits before our
449/// command runs — which would otherwise prepend to the `PATH=` line.
450const PATH_SENTINEL: &str = "__CLI_STREAM_PATH__";
451
452#[cfg(unix)]
453fn login_shell_path() -> Option<String> {
454    let shell = std::env::var("SHELL").ok().filter(|s| !s.is_empty())?;
455    // Print a sentinel line, then dump the environment. Reading PATH from `env`
456    // (not by expanding `$PATH`) keeps it OS colon format and shell-agnostic
457    // (fish stores PATH as a list); the sentinel lets the parser ignore
458    // anything the interactive shell prints at startup before `env` runs.
459    let script = format!("printf '\\n{PATH_SENTINEL}\\n'; env");
460    let mut child = Command::new(&shell)
461        .arg("-lic") // -l: login profiles, -i: interactive rc (nvm), -c: command
462        .arg(&script)
463        .stdin(Stdio::null())
464        .stdout(Stdio::piped())
465        .stderr(Stdio::null())
466        .spawn()
467        .ok()?;
468    // Read on a worker thread so the whole query can be bounded by a timeout —
469    // a misbehaving rc must not hang the app. Read bytes + lossy-decode (rather
470    // than `read_to_string`) so non-UTF-8 in the env dump degrades to
471    // replacement chars instead of discarding the whole output.
472    let mut stdout = child.stdout.take()?;
473    let (tx, rx) = mpsc::channel();
474    thread::spawn(move || {
475        let mut buf = Vec::new();
476        let _ = stdout.read_to_end(&mut buf);
477        let _ = tx.send(String::from_utf8_lossy(&buf).into_owned());
478    });
479    // 4s: generous enough for a heavy rc (oh-my-zsh + plugins + nvm lazy-load)
480    // to finish, since this is paid at most once (cached); on timeout we kill
481    // the shell and fall back to the hardcoded list.
482    let output = match rx.recv_timeout(Duration::from_secs(4)) {
483        Ok(buf) => buf,
484        Err(_) => {
485            let _ = child.kill();
486            let _ = child.wait();
487            return None;
488        }
489    };
490    let _ = child.wait();
491    parse_path_from_shell_output(&output)
492}
493
494#[cfg(not(unix))]
495fn login_shell_path() -> Option<String> {
496    None
497}
498
499/// Extract the `PATH=…` value from the shell's `printf <sentinel>; env` output.
500/// Everything up to (and including) the last sentinel is discarded — that's
501/// where shell-init chatter and terminal escape sequences live — then the
502/// `PATH=` line is read from the clean `env` dump that follows. `None` if the
503/// sentinel is missing (query misbehaved) or PATH is absent/empty.
504fn parse_path_from_shell_output(output: &str) -> Option<String> {
505    output
506        .rsplit_once(PATH_SENTINEL)?
507        .1
508        .lines()
509        .find_map(|line| line.strip_prefix("PATH="))
510        .map(str::trim)
511        .filter(|p| !p.is_empty())
512        .map(str::to_owned)
513}
514
515/// Hardcoded best-effort node locations — the fallback when the login-shell
516/// query is unavailable. Leans on the *universal* dirs every distro + macOS
517/// share: `/usr/bin` + `/usr/local/bin` are where apt/dnf/yum/pacman and the
518/// official Node tarball install, so the common Linux container case is covered
519/// without distro-specific guessing. Plus macOS Homebrew, the official-installer
520/// dir, and any nvm-managed node. Anything manager-specific (pnpm/volta/asdf,
521/// Linuxbrew, snap, …) is what the login-shell query is for — and a missing
522/// dir is just skipped, so this is never worse than the bare launchd PATH.
523fn hardcoded_node_dirs() -> String {
524    let mut parts: Vec<String> =
525        vec!["/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin".to_owned()];
526    if let Ok(home) = std::env::var("HOME") {
527        if !home.is_empty() {
528            let home_path = Path::new(&home);
529            // Official-installer location for several agent CLIs.
530            parts.push(home_path.join(".local/bin").display().to_string());
531            // nvm: ~/.nvm/versions/node/<version>/bin — where npm-global
532            // CLIs (bob, claude, codex) live under an nvm-managed node.
533            if let Ok(entries) = std::fs::read_dir(home_path.join(".nvm/versions/node")) {
534                for entry in entries.flatten() {
535                    let bin = entry.path().join("bin");
536                    if bin.is_dir() {
537                        parts.push(bin.display().to_string());
538                    }
539                }
540            }
541        }
542    }
543    parts.join(":")
544}
545
546#[cfg(test)]
547mod tests {
548    use super::*;
549
550    #[test]
551    fn hardcoded_fallback_includes_macos_defaults() {
552        // The fallback (used when the login-shell query is unavailable) must
553        // still carry Homebrew + the system bins, so a launchd-spawned `.app`
554        // resolves CLIs even without a usable shell — the original
555        // "not installed" fix.
556        let path = hardcoded_node_dirs();
557        assert!(path.contains("/opt/homebrew/bin"), "missing Apple-Silicon Homebrew bin");
558        assert!(path.contains("/usr/local/bin"), "missing Intel Homebrew / system bin");
559        assert!(path.contains("/usr/bin"), "missing system bin");
560    }
561
562    #[test]
563    fn parse_path_from_shell_output_skips_chatter_before_the_sentinel() {
564        // Real-world shape: iTerm2 OSC escapes + a banner emitted at shell
565        // startup, BEFORE our sentinel + `env` dump. Only the post-sentinel
566        // PATH= line counts — note the pre-sentinel "PATH=/decoy" is ignored.
567        let output = "\u{1b}]1337;RemoteHost=x\u{7}welcome banner\nPATH=/decoy\n__CLI_STREAM_PATH__\nHOME=/Users/x\nPATH=/opt/homebrew/bin:/usr/bin\nLANG=en_US";
568        assert_eq!(
569            parse_path_from_shell_output(output).as_deref(),
570            Some("/opt/homebrew/bin:/usr/bin")
571        );
572        // No sentinel (query misbehaved) → None, so the caller falls back —
573        // even if a bare PATH= is present.
574        assert_eq!(parse_path_from_shell_output("PATH=/usr/bin"), None);
575        // Sentinel present but PATH absent/empty → None.
576        assert_eq!(parse_path_from_shell_output("__CLI_STREAM_PATH__\nFOO=bar"), None);
577        assert_eq!(parse_path_from_shell_output("__CLI_STREAM_PATH__\nPATH=\nFOO=bar"), None);
578    }
579
580    #[test]
581    fn keep_absolute_entries_drops_relative_and_empty() {
582        // Relative (`node_modules/.bin`, `.`) and empty entries — which resolve
583        // against the spawn cwd (the user's workspace) — are dropped; absolute
584        // dirs survive in order.
585        assert_eq!(
586            keep_absolute_entries("/opt/homebrew/bin:node_modules/.bin:/usr/bin:.::/bin"),
587            "/opt/homebrew/bin:/usr/bin:/bin"
588        );
589        assert_eq!(keep_absolute_entries("/usr/bin"), "/usr/bin");
590        // All-relative → empty (caller still has the process PATH ahead of it).
591        assert_eq!(keep_absolute_entries(".:rel:"), "");
592    }
593
594    #[test]
595    fn prepend_program_dir_puts_the_binary_dir_first() {
596        let combined = prepend_program_dir(
597            Path::new("/Users/x/.nvm/versions/node/v22/bin/bob"),
598            "/opt/homebrew/bin:/usr/bin",
599        );
600        assert!(combined.starts_with("/Users/x/.nvm/versions/node/v22/bin:"));
601        assert!(combined.contains("/opt/homebrew/bin"));
602        // A bare program name has no parent dir → base path unchanged.
603        assert_eq!(prepend_program_dir(Path::new("bob"), "/usr/bin"), "/usr/bin");
604    }
605
606    #[test]
607    fn augmented_node_path_is_nonempty_and_resolves_system_bin() {
608        // Exercises the cached public path once. `/usr/bin` is present whether
609        // the shell query succeeds (real PATH) or falls back (hardcoded), and
610        // is on the bare launchd PATH too — so this holds in any environment.
611        let path = augmented_node_path();
612        assert!(!path.is_empty());
613        assert!(path.contains("/usr/bin"), "system bin must always resolve");
614    }
615
616    #[test]
617    fn resolve_program_returns_explicit_paths_untouched() {
618        // A caller-supplied path is the caller's choice — no PATH lookup.
619        let explicit = PathBuf::from("/opt/somewhere/bob");
620        assert_eq!(resolve_program(explicit.clone()), explicit);
621        let relative = PathBuf::from("./bin/bob");
622        assert_eq!(resolve_program(relative.clone()), relative);
623    }
624
625    #[cfg(unix)]
626    #[test]
627    fn resolve_on_path_finds_the_first_executable_match() {
628        use std::os::unix::fs::PermissionsExt;
629        let root = tempfile::tempdir().expect("tempdir");
630        // dir_a holds a NON-executable `bob` (must be skipped); dir_b an
631        // executable one (must win even though dir_a comes first on PATH).
632        let dir_a = root.path().join("a");
633        let dir_b = root.path().join("b");
634        std::fs::create_dir_all(&dir_a).unwrap();
635        std::fs::create_dir_all(&dir_b).unwrap();
636        std::fs::write(dir_a.join("bob"), "#!/bin/sh\n").unwrap();
637        let exec = dir_b.join("bob");
638        std::fs::write(&exec, "#!/bin/sh\n").unwrap();
639        std::fs::set_permissions(&exec, std::fs::Permissions::from_mode(0o755)).unwrap();
640
641        let path_env = format!("{}:{}", dir_a.display(), dir_b.display());
642        assert_eq!(resolve_on_path(Path::new("bob"), &path_env), Some(exec));
643        // An unknown name resolves to nothing.
644        assert_eq!(resolve_on_path(Path::new("definitely-missing"), &path_env), None);
645    }
646}
647
648/// End-to-end lifecycle tests that spawn real processes. Unix-only: they use
649/// `printf` / `sh` / `sleep`, and the cancel path is signal-based here.
650#[cfg(all(test, unix))]
651mod lifecycle {
652    use super::*;
653    use std::sync::Condvar;
654    use std::time::Instant;
655
656    type Done = Arc<(Mutex<bool>, Condvar)>;
657
658    /// A thread-safe event collector that signals `done` on the terminal
659    /// event. Returns the (cloneable) callback + the shared collections.
660    fn collector() -> (
661        impl FnMut(ProcessEvent) + Send + Sync + Clone + 'static,
662        Arc<Mutex<Vec<ProcessEvent>>>,
663        Done,
664    ) {
665        let events = Arc::new(Mutex::new(Vec::new()));
666        let done: Done = Arc::new((Mutex::new(false), Condvar::new()));
667        let cb = {
668            let events = Arc::clone(&events);
669            let done = Arc::clone(&done);
670            move |ev: ProcessEvent| {
671                let terminal =
672                    matches!(ev, ProcessEvent::Exited { .. } | ProcessEvent::Error { .. });
673                events.lock().unwrap().push(ev);
674                if terminal {
675                    let (lock, cvar) = &*done;
676                    *lock.lock().unwrap() = true;
677                    cvar.notify_all();
678                }
679            }
680        };
681        (cb, events, done)
682    }
683
684    /// Block until the terminal event fires, or panic after `secs`.
685    fn wait_done(done: &Done, secs: u64) {
686        let (lock, cvar) = &**done;
687        let mut finished = lock.lock().unwrap();
688        let deadline = Instant::now() + Duration::from_secs(secs);
689        while !*finished {
690            let now = Instant::now();
691            assert!(now < deadline, "process did not finish within {secs}s");
692            let (guard, _) = cvar.wait_timeout(finished, deadline - now).unwrap();
693            finished = guard;
694        }
695    }
696
697    /// Spawn `program args`, block until it exits, return every event.
698    fn run(program: &str, args: &[&str]) -> Vec<ProcessEvent> {
699        let (cb, events, done) = collector();
700        let _handle = spawn_streaming(
701            PathBuf::from(program),
702            args.iter().map(|s| (*s).to_owned()).collect(),
703            Vec::new(),
704            PathBuf::from("."),
705            "t".to_owned(),
706            cb,
707        )
708        .expect("spawn");
709        wait_done(&done, 10);
710        let events = events.lock().unwrap();
711        events.clone()
712    }
713
714    #[test]
715    fn streams_stdout_lines_then_exits_zero() {
716        let events = run("printf", &["%s\n", "alpha", "beta"]);
717        // Started leads, Exited(0, not cancelled) closes.
718        assert!(matches!(events.first(), Some(ProcessEvent::Started { .. })));
719        assert!(matches!(
720            events.last(),
721            Some(ProcessEvent::Exited { exit_code: Some(0), cancelled: false, .. })
722        ));
723        // Lines arrive in order, one event each.
724        let lines: Vec<&str> = events
725            .iter()
726            .filter_map(|e| match e {
727                ProcessEvent::Stdout { line, .. } => Some(line.as_str()),
728                _ => None,
729            })
730            .collect();
731        assert_eq!(lines, vec!["alpha", "beta"]);
732    }
733
734    #[test]
735    fn nonzero_exit_code_is_reported() {
736        let events = run("sh", &["-c", "exit 3"]);
737        assert!(matches!(
738            events.last(),
739            Some(ProcessEvent::Exited { exit_code: Some(3), cancelled: false, .. })
740        ));
741    }
742
743    #[test]
744    fn env_vars_are_passed_to_the_child() {
745        // The `env` argument must reach the child's environment — exercise it
746        // directly (the other lifecycle tests pass an empty env).
747        let (cb, events, done) = collector();
748        let _handle = spawn_streaming(
749            PathBuf::from("sh"),
750            vec!["-c".to_owned(), "printf '%s\\n' \"$CLI_STREAM_STUB\"".to_owned()],
751            vec![("CLI_STREAM_STUB".to_owned(), "from-env".to_owned())],
752            PathBuf::from("."),
753            "t".to_owned(),
754            cb,
755        )
756        .expect("spawn");
757        wait_done(&done, 10);
758        let events = events.lock().unwrap();
759        assert!(
760            events
761                .iter()
762                .any(|e| matches!(e, ProcessEvent::Stdout { line, .. } if line == "from-env")),
763            "child should observe the injected env var, got {events:?}"
764        );
765    }
766
767    #[test]
768    fn stderr_is_streamed_and_not_misrouted_to_stdout() {
769        let events = run("sh", &["-c", "echo to-stderr 1>&2"]);
770        assert!(events
771            .iter()
772            .any(|e| matches!(e, ProcessEvent::Stderr { line, .. } if line == "to-stderr")));
773        assert!(!events.iter().any(|e| matches!(e, ProcessEvent::Stdout { .. })));
774        assert!(events
775            .iter()
776            .any(|e| matches!(e, ProcessEvent::Exited { exit_code: Some(0), .. })));
777    }
778
779    #[test]
780    fn cancel_promptly_terminates_the_run_and_flags_it() {
781        // A 10s sleeper we cancel ~immediately; a working engine must kill it
782        // far sooner than 10s. `exec` so the process *is* sleep (no orphan).
783        let (cb, events, done) = collector();
784        let handle = spawn_streaming(
785            PathBuf::from("sh"),
786            vec!["-c".to_owned(), "exec sleep 10".to_owned()],
787            Vec::new(),
788            PathBuf::from("."),
789            "t".to_owned(),
790            cb,
791        )
792        .expect("spawn");
793
794        // cancel() may block until the child is reaped, so fire it off-thread.
795        let canceller = handle.clone();
796        thread::spawn(move || {
797            thread::sleep(Duration::from_millis(100));
798            let _ = canceller.cancel();
799        });
800
801        // Correct cancellation terminates the 10s sleep within a few seconds.
802        wait_done(&done, 4);
803        assert!(handle.was_cancelled());
804        let events = events.lock().unwrap();
805        assert!(
806            matches!(events.last(), Some(ProcessEvent::Exited { cancelled: true, .. })),
807            "expected Exited(cancelled=true), got {:?}",
808            events.last()
809        );
810    }
811
812    #[test]
813    fn spawning_a_missing_binary_is_err() {
814        let result = spawn_streaming(
815            PathBuf::from("cli-stream-no-such-binary-zzz"),
816            Vec::new(),
817            Vec::new(),
818            PathBuf::from("."),
819            "t".to_owned(),
820            |_ev: ProcessEvent| {},
821        );
822        // Typed: a `Spawn` error carrying the OS `NotFound` io::Error as its
823        // source — the whole point of `StreamError` over a `String`. A caller
824        // can branch on `ErrorKind` to tell "not installed" (NotFound) from
825        // "permission denied", which a flattened string can't support.
826        match result {
827            Err(StreamError::Spawn { program, source }) => {
828                assert!(program.contains("cli-stream-no-such-binary-zzz"));
829                assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
830            }
831            other => panic!("expected StreamError::Spawn, got {other:?}"),
832        }
833    }
834}