Skip to main content

agentmux_srv_core/backend/
cli_install.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where provider CLIs (claude, codex, …) are installed, shared by every
5//! resolver: `resolvecli`, `install.start` / `install.check`, `agent.open`'s
6//! launch path and the picker's read-only lookup.
7//!
8//! **Shared, keyed by pinned CLI version:**
9//! `<shared_dir>/cli/<provider>/<pinned_version>/`. The install used to live
10//! in `<home>/instances/v<AGENTMUX_VERSION>/cli/<provider>/`, i.e. inside the
11//! AgentMux *version* dir, so every upgrade, portable or dev build started
12//! with no CLI and the first open of each provider ran a blocking
13//! `npm install` of the very same pinned CLI (~3 s, 16 times in a week of
14//! logs — SPEC_AGENT_OPEN_LATENCY_2026_09_27.md F1). The CLI's identity is its
15//! pinned version, not AgentMux's, so that is the key now.
16//!
17//! **Legacy fallback (read-only):** an existing per-version install still
18//! resolves, so nothing breaks for a version that already has one; new
19//! installs always go to the shared dir.
20//!
21//! **Cross-instance safety:** the shared dir is written by every AgentMux
22//! instance on the machine, so installs into it serialize on an exclusive
23//! lock file (`<provider>/<pinned_version>.lock`, blocking, both platforms —
24//! the same primitive the agent registry uses) and re-check for a finished
25//! install after acquiring it, so a second instance waits and then reuses
26//! the first one's result instead of running npm into the same directory.
27//! A shared dir only counts as installed once [`COMPLETE_MARKER`] is written,
28//! after npm succeeded and the shim was verified; an unmarked dir (a failed or
29//! in-progress install), or a marked one whose shim is gone, is cleared —
30//! marker and all — before the next attempt.
31//! `install.start` waits for the lock with [`try_lock_install`] so the wait
32//! stays cancellable.
33
34use std::path::{Path, PathBuf};
35
36use agentmux_common::DataPaths;
37
38const AGENTMUX_VERSION: &str = env!("CARGO_PKG_VERSION");
39
40/// A pinned version string is used as a path component, so it must be a
41/// plain version: letters, digits and `.`, `-`, `_`, `+`, no `..`, bounded.
42/// Anything else (including empty — an unpinned provider) has no shared dir
43/// and falls back to the legacy per-version location.
44pub fn is_safe_version_component(v: &str) -> bool {
45    !v.is_empty()
46        && v.len() <= 64
47        && !v.contains("..")
48        && v.chars()
49            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
50}
51
52/// Same rule for the provider id, which is also a path component.
53pub(crate) fn is_safe_provider_component(p: &str) -> bool {
54    !p.is_empty()
55        && p.len() <= 64
56        && p.chars()
57            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
58}
59
60/// `<shared_dir>/cli/<provider>/<pinned_version>/`, or None when either
61/// component isn't safe to use as a path segment.
62pub fn shared_cli_dir(
63    paths: &DataPaths,
64    provider_id: &str,
65    pinned_version: &str,
66) -> Option<PathBuf> {
67    if !is_safe_provider_component(provider_id) || !is_safe_version_component(pinned_version) {
68        return None;
69    }
70    Some(
71        paths
72            .shared_dir
73            .join("cli")
74            .join(provider_id)
75            .join(pinned_version),
76    )
77}
78
79/// The pre-2026-09-27 per-AgentMux-version location, kept for read-only
80/// fallback and for unpinned providers.
81pub fn legacy_cli_dir(paths: &DataPaths, provider_id: &str) -> PathBuf {
82    paths
83        .home_dir
84        .join("instances")
85        .join(format!("v{AGENTMUX_VERSION}"))
86        .join("cli")
87        .join(provider_id)
88}
89
90/// The directory new installs go to: the shared dir when the provider is
91/// pinned, else the legacy one.
92pub fn install_dir(paths: &DataPaths, provider_id: &str, pinned_version: &str) -> PathBuf {
93    shared_cli_dir(paths, provider_id, pinned_version)
94        .unwrap_or_else(|| legacy_cli_dir(paths, provider_id))
95}
96
97/// `<dir>/node_modules/.bin/<cli>` — `.cmd` on Windows, where npm writes a
98/// batch shim.
99pub fn npm_bin(dir: &Path, cli_command: &str) -> PathBuf {
100    let bin = dir.join("node_modules").join(".bin");
101    if cfg!(windows) {
102        bin.join(format!("{cli_command}.cmd"))
103    } else {
104        bin.join(cli_command)
105    }
106}
107
108/// Written into a shared install dir only after npm succeeded and the shim was
109/// verified, under the install lock. npm creates `.bin` shims before its
110/// lifecycle scripts and the rest of the install finish, so a shim alone
111/// doesn't mean "installed" — a reader could otherwise run a CLI another
112/// instance is still installing, and a failed install's leftover shim would
113/// poison the shared cache for every later AgentMux version (Codex P2 on #3927).
114pub const COMPLETE_MARKER: &str = ".agentmux-install-complete";
115
116/// Whether `dir` holds a finished, verified install.
117pub fn is_complete(dir: &Path) -> bool {
118    dir.join(COMPLETE_MARKER).is_file()
119}
120
121/// Mark `dir` complete (write-then-rename, so a reader never sees a torn
122/// marker). Call under the install lock, after verifying the shim.
123pub fn mark_complete(dir: &Path, version: &str) -> std::io::Result<()> {
124    let tmp = dir.join(format!("{COMPLETE_MARKER}.tmp"));
125    std::fs::write(&tmp, version)?;
126    std::fs::rename(&tmp, dir.join(COMPLETE_MARKER))
127}
128
129/// Whether `dir` holds a usable install: marked complete AND its shim is
130/// still there. A marker alone isn't enough — a finished install can lose its
131/// shim later (corruption, antivirus cleanup).
132pub fn is_valid_install(dir: &Path, cli_command: &str) -> bool {
133    is_complete(dir) && installed_bin(dir, cli_command).is_some()
134}
135
136/// The CLI inside an install dir: an npm shim, or the program a release
137/// download unpacked (`cli_download`). One provider has one kind.
138pub fn installed_bin(dir: &Path, cli_command: &str) -> Option<PathBuf> {
139    [
140        npm_bin(dir, cli_command),
141        crate::backend::cli_download::download_bin(dir, cli_command),
142    ]
143    .into_iter()
144    .find(|b| b.is_file())
145}
146
147/// `--version` of a program just installed, run with the provider's own environment
148/// (`auth_extra_env`: its self-update off), so a CLI that replaces itself on any run cannot stall the install on a
149/// download or swap the hash-checked binary for an unchecked one.
150pub(crate) fn probe_installed(bin: &Path, provider_id: &str) -> Option<String> {
151    let env = crate::backend::providers::get_provider(provider_id).map_or(&[][..], |p| p.auth_extra_env);
152    crate::backend::tool_store::probe_version_when_it_runs(&bin.to_string_lossy(), &Some("--version".to_string()), env)
153}
154
155/// Under the install lock, before (re)installing into `dir`: unless it holds
156/// a valid install, remove it entirely — leftovers of a failed or interrupted
157/// install, and a stale completion marker whose shim is gone. Removing the
158/// marker is the point: a repair must not run with the old marker visible, or
159/// readers would accept the half-repaired install as soon as npm recreates the
160/// shim, and a failed repair would leave marker + shim accepted indefinitely
161/// (Codex P2 on #3927, second pass). No-op for a missing or valid dir.
162pub fn clear_unless_valid(dir: &Path, cli_command: &str) -> std::io::Result<()> {
163    if dir.exists() && !is_valid_install(dir, cli_command) {
164        std::fs::remove_dir_all(dir)?;
165    }
166    Ok(())
167}
168
169/// The installed CLI binary, if any: the shared dir (only once marked
170/// complete), then the legacy per-version dir (which predates the marker, so
171/// its shim is enough).
172pub fn find_installed(
173    paths: &DataPaths,
174    provider_id: &str,
175    pinned_version: &str,
176    cli_command: &str,
177) -> Option<PathBuf> {
178    let shared = shared_cli_dir(paths, provider_id, pinned_version)
179        .filter(|d| is_complete(d))
180        .inspect(|d| crate::backend::cli_prune::record_use(d, std::time::SystemTime::now()))
181        .and_then(|d| installed_bin(&d, cli_command));
182    shared.or_else(|| {
183        let legacy = npm_bin(&legacy_cli_dir(paths, provider_id), cli_command);
184        legacy.is_file().then_some(legacy)
185    })
186}
187
188/// Same, with the pinned version taken from the backend provider registry
189/// (the source of truth) rather than a caller-supplied string.
190pub fn find_installed_for_provider(paths: &DataPaths, provider_id: &str) -> Option<PathBuf> {
191    let provider = crate::backend::providers::get_provider(provider_id)?;
192    find_installed(
193        paths,
194        provider.id,
195        provider.pinned_version,
196        provider.cli_command,
197    )
198}
199
200/// Held for the duration of an install into a shared dir; dropping it
201/// releases the lock. `None` inside for the legacy (per-instance) dir,
202/// which needs no cross-instance lock.
203pub struct InstallGuard {
204    _file: Option<std::fs::File>,
205}
206
207/// Take the cross-instance install lock for `dir` when it is a shared dir.
208/// Blocks until any other instance's install into the same dir finishes —
209/// call it from a blocking context (`spawn_blocking`). The lock file sits
210/// next to the dir and is never deleted (deleting a locked file races
211/// waiters onto a different inode; see `registry::leases::CriticalSection`).
212pub fn lock_install(
213    paths: &DataPaths,
214    provider_id: &str,
215    pinned_version: &str,
216) -> std::io::Result<InstallGuard> {
217    let Some(file) = open_lock_file(paths, provider_id, pinned_version)? else {
218        return Ok(InstallGuard { _file: None });
219    };
220    crate::registry::lock_exclusive(&file)?;
221    Ok(InstallGuard { _file: Some(file) })
222}
223
224/// The same lock for any install folder, not only `cli/<provider>/<pin>`
225/// (the pinned `uv` under `tools/`): `<dir>.lock` beside it. Blocking.
226pub fn lock_dir(dir: &Path) -> std::io::Result<InstallGuard> {
227    let parent = dir.parent().unwrap_or(dir);
228    std::fs::create_dir_all(parent)?;
229    let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
230    let file = std::fs::OpenOptions::new()
231        .create(true)
232        .write(true)
233        .truncate(false)
234        .open(parent.join(format!("{name}.lock")))?;
235    crate::registry::lock_exclusive(&file)?;
236    Ok(InstallGuard { _file: Some(file) })
237}
238
239/// Non-blocking [`lock_install`]: `Ok(None)` while another instance holds
240/// the lock. For waiters that must stay cancellable (`install.start` polls
241/// this and races `install.cancel`, Codex P2 on #3927).
242pub fn try_lock_install(
243    paths: &DataPaths,
244    provider_id: &str,
245    pinned_version: &str,
246) -> std::io::Result<Option<InstallGuard>> {
247    let Some(file) = open_lock_file(paths, provider_id, pinned_version)? else {
248        return Ok(Some(InstallGuard { _file: None }));
249    };
250    if crate::registry::try_lock_exclusive(&file)? {
251        Ok(Some(InstallGuard { _file: Some(file) }))
252    } else {
253        Ok(None)
254    }
255}
256
257/// The shared dir's lock file, opened (created if missing); None for a
258/// provider/pin with no shared dir.
259fn open_lock_file(
260    paths: &DataPaths,
261    provider_id: &str,
262    pinned_version: &str,
263) -> std::io::Result<Option<std::fs::File>> {
264    let Some(dir) = shared_cli_dir(paths, provider_id, pinned_version) else {
265        return Ok(None);
266    };
267    let parent = dir.parent().unwrap_or(&dir).to_path_buf();
268    std::fs::create_dir_all(&parent)?;
269    let lock_path = parent.join(format!("{pinned_version}.lock"));
270    let file = std::fs::OpenOptions::new()
271        .create(true)
272        .write(true)
273        .truncate(false)
274        .open(&lock_path)?;
275    Ok(Some(file))
276}
277
278// ─── installing ─────────────────────────────────────────────────────────────
279
280/// What to install: `npm_package@pinned_version`, whose shim is `cli_command`.
281#[derive(Debug, Clone)]
282pub struct NpmInstallRequest {
283    pub provider_id: String,
284    pub npm_package: String,
285    pub pinned_version: String,
286    pub cli_command: String,
287    /// Run npm below normal priority (the startup warm-up, not an open
288    /// someone is waiting on).
289    pub background: bool,
290}
291
292/// What `npm install` produced.
293#[derive(Debug)]
294pub struct NpmRun {
295    pub success: bool,
296    pub code: Option<i32>,
297    pub stdout: Vec<u8>,
298    pub stderr: Vec<u8>,
299}
300
301#[derive(Debug)]
302pub enum InstallOutcome {
303    /// This call ran npm; the shim is here.
304    Installed(PathBuf),
305    /// A finished install was already there — typically another instance's,
306    /// completed while this one waited for the lock.
307    AlreadyInstalled(PathBuf),
308}
309
310#[derive(Debug)]
311pub enum InstallError {
312    Lock(std::io::Error),
313    Clear(PathBuf, std::io::Error),
314    Spawn(std::io::Error),
315    NpmFailed { code: Option<i32> },
316    ShimMissing { expected: PathBuf },
317    Mark(PathBuf, std::io::Error),
318}
319
320impl std::fmt::Display for InstallError {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        match self {
323            InstallError::Lock(e) => write!(f, "cannot take the CLI install lock: {e}"),
324            InstallError::Clear(d, e) => write!(
325                f,
326                "cannot clear an incomplete CLI install at {}: {e}",
327                d.display()
328            ),
329            InstallError::Spawn(e) => write!(f, "failed to run npm install: {e}"),
330            InstallError::NpmFailed { code } => {
331                write!(f, "npm install exited {}", code.unwrap_or(-1))
332            }
333            InstallError::ShimMissing { expected } => {
334                write!(f, "npm install left no CLI shim at {}", expected.display())
335            }
336            InstallError::Mark(d, e) => write!(
337                f,
338                "cannot mark the CLI install complete at {}: {e}",
339                d.display()
340            ),
341        }
342    }
343}
344
345/// Install `req` into its install dir, **blocking** — call it from
346/// `spawn_blocking` or a plain thread. The one install routine for
347/// `resolvecli` and the startup warm-up ([`warm_used_providers`]):
348///
349/// 1. Take the cross-instance lock, and hold it until this returns — so npm
350///    never outlives the lock (Codex P2 on #3927: a timed-out RPC used to
351///    drop its guard while npm kept writing).
352/// 2. A valid install already there (another instance finished while this
353///    one waited): reuse it. Otherwise clear leftovers, marker and all.
354/// 3. `npm install --prefix <dir> <pkg>@<pin>`; every output line goes to
355///    `on_line(stream, line)`.
356/// 4. Verify the shim, then publish with [`COMPLETE_MARKER`].
357pub fn install_pinned_cli(
358    paths: &DataPaths,
359    req: &NpmInstallRequest,
360    on_line: &dyn Fn(&'static str, &str),
361) -> Result<InstallOutcome, InstallError> {
362    install_pinned_cli_with(paths, req, on_line, run_npm_install)
363}
364
365/// [`install_pinned_cli`] with the npm runner injected (tests).
366pub fn install_pinned_cli_with(
367    paths: &DataPaths,
368    req: &NpmInstallRequest,
369    on_line: &dyn Fn(&'static str, &str),
370    run_npm: impl FnOnce(&Path, &str, bool) -> std::io::Result<NpmRun>,
371) -> Result<InstallOutcome, InstallError> {
372    let dir = install_dir(paths, &req.provider_id, &req.pinned_version);
373    let bin = npm_bin(&dir, &req.cli_command);
374    let _guard =
375        lock_install(paths, &req.provider_id, &req.pinned_version).map_err(InstallError::Lock)?;
376    let shared = shared_cli_dir(paths, &req.provider_id, &req.pinned_version);
377    if let Some(d) = shared.as_deref() {
378        if is_valid_install(d, &req.cli_command) {
379            return Ok(InstallOutcome::AlreadyInstalled(bin));
380        }
381        clear_unless_valid(d, &req.cli_command)
382            .map_err(|e| InstallError::Clear(d.to_path_buf(), e))?;
383    }
384    // The pinned package plus any companions (pi-acp's `pi`), in one npm run
385    // under the same lock and completion marker. Specs never hold whitespace.
386    let package = match crate::backend::providers::get_provider(&req.provider_id) {
387        Some(p) if p.npm_package == req.npm_package => p.npm_install_specs(&req.pinned_version).join(" "),
388        _ => format!("{}@{}", req.npm_package, req.pinned_version),
389    };
390    tracing::info!(package = %package, prefix = %dir.display(), background = req.background, "running npm install");
391    let run = run_npm(&dir, &package, req.background).map_err(InstallError::Spawn)?;
392    tracing::info!(
393        exit_code = run.code.unwrap_or(-1),
394        stdout_bytes = run.stdout.len(),
395        stderr_bytes = run.stderr.len(),
396        "npm install output collected"
397    );
398    // stderr first: npm writes progress and errors there.
399    for (stream, bytes) in [("stderr", &run.stderr), ("stdout", &run.stdout)] {
400        for line in String::from_utf8_lossy(bytes).lines() {
401            if !line.trim().is_empty() {
402                on_line(stream, line);
403            }
404        }
405    }
406    if !run.success {
407        return Err(InstallError::NpmFailed { code: run.code });
408    }
409    if !bin.is_file() {
410        return Err(InstallError::ShimMissing { expected: bin });
411    }
412    if let Some(d) = shared.as_deref() {
413        mark_complete(d, &req.pinned_version)
414            .map_err(|e| InstallError::Mark(d.to_path_buf(), e))?;
415    }
416    Ok(InstallOutcome::Installed(bin))
417}
418
419/// The public npm registry, the only one an agent CLI is installed from.
420const NPM_REGISTRY: &str = "https://registry.npmjs.org/";
421
422/// The flags that keep an install from the person's own npm setup: the public registry, and an
423/// empty file each in place of their `~/.npmrc` and npm's global config (npm refuses one file
424/// loaded as both). Their registry, scope
425/// routing (a `@agentmuxai:registry=https://npm.pkg.github.com` line made the muxcode install
426/// 404), proxy and script policy then cannot change what is installed, or from where. A proxy
427/// in the environment (`HTTPS_PROXY`) still applies. The empty files are made in `dir`, the
428/// install folder, which is created if need be.
429pub fn npm_isolation_args(dir: &Path) -> std::io::Result<Vec<String>> {
430    std::fs::create_dir_all(dir)?;
431    let mut args = vec![format!("--registry={NPM_REGISTRY}")];
432    for (flag, name) in [("--userconfig", ".agentmux-empty-user.npmrc"), ("--globalconfig", ".agentmux-empty-global.npmrc")] {
433        let empty = dir.join(name);
434        std::fs::write(&empty, b"")?;
435        args.push(flag.to_string());
436        args.push(empty.to_string_lossy().into_owned());
437    }
438    Ok(args)
439}
440
441/// Run `npm install --prefix <dir> <package>` to completion. `package` is one
442/// or more space-separated `name@version` specs.
443///
444/// Output is collected after exit (`.output()`): pipe-based streaming
445/// (async IOCP and sync blocking alike) receives nothing from `cmd.exe /C`
446/// batch children on Windows until the process exits.
447fn run_npm_install(dir: &Path, package: &str, background: bool) -> std::io::Result<NpmRun> {
448    let out = npm_install_command(dir, package, background)?.output()?;
449    Ok(NpmRun {
450        success: out.status.success(),
451        code: out.status.code(),
452        stdout: out.stdout,
453        stderr: out.stderr,
454    })
455}
456
457/// The command [`run_npm_install`] runs. Its working folder is the install folder `dir`, so nothing it does
458/// depends on the folder srv was started in (on Windows `cmd /C npm` looks in the working folder before PATH).
459fn npm_install_command(dir: &Path, package: &str, background: bool) -> std::io::Result<std::process::Command> {
460    let command = {
461        #[cfg(windows)]
462        {
463            // npm on Windows is a .cmd batch script — it must run via
464            // `cmd /C`. `raw_arg` passes the command string verbatim: with
465            // `.args(["/C", s])` Rust quotes `s` and escapes inner quotes as
466            // `\"`, which cmd.exe takes literally, corrupting the path
467            // (CWD + \"C:\path\" → ENOENT).
468            use std::os::windows::process::CommandExt;
469            // No console flash from a GUI process (CREATE_NO_WINDOW); the
470            // warm-up also runs below normal priority.
471            const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000;
472            let mut flags = agentmux_common::win32::CREATE_NO_WINDOW;
473            if background {
474                flags |= BELOW_NORMAL_PRIORITY_CLASS;
475            }
476            let prefix = dir.to_string_lossy().replace('/', "\\");
477            let isolation = npm_isolation_args(dir)?;
478            // The two config paths are quoted: the install folder can hold spaces.
479            let (user, global) = (isolation[2].replace('/', "\\"), isolation[4].replace('/', "\\"));
480            let isolation = format!("{} --userconfig \"{user}\" --globalconfig \"{global}\"", isolation[0]);
481            let cmdline = format!(
482                "npm install --loglevel=http --no-audit --no-fund --no-progress --legacy-peer-deps=false {isolation} --prefix \"{prefix}\" {package}"
483            );
484            let mut c = std::process::Command::new("cmd");
485            // `npm install` runs arbitrary postinstall scripts — no instance
486            // identity for those.
487            crate::backend::pane_env::sanitize_external_std_command(&mut c);
488            c.arg("/C")
489                .raw_arg(&cmdline)
490                .creation_flags(flags)
491                .current_dir(dir)
492                .env("CI", "true")
493                .env("FORCE_COLOR", "0");
494            c
495        }
496        #[cfg(not(windows))]
497        {
498            let mut c = std::process::Command::new("npm");
499            crate::backend::pane_env::sanitize_external_std_command(&mut c);
500            c.args([
501                "install",
502                "--loglevel=http",
503                "--no-audit",
504                "--no-fund",
505                "--no-progress",
506                "--legacy-peer-deps=false",
507            ])
508            .args(npm_isolation_args(dir)?)
509            .arg("--prefix")
510            .arg(dir)
511            .args(package.split_whitespace())
512            .current_dir(dir)
513            .env("CI", "true")
514            .env("FORCE_COLOR", "0");
515            if background {
516                use std::os::unix::process::CommandExt;
517                // SAFETY: setpriority is async-signal-safe; nothing else runs
518                // between fork and exec here.
519                unsafe {
520                    c.pre_exec(|| {
521                        let _ = libc::setpriority(libc::PRIO_PROCESS, 0, 10);
522                        Ok(())
523                    });
524                }
525            }
526            c
527        }
528    };
529    Ok(command)
530}
531
532// ─── install on demand ──────────────────────────────────────────────────────
533
534/// Why [`ensure_installed`] did not hand back a CLI.
535#[derive(Debug)]
536pub enum EnsureError {
537    /// The install ran and failed (no npm, offline, npm exited non-zero, ...).
538    Failed(String),
539    /// It is still running after the wait. The install is NOT cancelled: it keeps
540    /// the cross-instance lock until npm returns, and a later call waits on that
541    /// lock and then reuses the result.
542    StillInstalling,
543}
544
545/// The pinned CLI for a provider whose install is missing: install it, waiting
546/// up to `wait`. `install` is injected so tests don't need npm.
547///
548/// This is what the UI's launch flow does on a pin bump (`ResolveCli` installs
549/// and waits). `agent.open` used to refuse instead, with `CLI_NOT_AVAILABLE`,
550/// for the minute or two after an upgrade while the new pin downloaded.
551pub async fn ensure_installed_with<F>(
552    paths: DataPaths,
553    req: NpmInstallRequest,
554    wait: std::time::Duration,
555    install: F,
556) -> Result<PathBuf, EnsureError>
557where
558    F: FnOnce(&DataPaths, &NpmInstallRequest) -> Result<InstallOutcome, InstallError>
559        + Send
560        + 'static,
561{
562    let task = tokio::task::spawn_blocking(move || install(&paths, &req));
563    match tokio::time::timeout(wait, task).await {
564        Ok(Ok(Ok(InstallOutcome::Installed(bin) | InstallOutcome::AlreadyInstalled(bin)))) => {
565            Ok(bin)
566        }
567        Ok(Ok(Err(e))) => Err(EnsureError::Failed(e.to_string())),
568        Ok(Err(join)) => Err(EnsureError::Failed(format!(
569            "the install task failed: {join}"
570        ))),
571        Err(_elapsed) => Err(EnsureError::StillInstalling),
572    }
573}
574
575/// [`ensure_installed_with`] running the real npm install.
576pub async fn ensure_installed(
577    paths: DataPaths,
578    req: NpmInstallRequest,
579    wait: std::time::Duration,
580) -> Result<PathBuf, EnsureError> {
581    ensure_installed_with(paths, req, wait, |p, r| {
582        install_pinned_cli(p, r, &|_, _| {})
583    })
584    .await
585}
586
587// ─── startup warm-up ────────────────────────────────────────────────────────
588
589/// How long after srv start the warm-up begins: after the first IPC traffic,
590/// well before most users open an agent.
591pub const WARM_INSTALL_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
592
593/// The npm-installed providers among `provider_ids` whose pinned CLI has no
594/// install yet, deduplicated, in first-seen order. Pure over the registry and
595/// the filesystem.
596pub fn providers_needing_install(
597    paths: &DataPaths,
598    provider_ids: &[String],
599) -> Vec<NpmInstallRequest> {
600    let mut seen = std::collections::HashSet::new();
601    let mut out = Vec::new();
602    for id in provider_ids {
603        let Some(p) = crate::backend::providers::get_provider(id) else {
604            continue;
605        };
606        if p.npm_package.is_empty() || !seen.insert(p.id) {
607            continue;
608        }
609        if find_installed(paths, p.id, p.pinned_version, p.cli_command).is_some() {
610            continue;
611        }
612        out.push(NpmInstallRequest {
613            provider_id: p.id.to_string(),
614            npm_package: p.npm_package.to_string(),
615            pinned_version: p.pinned_version.to_string(),
616            cli_command: p.cli_command.to_string(),
617            background: true,
618        });
619    }
620    out
621}
622
623/// SPEC_AGENT_OPEN_LATENCY_2026_09_27.md §4.1: install the pinned CLI of every
624/// provider the user's agents use, in the background, so the first open
625/// after a pin bump doesn't wait on npm. Only providers in `provider_ids`
626/// (the user's own agent definitions — not every template's), only pins with
627/// no install yet, one at a time, npm below normal priority. An open that
628/// arrives mid-install waits on the same lock and then reuses the result.
629/// Failures (no npm, offline) are logged and left for the open to report.
630pub fn warm_used_providers(
631    paths: DataPaths,
632    provider_ids: Vec<String>,
633) -> std::thread::JoinHandle<()> {
634    std::thread::Builder::new()
635        .name("cli-install-warm".into())
636        .spawn(move || {
637            std::thread::sleep(WARM_INSTALL_DELAY);
638            let todo = providers_needing_install(&paths, &provider_ids);
639            if todo.is_empty() {
640                tracing::info!(
641                    providers = provider_ids.len(),
642                    "cli warm-up: every used provider's pinned CLI is installed"
643                );
644                return;
645            }
646            for req in todo {
647                let started = std::time::Instant::now();
648                let quiet = |_: &'static str, _: &str| {};
649                match install_pinned_cli(&paths, &req, &quiet) {
650                    Ok(outcome) => tracing::info!(
651                        provider = %req.provider_id,
652                        pinned_version = %req.pinned_version,
653                        duration_ms = started.elapsed().as_millis() as u64,
654                        outcome = ?outcome,
655                        "cli warm-up: installed"
656                    ),
657                    Err(e) => tracing::info!(
658                        provider = %req.provider_id,
659                        pinned_version = %req.pinned_version,
660                        error = %e,
661                        "cli warm-up: install failed; the first open will retry and report it"
662                    ),
663                }
664            }
665        })
666        .expect("spawn cli-install-warm thread")
667}
668
669#[cfg(test)]
670mod tests {
671
672    /// What the install does must not depend on the folder srv was started in: npm runs in the install folder.
673    #[test]
674    fn the_npm_install_runs_in_the_install_folder() {
675        let tmp = tempfile::tempdir().unwrap();
676        let dir = tmp.path().join("cli").join("claude").join("1.0.0");
677        for background in [false, true] {
678            let command = super::npm_install_command(&dir, "@anthropic-ai/claude-code@1.0.0", background).unwrap();
679            assert_eq!(command.get_current_dir(), Some(dir.as_path()), "background {background}");
680        }
681    }
682
683    /// A `.npmrc` routing @agentmuxai to GitHub Packages made the muxcode install 404, and any
684    /// package could be pulled from the person's own registry: every install now names the public
685    /// one and reads an empty config instead of theirs.
686    #[test]
687    fn every_npm_install_uses_the_public_registry_and_an_empty_config() {
688        let tmp = tempfile::tempdir().unwrap();
689        let dir = tmp.path().join("cli").join("claude").join("1.0.0");
690        let args = super::npm_isolation_args(&dir).unwrap();
691        assert_eq!(args[0], "--registry=https://registry.npmjs.org/");
692        assert_eq!((args[1].as_str(), args[3].as_str()), ("--userconfig", "--globalconfig"));
693        assert_ne!(args[2], args[4], "npm refuses one file as both the user and the global config");
694        for config in [&args[2], &args[4]] {
695            let empty = std::path::Path::new(config);
696            assert!(empty.starts_with(&dir), "the empty config is inside the install folder: {empty:?}");
697            assert_eq!(std::fs::read(empty).unwrap(), b"", "the config npm reads is empty");
698        }
699    }
700
701    use super::*;
702
703    fn paths_in(root: &Path) -> DataPaths {
704        let version_dir = root
705            .join("channels")
706            .join("c")
707            .join("versions")
708            .join("1.0.0");
709        DataPaths {
710            home_dir: version_dir.join("data"),
711            instance_dir: root.join("channels").join("c"),
712            channel: "c".to_string(),
713            data_dir: version_dir.join("data"),
714            config_dir: root.join("channels").join("c").join("config"),
715            logs_dir: version_dir.join("logs"),
716            cef_cache_dir: version_dir.join("cef-cache"),
717            agents_dir: root.join("channels").join("c").join("agents"),
718            instance_runtime_dir: version_dir.join("runtime"),
719            shared_dir: root.join("shared"),
720            mode: agentmux_common::RuntimeMode::Portable,
721        }
722    }
723
724    #[test]
725    fn shared_dir_is_keyed_by_provider_and_pinned_version_not_agentmux_version() {
726        let tmp = tempfile::tempdir().unwrap();
727        let p = paths_in(tmp.path());
728        let d = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
729        assert_eq!(
730            d,
731            tmp.path()
732                .join("shared")
733                .join("cli")
734                .join("claude")
735                .join("2.1.280")
736        );
737        assert!(!d.to_string_lossy().contains(AGENTMUX_VERSION) || AGENTMUX_VERSION == "2.1.280");
738    }
739
740    #[test]
741    fn unsafe_components_have_no_shared_dir_and_fall_back_to_legacy() {
742        let tmp = tempfile::tempdir().unwrap();
743        let p = paths_in(tmp.path());
744        for bad in ["", "..", "../x", "1.0/2", "1.0\\2", "a b"] {
745            assert!(shared_cli_dir(&p, "claude", bad).is_none(), "{bad:?}");
746            assert_eq!(install_dir(&p, "claude", bad), legacy_cli_dir(&p, "claude"));
747        }
748        assert!(shared_cli_dir(&p, "../claude", "1.0.0").is_none());
749        assert!(is_safe_version_component("2.1.280"));
750        assert!(is_safe_version_component("1.0.0-beta.1+build_7"));
751    }
752
753    fn touch_bin(dir: &Path, cli: &str) -> PathBuf {
754        let b = npm_bin(dir, cli);
755        std::fs::create_dir_all(b.parent().unwrap()).unwrap();
756        std::fs::write(&b, "").unwrap();
757        b
758    }
759
760    #[test]
761    fn finds_the_shared_install_first_then_the_legacy_one() {
762        let tmp = tempfile::tempdir().unwrap();
763        let p = paths_in(tmp.path());
764        assert!(find_installed(&p, "claude", "2.1.280", "claude").is_none());
765
766        let legacy = touch_bin(&legacy_cli_dir(&p, "claude"), "claude");
767        assert_eq!(
768            find_installed(&p, "claude", "2.1.280", "claude"),
769            Some(legacy.clone())
770        );
771
772        let shared_dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
773        let shared = touch_bin(&shared_dir, "claude");
774        // A shim alone isn't an install (npm writes it early): still legacy.
775        assert_eq!(
776            find_installed(&p, "claude", "2.1.280", "claude"),
777            Some(legacy.clone())
778        );
779        mark_complete(&shared_dir, "2.1.280").unwrap();
780        assert_eq!(
781            find_installed(&p, "claude", "2.1.280", "claude"),
782            Some(shared)
783        );
784
785        // A different pinned version doesn't see the shared install.
786        assert_eq!(
787            find_installed(&p, "claude", "2.1.281", "claude"),
788            Some(legacy)
789        );
790    }
791
792    #[test]
793    fn an_upgraded_agentmux_version_reuses_the_shared_install() {
794        let tmp = tempfile::tempdir().unwrap();
795        let old = paths_in(tmp.path());
796        let shared_dir = shared_cli_dir(&old, "claude", "2.1.280").unwrap();
797        let shared = touch_bin(&shared_dir, "claude");
798        mark_complete(&shared_dir, "2.1.280").unwrap();
799
800        // Same machine, a different AgentMux version dir, same pinned CLI.
801        let mut new = paths_in(tmp.path());
802        new.home_dir = tmp
803            .path()
804            .join("channels")
805            .join("c")
806            .join("versions")
807            .join("9.9.9")
808            .join("data");
809        assert_eq!(
810            find_installed(&new, "claude", "2.1.280", "claude"),
811            Some(shared)
812        );
813    }
814
815    #[test]
816    fn the_install_lock_serializes_two_holders() {
817        let tmp = tempfile::tempdir().unwrap();
818        let p = paths_in(tmp.path());
819        let first = lock_install(&p, "claude", "2.1.280").unwrap();
820        assert!(tmp
821            .path()
822            .join("shared")
823            .join("cli")
824            .join("claude")
825            .join("2.1.280.lock")
826            .is_file());
827
828        let p2 = paths_in(tmp.path());
829        let (tx, rx) = std::sync::mpsc::channel();
830        let waiter = std::thread::spawn(move || {
831            let _second = lock_install(&p2, "claude", "2.1.280").unwrap();
832            tx.send(()).unwrap();
833        });
834        // The second holder is still blocked while the first holds the lock.
835        assert!(rx
836            .recv_timeout(std::time::Duration::from_millis(300))
837            .is_err());
838        drop(first);
839        rx.recv_timeout(std::time::Duration::from_secs(5))
840            .expect("second holder acquires after release");
841        waiter.join().unwrap();
842    }
843
844    #[test]
845    fn the_legacy_dir_needs_no_lock() {
846        let tmp = tempfile::tempdir().unwrap();
847        let p = paths_in(tmp.path());
848        let g = lock_install(&p, "claude", "").unwrap();
849        assert!(g._file.is_none());
850    }
851
852    /// Codex P2 on #3927: a shared shim without the completion marker (an
853    /// install in progress in another instance, or one that failed) is never
854    /// handed out, and it doesn't hide an absent install either.
855    #[test]
856    fn a_shim_without_the_completion_marker_is_not_an_install() {
857        let tmp = tempfile::tempdir().unwrap();
858        let p = paths_in(tmp.path());
859        let dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
860        touch_bin(&dir, "claude");
861        assert!(!is_complete(&dir));
862        assert!(find_installed(&p, "claude", "2.1.280", "claude").is_none());
863    }
864
865    #[test]
866    fn clear_unless_valid_removes_leftovers_but_keeps_a_finished_install() {
867        let tmp = tempfile::tempdir().unwrap();
868        let p = paths_in(tmp.path());
869        let dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
870        touch_bin(&dir, "claude");
871        clear_unless_valid(&dir, "claude").unwrap();
872        assert!(!dir.exists(), "a partial install is cleared");
873
874        touch_bin(&dir, "claude");
875        mark_complete(&dir, "2.1.280").unwrap();
876        clear_unless_valid(&dir, "claude").unwrap();
877        assert!(
878            is_valid_install(&dir, "claude"),
879            "a finished install is kept"
880        );
881        clear_unless_valid(&tmp.path().join("missing"), "claude").unwrap();
882    }
883
884    /// Codex P2 on #3927 (second pass): a completed install that lost its
885    /// shim must have its marker removed before the repair, so neither a
886    /// repair in progress nor a failed one is ever accepted.
887    #[test]
888    fn a_completed_install_that_lost_its_shim_is_cleared_marker_and_all() {
889        let tmp = tempfile::tempdir().unwrap();
890        let p = paths_in(tmp.path());
891        let dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
892        let shim = touch_bin(&dir, "claude");
893        mark_complete(&dir, "2.1.280").unwrap();
894        std::fs::remove_file(&shim).unwrap();
895        assert!(is_complete(&dir) && !is_valid_install(&dir, "claude"));
896
897        clear_unless_valid(&dir, "claude").unwrap();
898        assert!(!dir.exists(), "stale marker and leftovers are gone");
899
900        // A repair that recreates only the shim (npm mid-install) is not accepted.
901        touch_bin(&dir, "claude");
902        assert!(find_installed(&p, "claude", "2.1.280", "claude").is_none());
903    }
904
905    #[test]
906    fn try_lock_install_reports_a_held_lock_instead_of_waiting() {
907        let tmp = tempfile::tempdir().unwrap();
908        let p = paths_in(tmp.path());
909        let held = lock_install(&p, "claude", "2.1.280").unwrap();
910        let p2 = paths_in(tmp.path());
911        // A second instance's attempt, from another thread (flock/LockFileEx
912        // are per-handle, so a second handle contends like another process).
913        let busy = std::thread::spawn(move || {
914            try_lock_install(&p2, "claude", "2.1.280")
915                .unwrap()
916                .is_none()
917        })
918        .join()
919        .unwrap();
920        assert!(
921            busy,
922            "try_lock_install must report the held lock, not block"
923        );
924        drop(held);
925        let p3 = paths_in(tmp.path());
926        let got = std::thread::spawn(move || {
927            try_lock_install(&p3, "claude", "2.1.280")
928                .unwrap()
929                .is_some()
930        })
931        .join()
932        .unwrap();
933        assert!(got, "acquired once released");
934        assert!(
935            try_lock_install(&p, "claude", "").unwrap().is_some(),
936            "no lock needed without a shared dir"
937        );
938    }
939
940    fn claude_req(background: bool) -> NpmInstallRequest {
941        NpmInstallRequest {
942            provider_id: "claude".into(),
943            npm_package: "@anthropic-ai/claude-code".into(),
944            pinned_version: "2.1.280".into(),
945            cli_command: "claude".into(),
946            background,
947        }
948    }
949
950    /// A fake npm: writes the shim unless told not to, and reports `success`.
951    fn fake_npm(
952        write_shim: bool,
953        success: bool,
954    ) -> impl FnOnce(&Path, &str, bool) -> std::io::Result<NpmRun> {
955        move |dir: &Path, _pkg: &str, _bg: bool| {
956            if write_shim {
957                let bin = npm_bin(dir, "claude");
958                std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
959                std::fs::write(&bin, "").unwrap();
960            }
961            Ok(NpmRun {
962                success,
963                code: Some(if success { 0 } else { 1 }),
964                stdout: b"added 3 packages\n".to_vec(),
965                stderr: b"npm http fetch\n\n".to_vec(),
966            })
967        }
968    }
969
970    #[test]
971    fn install_runs_npm_verifies_the_shim_and_marks_it_complete() {
972        let _tmp = tempfile::tempdir().unwrap();
973        let paths = paths_in(_tmp.path());
974        let lines = std::sync::Mutex::new(Vec::new());
975        let on_line = |s: &'static str, l: &str| lines.lock().unwrap().push(format!("{s}:{l}"));
976        let out =
977            install_pinned_cli_with(&paths, &claude_req(false), &on_line, fake_npm(true, true))
978                .unwrap();
979        let dir = shared_cli_dir(&paths, "claude", "2.1.280").unwrap();
980        assert!(matches!(out, InstallOutcome::Installed(ref b) if *b == npm_bin(&dir, "claude")));
981        assert!(is_valid_install(&dir, "claude"));
982        assert_eq!(
983            *lines.lock().unwrap(),
984            vec!["stderr:npm http fetch", "stdout:added 3 packages"]
985        );
986    }
987
988    #[test]
989    fn a_finished_install_is_reused_without_running_npm() {
990        let _tmp = tempfile::tempdir().unwrap();
991        let paths = paths_in(_tmp.path());
992        install_pinned_cli_with(&paths, &claude_req(true), &|_, _| {}, fake_npm(true, true))
993            .unwrap();
994        let out = install_pinned_cli_with(
995            &paths,
996            &claude_req(false),
997            &|_, _| {},
998            |_: &Path, _: &str, _: bool| -> std::io::Result<NpmRun> {
999                panic!("npm must not run again")
1000            },
1001        )
1002        .unwrap();
1003        assert!(matches!(out, InstallOutcome::AlreadyInstalled(_)));
1004    }
1005
1006    #[test]
1007    fn a_failed_npm_leaves_no_marker_and_the_next_attempt_starts_clean() {
1008        let _tmp = tempfile::tempdir().unwrap();
1009        let paths = paths_in(_tmp.path());
1010        let dir = shared_cli_dir(&paths, "claude", "2.1.280").unwrap();
1011        // npm wrote a shim but exited non-zero: not an install.
1012        let err = install_pinned_cli_with(
1013            &paths,
1014            &claude_req(false),
1015            &|_, _| {},
1016            fake_npm(true, false),
1017        )
1018        .unwrap_err();
1019        assert!(matches!(err, InstallError::NpmFailed { code: Some(1) }));
1020        assert!(!is_complete(&dir));
1021        assert!(find_installed(&paths, "claude", "2.1.280", "claude").is_none());
1022        // The retry clears the leftover before npm runs.
1023        let retry = install_pinned_cli_with(
1024            &paths,
1025            &claude_req(false),
1026            &|_, _| {},
1027            |d: &Path, p: &str, b: bool| {
1028                assert!(
1029                    !npm_bin(d, "claude").exists(),
1030                    "leftover shim must be cleared first"
1031                );
1032                fake_npm(true, true)(d, p, b)
1033            },
1034        );
1035        assert!(matches!(retry, Ok(InstallOutcome::Installed(_))));
1036    }
1037
1038    #[test]
1039    fn npm_success_without_a_shim_is_an_error_and_unmarked() {
1040        let _tmp = tempfile::tempdir().unwrap();
1041        let paths = paths_in(_tmp.path());
1042        let err = install_pinned_cli_with(
1043            &paths,
1044            &claude_req(false),
1045            &|_, _| {},
1046            fake_npm(false, true),
1047        )
1048        .unwrap_err();
1049        assert!(matches!(err, InstallError::ShimMissing { .. }));
1050        assert!(!is_complete(
1051            &shared_cli_dir(&paths, "claude", "2.1.280").unwrap()
1052        ));
1053    }
1054
1055    #[test]
1056    fn the_install_holds_the_lock_until_npm_returns() {
1057        let _tmp = tempfile::tempdir().unwrap();
1058        let paths = paths_in(_tmp.path());
1059        let p2 = paths.clone();
1060        install_pinned_cli_with(
1061            &paths,
1062            &claude_req(false),
1063            &|_, _| {},
1064            move |d: &Path, pk: &str, b: bool| {
1065                // While npm "runs", nobody else can take the lock.
1066                assert!(try_lock_install(&p2, "claude", "2.1.280")
1067                    .unwrap()
1068                    .is_none());
1069                fake_npm(true, true)(d, pk, b)
1070            },
1071        )
1072        .unwrap();
1073        assert!(try_lock_install(&paths, "claude", "2.1.280")
1074            .unwrap()
1075            .is_some());
1076    }
1077
1078    #[test]
1079    fn warm_up_picks_used_npm_providers_with_no_install_once_each() {
1080        let _tmp = tempfile::tempdir().unwrap();
1081        let paths = paths_in(_tmp.path());
1082        let ids: Vec<String> = ["claude", "claude", "codex", "not-a-provider"]
1083            .iter()
1084            .map(|s| s.to_string())
1085            .collect();
1086        let todo: Vec<String> = providers_needing_install(&paths, &ids)
1087            .into_iter()
1088            .map(|r| r.provider_id)
1089            .collect();
1090        assert_eq!(todo, vec!["claude", "codex"]);
1091        assert!(providers_needing_install(&paths, &ids)
1092            .iter()
1093            .all(|r| r.background));
1094
1095        // Installed → no longer needed. `providers_needing_install` checks
1096        // against the LIVE registry pin (`providers::get_provider`), unlike
1097        // `claude_req`'s own hardcoded fixture version — install a request
1098        // built from that live pin, or this only keeps passing by coincidence
1099        // (it did, silently, until the 2.1.280 -> 2.1.285 bump broke it).
1100        let live_claude = crate::backend::providers::get_provider("claude").unwrap();
1101        let live_req = NpmInstallRequest {
1102            provider_id: "claude".into(),
1103            npm_package: live_claude.npm_package.into(),
1104            pinned_version: live_claude.pinned_version.into(),
1105            cli_command: live_claude.cli_command.into(),
1106            background: true,
1107        };
1108        install_pinned_cli_with(&paths, &live_req, &|_, _| {}, fake_npm(true, true)).unwrap();
1109        let todo: Vec<String> = providers_needing_install(&paths, &ids)
1110            .into_iter()
1111            .map(|r| r.provider_id)
1112            .collect();
1113        assert_eq!(todo, vec!["codex"]);
1114    }
1115
1116    // ── a pin bump, as a user meets it ─────────────────────────────────────
1117    //
1118    // The user upgraded AgentMux, the provider's pin moved, and they open an
1119    // existing agent. The previous pin is installed and complete; the new one is
1120    // not. These use the LIVE registry pin (never a hardcoded version — that is
1121    // what silently broke `warm_up_picks_used_npm_providers…` at 2.1.280 →
1122    // 2.1.285) and a fake npm.
1123
1124    /// A completed install of "some earlier pin" of claude, plus the paths.
1125    fn with_previous_pin_installed() -> (tempfile::TempDir, DataPaths, String, PathBuf) {
1126        let tmp = tempfile::tempdir().unwrap();
1127        let paths = paths_in(tmp.path());
1128        let live = crate::backend::providers::get_provider("claude").unwrap();
1129        let previous = "1.0.0-previous".to_string();
1130        assert_ne!(previous, live.pinned_version);
1131        let req = NpmInstallRequest {
1132            provider_id: "claude".into(),
1133            npm_package: live.npm_package.into(),
1134            pinned_version: previous.clone(),
1135            cli_command: live.cli_command.into(),
1136            background: true,
1137        };
1138        install_pinned_cli_with(&paths, &req, &|_, _| {}, fake_npm(true, true)).unwrap();
1139        let old_bin = npm_bin(
1140            &shared_cli_dir(&paths, "claude", &previous).unwrap(),
1141            "claude",
1142        );
1143        assert!(old_bin.is_file());
1144        (tmp, paths, previous, old_bin)
1145    }
1146
1147    fn live_claude_req(background: bool) -> NpmInstallRequest {
1148        let live = crate::backend::providers::get_provider("claude").unwrap();
1149        NpmInstallRequest {
1150            provider_id: "claude".into(),
1151            npm_package: live.npm_package.into(),
1152            pinned_version: live.pinned_version.into(),
1153            cli_command: live.cli_command.into(),
1154            background,
1155        }
1156    }
1157
1158    #[test]
1159    fn after_a_pin_bump_the_previous_install_is_not_mistaken_for_the_new_pin() {
1160        let (_tmp, paths, _prev, _old_bin) = with_previous_pin_installed();
1161        assert_eq!(
1162            find_installed_for_provider(&paths, "claude"),
1163            None,
1164            "an open must resolve the NEW pin (installing it), not run whatever was there"
1165        );
1166        // …and the warm-up knows it has work to do, for exactly the live pin.
1167        let todo = providers_needing_install(&paths, &["claude".to_string()]);
1168        assert_eq!(todo.len(), 1);
1169        let live = crate::backend::providers::get_provider("claude").unwrap();
1170        assert_eq!(todo[0].pinned_version, live.pinned_version);
1171    }
1172
1173    #[test]
1174    fn installing_the_new_pin_leaves_the_previous_one_runnable_for_panes_that_hold_its_path() {
1175        // A pane restored with the old `cmd` path keeps working until its mount
1176        // flow rewrites it; nothing may delete the old install out from under it.
1177        let (_tmp, paths, previous, old_bin) = with_previous_pin_installed();
1178        install_pinned_cli_with(
1179            &paths,
1180            &live_claude_req(false),
1181            &|_, _| {},
1182            fake_npm(true, true),
1183        )
1184        .unwrap();
1185
1186        let new_bin = find_installed_for_provider(&paths, "claude").expect("new pin resolves");
1187        assert_ne!(new_bin, old_bin);
1188        assert!(is_valid_install(
1189            &shared_cli_dir(&paths, "claude", &previous).unwrap(),
1190            "claude"
1191        ));
1192        assert!(old_bin.is_file(), "the previous pin's shim is untouched");
1193        // Resolving again is stable and does not reinstall.
1194        assert_eq!(find_installed_for_provider(&paths, "claude"), Some(new_bin));
1195    }
1196
1197    #[test]
1198    fn a_failed_install_of_the_new_pin_does_not_fall_back_to_the_previous_one() {
1199        // DOCUMENTS CURRENT BEHAVIOUR: the pin is exact. Offline (or no npm)
1200        // right after an upgrade, opening an agent fails with the install error
1201        // rather than silently running the previous CLI. The previous install is
1202        // still on disk and valid; nothing selects it.
1203        let (_tmp, paths, previous, old_bin) = with_previous_pin_installed();
1204        let out = install_pinned_cli_with(
1205            &paths,
1206            &live_claude_req(false),
1207            &|_, _| {},
1208            fake_npm(false, false),
1209        );
1210        assert!(
1211            matches!(out, Err(InstallError::NpmFailed { .. })),
1212            "{out:?}"
1213        );
1214        assert_eq!(find_installed_for_provider(&paths, "claude"), None);
1215        assert!(old_bin.is_file());
1216        assert!(is_valid_install(
1217            &shared_cli_dir(&paths, "claude", &previous).unwrap(),
1218            "claude"
1219        ));
1220        // The failed attempt left nothing behind that a later attempt would trip on.
1221        let live = crate::backend::providers::get_provider("claude").unwrap();
1222        assert!(!shared_cli_dir(&paths, "claude", live.pinned_version)
1223            .unwrap()
1224            .exists());
1225    }
1226
1227    // ── installing on demand (agent.open) ──────────────────────────────────
1228
1229    fn live_req() -> NpmInstallRequest {
1230        live_claude_req(false)
1231    }
1232
1233    #[tokio::test]
1234    async fn ensure_installed_installs_the_missing_pin_and_returns_the_shim() {
1235        let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1236        let live = crate::backend::providers::get_provider("claude").unwrap();
1237        let want = npm_bin(
1238            &shared_cli_dir(&paths, "claude", live.pinned_version).unwrap(),
1239            "claude",
1240        );
1241        let bin = ensure_installed_with(
1242            paths.clone(),
1243            live_req(),
1244            std::time::Duration::from_secs(30),
1245            |p, r| install_pinned_cli_with(p, r, &|_, _| {}, fake_npm(true, true)),
1246        )
1247        .await
1248        .expect("installs");
1249        assert_eq!(bin, want);
1250        assert!(bin.is_file());
1251        assert_eq!(find_installed_for_provider(&paths, "claude"), Some(bin));
1252    }
1253
1254    #[tokio::test]
1255    async fn ensure_installed_reuses_an_install_that_finished_meanwhile() {
1256        let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1257        install_pinned_cli_with(
1258            &paths,
1259            &live_claude_req(true),
1260            &|_, _| {},
1261            fake_npm(true, true),
1262        )
1263        .unwrap();
1264        let bin = ensure_installed_with(
1265            paths,
1266            live_req(),
1267            std::time::Duration::from_secs(30),
1268            |p, r| {
1269                install_pinned_cli_with(
1270                    p,
1271                    r,
1272                    &|_, _| {},
1273                    |_: &Path, _: &str, _: bool| -> std::io::Result<NpmRun> {
1274                        panic!("npm must not run again")
1275                    },
1276                )
1277            },
1278        )
1279        .await
1280        .expect("reuses");
1281        assert!(bin.is_file());
1282    }
1283
1284    #[tokio::test]
1285    async fn ensure_installed_reports_a_failed_install_with_its_reason() {
1286        let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1287        let err = ensure_installed_with(
1288            paths.clone(),
1289            live_req(),
1290            std::time::Duration::from_secs(30),
1291            |p, r| install_pinned_cli_with(p, r, &|_, _| {}, fake_npm(false, false)),
1292        )
1293        .await
1294        .unwrap_err();
1295        assert!(
1296            matches!(&err, EnsureError::Failed(m) if m.contains("npm install exited 1")),
1297            "{err:?}"
1298        );
1299        assert_eq!(find_installed_for_provider(&paths, "claude"), None);
1300    }
1301
1302    #[tokio::test]
1303    async fn ensure_installed_stops_waiting_but_does_not_cancel_a_slow_install() {
1304        let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1305        let finished = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1306        let flag = finished.clone();
1307        let err = ensure_installed_with(
1308            paths.clone(),
1309            live_req(),
1310            std::time::Duration::from_millis(50),
1311            move |p, r| {
1312                std::thread::sleep(std::time::Duration::from_millis(400));
1313                let out = install_pinned_cli_with(p, r, &|_, _| {}, fake_npm(true, true));
1314                flag.store(true, std::sync::atomic::Ordering::SeqCst);
1315                out
1316            },
1317        )
1318        .await
1319        .unwrap_err();
1320        assert!(matches!(err, EnsureError::StillInstalling), "{err:?}");
1321        // The caller got its answer quickly; the install carries on and lands.
1322        for _ in 0..100 {
1323            if finished.load(std::sync::atomic::Ordering::SeqCst) {
1324                break;
1325            }
1326            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1327        }
1328        assert!(
1329            finished.load(std::sync::atomic::Ordering::SeqCst),
1330            "the install must keep running"
1331        );
1332        assert!(
1333            find_installed_for_provider(&paths, "claude").is_some(),
1334            "and a later open finds it"
1335        );
1336    }
1337}