Skip to main content

agentmux_srv/server/
install_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `install.start` / `install.cancel` RPC handlers.
5//!
6//! Phase α of `SPEC_AGENT_INSTALL_STAGE_2026_05_17.md`. Spawns
7//! `npm install <package>` for the requested provider, streams every
8//! line of stdout+stderr to `install_chunk` MPS events scoped to
9//! `install:<sessionId>`, and emits a terminal `{ op: "done", ok,
10//! error? }` event when the child exits (or the user cancels).
11//!
12//! Phase α scope:
13//!  - npm-only install (existing per-version layout at
14//!    `~/.agentmux/<version>/cli/<provider>/`).
15//!  - Plain piped stdio (no PTY) — npm doesn't isatty-gate its output
16//!    line-by-line, so pipes are fine here. PTY would be required for
17//!    interactive post-install steps (Phase δ).
18//!  - Single in-flight install per session id. The frontend modal owns
19//!    the session id and prevents parallel installs at the UI layer.
20//!  - Cancel kills the child via `kill_on_drop` when the abort handle
21//!    fires. The partial `node_modules` dir is rm-rf'd best-effort.
22//!  - No verify / doctor / post-install steps yet — those land in
23//!    Phase β.
24
25use std::sync::Arc;
26
27use parking_lot::Mutex;
28use serde::{Deserialize, Serialize};
29
30use crate::backend::rpc::engine::WshRpcEngine;
31use crate::backend::mps::Broker;
32use crate::server::AppState;
33
34pub const COMMAND_INSTALL_START: &str = "install.start";
35pub const COMMAND_INSTALL_CANCEL: &str = "install.cancel";
36pub const COMMAND_INSTALL_CHECK: &str = "install.check";
37pub const COMMAND_RESOLVE_PREREQS: &str = "resolve.prereqs";
38
39pub use crate::backend::install_events::{InstallChunkEvent, InstallStream};
40
41#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
42#[ts(export, export_to = "../../../frontend/types/rpc/")]
43#[serde(rename_all = "camelCase")]
44pub struct InstallStartReq {
45    /// The agent CLI to install. The package, its version and the command it
46    /// provides come from srv's own provider registry, never from the caller:
47    /// an older client that still sends them has them ignored.
48    pub provider_id: String,
49}
50
51#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53#[serde(rename_all = "camelCase")]
54pub struct InstallCancelReq {
55    pub session_id: String,
56}
57
58#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
59#[ts(export, export_to = "../../../frontend/types/rpc/")]
60#[serde(rename_all = "camelCase")]
61pub struct InstallCheckReq {
62    pub provider_id: String,
63    pub cli_command: String,
64    /// npm package name, so the check can also report which version is
65    /// installed (read from that package's `package.json` in the per-version
66    /// cache). Optional: callers that only care about presence may omit it,
67    /// and every provider whose catalog entry has no `npmPackage` never had a
68    /// managed install to inspect in the first place.
69    #[serde(default)]
70    pub npm_package: Option<String>,
71}
72
73/// Request for `resolve.prereqs`. Was a function-local anonymous struct.
74#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
75#[ts(export, export_to = "../../../frontend/types/rpc/")]
76pub struct ResolvePrereqsReq {
77    pub tools: Vec<String>,
78    /// Tools from `tools` whose version should also be read, for prereqs with
79    /// a minimum version (e.g. a CLI that needs a recent Node). Only these are
80    /// executed (`<resolved path> --version`); every other tool stays a
81    /// path-only lookup. Names not also in `tools` are ignored.
82    #[serde(default)]
83    #[ts(optional)]
84    pub versions: Option<Vec<String>>,
85}
86
87/// Result of `install.start`. Was an inline `json!({ "sessionId": .. })`.
88#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
89#[ts(export, export_to = "../../../frontend/types/rpc/")]
90#[serde(rename_all = "camelCase")]
91pub struct InstallStartResult {
92    pub session_id: String,
93}
94
95/// Result of `install.check`.
96#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
97#[ts(export, export_to = "../../../frontend/types/rpc/")]
98#[serde(rename_all = "camelCase")]
99pub struct InstallCheckResult {
100    pub installed: bool,
101    /// Version of the managed install, when it could be read. `None` means
102    /// "not known" — never "current". The caller compares this against the
103    /// provider's pin (see `frontend/app/view/agent/providers/version-drift.ts`),
104    /// and an absent version must resolve to `unknown` rather than quietly
105    /// looking up to date.
106    ///
107    /// Read from `package.json` rather than by running `<cli> --version`: the
108    /// agent picker calls this once per card, and spawning a process per card
109    /// to answer a question a file read already answers is not a trade worth
110    /// making. The user's own copy of a provider AgentMux doesn't install
111    /// (`source: "system_path"`) has no such file, so it is asked instead.
112    pub version: Option<String>,
113    /// The CLI a launch would run, when found.
114    pub path: Option<String>,
115    /// `"local_install"` (AgentMux's own copy) or `"system_path"` (the user's,
116    /// for a provider AgentMux doesn't install), when found.
117    pub source: Option<String>,
118}
119
120/// Result of `install.cancel`.
121///
122/// `error` is genuinely `string | null`, NOT an optional property: the handler
123/// writes an explicit `Value::Null` on success, so the key is always present.
124/// The hand-written stub declared it `error?: string`, which said the key could
125/// be absent — it never is. Generating the type corrects that.
126#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
127#[ts(export, export_to = "../../../frontend/types/rpc/")]
128#[serde(rename_all = "camelCase")]
129pub struct InstallCancelResult {
130    pub success: bool,
131    pub error: Option<String>,
132}
133
134/// One tool's resolution in `resolve.prereqs`.
135#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
136#[ts(export, export_to = "../../../frontend/types/rpc/")]
137pub struct PrereqToolResolution {
138    pub tool: String,
139    pub found: bool,
140    /// Always present, null when the tool was not found.
141    pub path: Option<String>,
142    /// The tool's version, when the request asked for it (`versions`) and
143    /// it could be read. Null means "not asked" or "unknown" — never
144    /// "new enough"; the caller decides how to treat an unknown version.
145    pub version: Option<String>,
146}
147
148/// Result of `resolve.prereqs`.
149#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
150#[ts(export, export_to = "../../../frontend/types/rpc/")]
151pub struct ResolvePrereqsResult {
152    pub results: Vec<PrereqToolResolution>,
153}
154
155/// Per-session abort handle so `install.cancel` can kill an in-flight
156/// install. Also tracks `active_providers` so concurrent sessions for
157/// the *same* provider directory are rejected — without that, cancel
158/// of one would `rm_rf` the shared dir mid-install for the other.
159/// `parking_lot::Mutex` since the engine is sync at the handler
160/// boundary.
161#[derive(Default)]
162pub struct InstallSessionRegistry {
163    sessions: Mutex<std::collections::HashMap<String, tokio::sync::oneshot::Sender<()>>>,
164    active_providers: Mutex<std::collections::HashSet<String>>,
165    /// Same idea as `active_providers`, but a separate set keyed by
166    /// system-tool id (`"git"`, `"node"`, …) rather than provider id — a
167    /// distinct namespace so a future provider literally named e.g. "git"
168    /// can never collide with a system-tool claim. See
169    /// `system_install_handlers.rs` / `SPEC_SYSTEM_TOOLCHAIN_INSTALLER_2026_08_24.md`.
170    active_system_tools: Mutex<std::collections::HashSet<String>>,
171}
172
173impl InstallSessionRegistry {
174    pub fn new() -> Arc<Self> {
175        Arc::new(Self::default())
176    }
177
178    pub(crate) fn insert(&self, session_id: String, tx: tokio::sync::oneshot::Sender<()>) {
179        self.sessions.lock().insert(session_id, tx);
180    }
181
182    /// Try to claim a provider; returns false if another session is
183    /// already installing this provider.
184    pub(crate) fn try_claim_provider(&self, provider_id: &str) -> bool {
185        self.active_providers.lock().insert(provider_id.to_string())
186    }
187
188    pub(crate) fn release_provider(&self, provider_id: &str) {
189        self.active_providers.lock().remove(provider_id);
190    }
191
192    /// Try to claim a system tool (git/node/npm/python); returns false if
193    /// another session is already installing this tool.
194    pub(crate) fn try_claim_system_tool(&self, tool_id: &str) -> bool {
195        self.active_system_tools.lock().insert(tool_id.to_string())
196    }
197
198    pub(crate) fn release_system_tool(&self, tool_id: &str) {
199        self.active_system_tools.lock().remove(tool_id);
200    }
201
202    pub(crate) fn cancel(&self, session_id: &str) -> bool {
203        if let Some(tx) = self.sessions.lock().remove(session_id) {
204            let _ = tx.send(());
205            true
206        } else {
207            false
208        }
209    }
210
211    pub(crate) fn drop_session(&self, session_id: &str) {
212        self.sessions.lock().remove(session_id);
213    }
214}
215
216/// Provider ids feed into the install dir path; reject anything that
217/// could escape `~/.agentmux/<version>/cli/<provider>/`.
218fn is_safe_provider_id(s: &str) -> bool {
219    !s.is_empty()
220        && s.len() <= 64
221        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
222}
223
224/// CLI command names are joined into the bin-resolution path; same
225/// allowlist as provider ids, plus `.` (some real CLIs include dots,
226/// e.g. `eslint.cmd`).
227fn is_safe_cli_command(s: &str) -> bool {
228    !s.is_empty()
229        && s.len() <= 64
230        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
231        && !s.contains("..")
232}
233
234/// The registry entry an install of `provider_id` may use, or why there is none.
235/// What gets installed is decided here, from srv's own registry of known agent
236/// CLIs: a caller names an id and nothing else. Shared by `install.start` and
237/// `resolvecli`.
238pub(crate) fn installable_provider(
239    provider_id: &str,
240) -> Result<&'static crate::backend::providers::ProviderConfig, String> {
241    if !is_safe_provider_id(provider_id) {
242        return Err(format!("invalid provider id {provider_id:?} — must match [a-zA-Z0-9_-]+"));
243    }
244    let provider = crate::backend::providers::get_provider(provider_id)
245        .ok_or_else(|| format!("{provider_id:?} is not a known agent CLI"))?;
246    if provider.npm_package.is_empty() && !crate::backend::cli_download::is_managed_install(provider.id) {
247        return Err(format!("provider {} is not installed by AgentMux (no npm package or download)", provider.id));
248    }
249    Ok(provider)
250}
251
252/// The pinned CLI version an install of `provider_id` uses: the backend
253/// provider registry's pin (the source of truth), else the caller's.
254pub(super) fn effective_pin(provider_id: &str, requested: &str) -> String {
255    crate::backend::providers::get_provider(provider_id)
256        .map(|p| p.pinned_version.to_string())
257        .filter(|v| !v.is_empty())
258        .unwrap_or_else(|| requested.to_string())
259}
260
261/// Where a new install of `provider_id` goes: the shared, pinned-version dir
262/// (`backend::cli_install`), which is also what `resolvecli` and the launch
263/// path look in first. Honors portable / installed mode + the
264/// `AGENTMUX_HOME_OVERRIDE` test override via `DataPaths::from_env()`.
265pub(super) fn provider_install_dir(provider_id: &str, pinned_version: &str) -> Option<std::path::PathBuf> {
266    let paths = agentmux_common::DataPaths::from_env()?;
267    Some(crate::backend::cli_install::install_dir(
268        &paths,
269        provider_id,
270        pinned_version,
271    ))
272}
273
274/// Every dir an existing install of `provider_id` may be in, in lookup order:
275/// the shared pinned-version dir, then the legacy per-AgentMux-version one.
276fn provider_installed_dirs(provider_id: &str) -> Vec<std::path::PathBuf> {
277    let Some(paths) = agentmux_common::DataPaths::from_env() else {
278        return Vec::new();
279    };
280    let pin = effective_pin(provider_id, "");
281    // The shared dir only once its install is marked complete — a shim alone
282    // may be another instance's install in progress (Codex P2 on #3927).
283    crate::backend::cli_install::shared_cli_dir(&paths, provider_id, &pin)
284        .filter(|d| crate::backend::cli_install::is_complete(d))
285        .into_iter()
286        .chain(std::iter::once(
287            crate::backend::cli_install::legacy_cli_dir(&paths, provider_id),
288        ))
289        .collect()
290}
291
292/// Returns the path to the installed CLI binary if present in the
293/// per-version cache, else None. Used by `install.check`.
294/// Locate a system tool (e.g. `git`, `gh`) on this process's PATH and return
295/// its absolute path; None when it isn't there.
296///
297/// Used by `resolve.prereqs` to pre-launch-check whether a provider's
298/// system dependencies are installed. The lookup is path-only — never
299/// executes the tool. (`resolve.prereqs` runs `--version` separately, and
300/// only for tools the caller lists in `versions`.)
301/// See SPEC_PROVIDER_SYSTEM_PREREQS_2026_05_18.md.
302pub(crate) async fn resolve_tool_path(tool: &str) -> Option<String> {
303    // In-process PATH search (the `which` crate: PATHEXT-aware on Windows),
304    // not a spawned `which`/`where`. The spawn made "the lookup program is
305    // missing" indistinguishable from "the tool is missing": on a minimal
306    // Linux without `which`, node/npm read as absent and launches were
307    // blocked (Codex P2 on #3891). No console window to suppress either.
308    let tool = tool.to_string();
309    tokio::task::spawn_blocking(move || find_on_path(&tool, std::env::var_os("PATH").as_deref()))
310        .await
311        .ok()
312        .flatten()
313}
314
315/// Version of the prereq binary at `path` (already resolved on PATH), via
316/// `--version`, bounded so a hung binary can't stall the launch check.
317async fn probe_prereq_version(path: &str) -> Option<String> {
318    let path = path.to_string();
319    let probe = tokio::task::spawn_blocking(move || {
320        crate::backend::tool_store::probe_version(&path, &Some("--version".to_string()))
321    });
322    tokio::time::timeout(std::time::Duration::from_secs(5), probe)
323        .await
324        .ok()?
325        .ok()
326        .flatten()
327}
328
329/// `tool`'s absolute path in the directories of `path` (a PATH-style list).
330fn find_on_path(tool: &str, path: Option<&std::ffi::OsStr>) -> Option<String> {
331    let cwd = std::env::current_dir().ok()?;
332    which::which_in(tool, path, cwd).ok().map(|p| p.to_string_lossy().into_owned())
333}
334
335/// Version of a managed provider install, read from the installed package's
336/// own `package.json`. `None` for anything unreadable — a missing directory, a
337/// partial install, unparseable JSON — all of which mean "we do not know",
338/// which is a distinct answer from "up to date" and must stay distinct.
339///
340/// `npm_package` becomes a path segment, so the join goes through
341/// [`crate::backend::base::safe_join_within_base`] rather than an ad-hoc
342/// check. An earlier revision hand-rolled the validation (empty / `..` /
343/// leading `/` / leading `\` / NUL) and missed the Windows **drive-letter**
344/// form: `PathBuf::push("C:\\Users\\…")` REPLACES the whole path rather than
345/// appending, so `npm_package = "C:\\Users\\Victim\\AppData"` escaped the
346/// install dir entirely and read an attacker-chosen `package.json`
347/// (ReAgent P1 on #3350). That helper already rejects drive-letter and
348/// drive-relative prefixes, UNC roots, rooted paths and `..`, and accepts
349/// both separators — which is exactly why it exists and why this must not
350/// grow a second copy of the same reasoning.
351///
352/// Scoped names (`@scope/name`) are legitimate and produce one nested
353/// directory; the helper splits on `/` and `\` and handles them.
354///
355/// `dir` is the install whose shim `install.check` resolved: the version is
356/// read from that same install, never from another dir's leftover manifest —
357/// otherwise a shared dir with a manifest but no shim would lend its version
358/// to the legacy binary actually in use and hide drift (Codex P2 on #3927).
359fn installed_version_in(dir: &std::path::Path, npm_package: &str) -> Option<String> {
360    let base = dir.join("node_modules");
361    let pkg_dir = crate::backend::base::safe_join_within_base(&base, npm_package).ok()?;
362    manifest_version(&pkg_dir.join("package.json"))
363}
364
365fn manifest_version(manifest: &std::path::Path) -> Option<String> {
366    let raw = std::fs::read_to_string(manifest).ok()?;
367    let parsed: serde_json::Value = serde_json::from_str(&raw).ok()?;
368    parsed.get("version")?.as_str().map(|s| s.to_string())
369}
370
371pub(super) fn installed_bin_in(dir: &std::path::Path, cli_command: &str) -> Option<std::path::PathBuf> {
372    let managed = crate::backend::cli_download::download_bin(dir, cli_command);
373    if managed.is_file() {
374        return Some(managed);
375    }
376    let bin_dir = dir.join("node_modules").join(".bin");
377    let candidates: &[&str] = if cfg!(windows) {
378        &[".cmd", ".exe", ""]
379    } else {
380        &["", ".cmd"]
381    };
382    candidates
383        .iter()
384        .map(|suffix| bin_dir.join(format!("{cli_command}{suffix}")))
385        .find(|p| p.is_file())
386}
387
388/// The first of `dirs` holding `cli_command`'s shim — the install a launch
389/// would use. Pure over `dirs`, for tests.
390fn installed_dir_among(
391    dirs: Vec<std::path::PathBuf>,
392    cli_command: &str,
393) -> Option<std::path::PathBuf> {
394    dirs.into_iter()
395        .find(|dir| installed_bin_in(dir, cli_command).is_some())
396}
397
398fn resolve_installed_dir(provider_id: &str, cli_command: &str) -> Option<std::path::PathBuf> {
399    installed_dir_among(provider_installed_dirs(provider_id), cli_command)
400}
401
402pub fn register_install_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
403    let registry = state.install_sessions.clone();
404    let broker = state.broker.clone();
405    engine.register_typed(COMMAND_INSTALL_START, move |req: InstallStartReq, _ctx| {
406        let registry = registry.clone();
407        let broker = broker.clone();
408        async move { install_start(&registry, &broker, req) }
409    });
410
411    engine.register_typed(COMMAND_INSTALL_CHECK, move |req: InstallCheckReq, _ctx| async move {
412        install_check(req).await
413    });
414
415    engine.register_typed(COMMAND_RESOLVE_PREREQS, move |req: ResolvePrereqsReq, _ctx| async move {
416        resolve_prereqs(req).await
417    });
418
419    let registry = state.install_sessions.clone();
420    engine.register_typed(COMMAND_INSTALL_CANCEL, move |req: InstallCancelReq, _ctx| {
421        let registry = registry.clone();
422        async move { Ok(install_cancel(&registry, req)) }
423    });
424}
425
426/// `install.start`: claim the provider, record a session, and run the install in the background.
427pub(crate) fn install_start(
428    registry: &Arc<InstallSessionRegistry>,
429    broker: &Arc<Broker>,
430    req: InstallStartReq,
431) -> Result<InstallStartResult, String> {
432    let provider = installable_provider(&req.provider_id).map_err(|e| format!("install.start: {e}"))?;
433    if !registry.try_claim_provider(provider.id) {
434        return Err(format!("install.start: provider {} is already being installed in another session", provider.id));
435    }
436    let session_id = format!("install-{}", uuid::Uuid::new_v4());
437    tracing::info!(
438        session_id = %session_id,
439        provider_id = %provider.id,
440        npm_package = %provider.npm_package,
441        pinned_version = %provider.pinned_version,
442        "install.start"
443    );
444
445    let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
446    registry.insert(session_id.clone(), cancel_tx);
447
448    super::install_task::spawn_install_task(
449        broker.clone(),
450        registry.clone(),
451        session_id.clone(),
452        provider.id.to_string(),
453        provider.cli_command.to_string(),
454        provider.npm_package.to_string(),
455        provider.pinned_version.to_string(),
456        cancel_rx,
457    );
458
459    Ok(InstallStartResult { session_id })
460}
461
462/// `install.check`: whether the provider's CLI is there, and which version.
463pub(crate) async fn install_check(req: InstallCheckReq) -> Result<InstallCheckResult, String> {
464    if !is_safe_provider_id(&req.provider_id) {
465        return Err(format!("install.check: invalid provider id {:?}", req.provider_id));
466    }
467    if !is_safe_cli_command(&req.cli_command) {
468        return Err(format!("install.check: invalid cli command {:?}", req.cli_command));
469    }
470    // The one lookup a launch uses (`locate_provider_cli`), so the
471    // agent picker and the Toolchain pane give the same answer: an
472    // npm provider's own install only, and the user's copy only for
473    // a provider AgentMux doesn't install.
474    let located = crate::server::cli_handlers::locate_provider_cli(&req.provider_id).await;
475    let version = match &located {
476        // Read from the install's package.json, not by running it
477        // (one check per picker card): only meaningful when the
478        // CLI is actually there, and read from that same install.
479        Some(l) if l.source == crate::server::cli_handlers::CliSource::LocalInstall => {
480            resolve_installed_dir(&req.provider_id, &req.cli_command).and_then(|dir| match req.npm_package.as_deref() {
481                Some(pkg) => installed_version_in(&dir, pkg),
482                // A release download has no package.json: its completion marker holds the pin.
483                None => std::fs::read_to_string(dir.join(crate::backend::cli_install::COMPLETE_MARKER))
484                    .ok()
485                    .map(|v| v.trim().to_string())
486                    .filter(|v| !v.is_empty()),
487            })
488        }
489        // The user's own copy has no package.json of ours: ask it.
490        // Only the few providers AgentMux doesn't install get here.
491        Some(l) => Some(crate::server::cli_handlers::get_cli_version(&l.path).await)
492            .filter(|v| !v.is_empty() && v != "unknown"),
493        None => None,
494    };
495    Ok(InstallCheckResult {
496        installed: located.is_some(),
497        version,
498        path: located.as_ref().map(|l| l.path.clone()),
499        source: located.map(|l| l.source.as_str().to_string()),
500    })
501}
502
503/// `resolve.prereqs`: where each named tool is, and its version for those that asked.
504pub(crate) async fn resolve_prereqs(req: ResolvePrereqsReq) -> Result<ResolvePrereqsResult, String> {
505    let mut results = Vec::with_capacity(req.tools.len());
506    for tool in &req.tools {
507        if !is_safe_cli_command(tool) {
508            return Err(format!("resolve.prereqs: invalid tool name {:?}", tool));
509        }
510        let path = resolve_tool_path(tool).await;
511        let wants_version = req.versions.as_deref().is_some_and(|v| v.iter().any(|t| t == tool));
512        let version = match (&path, wants_version) {
513            (Some(p), true) => probe_prereq_version(p).await,
514            _ => None,
515        };
516        results.push(PrereqToolResolution { tool: tool.clone(), found: path.is_some(), path, version });
517    }
518    Ok(ResolvePrereqsResult { results })
519}
520
521/// `install.cancel`.
522pub(crate) fn install_cancel(registry: &Arc<InstallSessionRegistry>, req: InstallCancelReq) -> InstallCancelResult {
523    let ok = registry.cancel(&req.session_id);
524    InstallCancelResult {
525        success: ok,
526        error: if ok { None } else { Some(format!("unknown or already-terminal session: {}", req.session_id)) },
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::{find_on_path, is_safe_cli_command, is_safe_provider_id};
533
534    /// The lookup is in-process: a PATH holding only the tool (no `which`
535    /// binary anywhere on it) still finds it. Codex P2 on #3891.
536    #[test]
537    fn find_on_path_needs_no_which_binary() {
538        let dir = tempfile::tempdir().unwrap();
539        let name = if cfg!(windows) { "node.exe" } else { "node" };
540        let exe = dir.path().join(name);
541        std::fs::write(&exe, b"").unwrap();
542        #[cfg(unix)]
543        {
544            use std::os::unix::fs::PermissionsExt;
545            std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
546        }
547        let found = find_on_path("node", Some(dir.path().as_os_str())).expect("node found");
548        assert_eq!(std::path::Path::new(&found), exe.as_path());
549        assert!(find_on_path("npm", Some(dir.path().as_os_str())).is_none());
550    }
551
552    #[test]
553    fn safe_provider_ids_accepted() {
554        for id in ["claude", "claude-code", "open_claw", "Codex42"] {
555            assert!(is_safe_provider_id(id), "{id} should be accepted");
556        }
557    }
558
559    #[test]
560    fn unsafe_provider_ids_rejected() {
561        for id in [
562            "",
563            "../escape",
564            "a/b",
565            "a\\b",
566            "a b",
567            ".",
568            "..",
569            "a..b",
570            "a/../b",
571            "\0null",
572            &"x".repeat(65),
573        ] {
574            assert!(!is_safe_provider_id(id), "{id:?} should be rejected");
575        }
576    }
577
578    #[test]
579    fn safe_cli_commands_accepted() {
580        for cmd in ["claude", "claude-code", "kimi.cmd", "agentmux-srv", "open_claw"] {
581            assert!(is_safe_cli_command(cmd), "{cmd} should be accepted");
582        }
583    }
584
585    #[test]
586    fn unsafe_cli_commands_rejected() {
587        for cmd in [
588            "",
589            "../etc/passwd",
590            "../../etc/passwd",
591            "a/b",
592            "a\\b",
593            "a b",
594            "..",
595            "a..b",
596            "a/../b",
597            "\0null",
598            &"x".repeat(65),
599        ] {
600            assert!(!is_safe_cli_command(cmd), "{cmd:?} should be rejected");
601        }
602    }
603}
604
605// Request/result shape tests for the four install-related commands.
606#[cfg(test)]
607mod req_shape_tests {
608    use super::*;
609    use serde_json::json;
610
611    #[test]
612    fn install_chunk_events_serialize_as_before() {
613        let line = InstallChunkEvent::line("s1", "added 3 packages".into(), InstallStream::Stderr);
614        assert_eq!(serde_json::to_value(&line).unwrap(), json!({ "sessionId": "s1", "line": "added 3 packages", "stream": "stderr" }));
615        let done = InstallChunkEvent::done("s1", false, json!(None::<String>));
616        assert_eq!(serde_json::to_value(&done).unwrap(), json!({ "sessionId": "s1", "op": "done", "ok": false, "error": null }));
617    }
618
619    // These structs rely on rename_all = "camelCase" to match the wire. Drop
620    // that attribute and everything still compiles and the binding still
621    // generates -- it just silently stops parsing real payloads.
622    #[test]
623    fn the_requests_accept_the_camel_case_payloads_the_stub_sends() {
624        let start: InstallStartReq = serde_json::from_value(json!({ "providerId": "claude" })).expect("install.start");
625        assert_eq!(start.provider_id, "claude");
626
627        // A client that still sends the package fields is understood; they are not read.
628        let older: InstallStartReq = serde_json::from_value(json!({
629            "providerId": "claude",
630            "cliCommand": "claude",
631            "npmPackage": "some-other-package",
632            "pinnedVersion": "9.9.9",
633        }))
634        .expect("install.start from an older client");
635        assert_eq!(older.provider_id, "claude");
636
637        serde_json::from_value::<InstallCancelReq>(json!({"sessionId": "s1"}))
638            .expect("install.cancel");
639        serde_json::from_value::<InstallCheckReq>(
640            json!({"providerId": "claude", "cliCommand": "claude"}),
641        )
642        .expect("install.check");
643        serde_json::from_value::<ResolvePrereqsReq>(json!({"tools": ["node", "git"]}))
644            .expect("resolve.prereqs");
645        let with_versions = serde_json::from_value::<ResolvePrereqsReq>(
646            json!({"tools": ["node", "git"], "versions": ["node"]}),
647        )
648        .expect("resolve.prereqs with versions");
649        assert_eq!(with_versions.versions.as_deref(), Some(&["node".to_string()][..]));
650
651        assert!(
652            serde_json::from_value::<InstallCancelReq>(json!({"session_id": "s1"})).is_err(),
653            "snake_case is not the wire format for these"
654        );
655    }
656
657    // THE DRIFT THIS SLICE FIXES. The handler writes an explicit null for
658    // `error` on success, so the key is ALWAYS present. The hand-written stub
659    // said `error?: string`, i.e. the key may be absent -- it never is.
660    #[test]
661    fn cancel_result_always_carries_the_error_key() {
662        let ok = serde_json::to_value(InstallCancelResult { success: true, error: None })
663            .expect("serializable");
664        assert_eq!(ok, json!({"success": true, "error": null}));
665        assert!(
666            ok.as_object().unwrap().contains_key("error"),
667            "error is `string | null`, not an optional property"
668        );
669    }
670
671    #[test]
672    fn prereq_results_carry_a_nullable_path() {
673        let v = serde_json::to_value(ResolvePrereqsResult {
674            results: vec![PrereqToolResolution {
675                tool: "node".to_string(),
676                found: false,
677                path: None,
678                version: None,
679            }],
680        })
681        .expect("serializable");
682        assert_eq!(
683            v,
684            json!({"results": [{"tool": "node", "found": false, "path": null, "version": null}]})
685        );
686    }
687}
688
689#[cfg(test)]
690mod installed_version_tests {
691    use super::installed_version_in;
692
693    fn read_installed_version(_provider: &str, npm_package: &str) -> Option<String> {
694        installed_version_in(
695            &std::env::temp_dir().join("agentmux-no-such-install"),
696            npm_package,
697        )
698    }
699
700    /// The npm package name becomes a path segment, so a hostile or malformed
701    /// one must be rejected BEFORE any filesystem access. These cases return
702    /// early on the validation branch, so they hold regardless of whether a
703    /// data dir exists in the test environment — which is also why they are
704    /// the part worth pinning: the happy path needs a real per-version cache,
705    /// but the rejection path is pure and is the one with teeth.
706    ///
707    /// The drive-letter cases are the ones an earlier revision of this
708    /// function got wrong (ReAgent P1 on #3350): `PathBuf::push` REPLACES the
709    /// path when the pushed component carries a drive prefix, so these escaped
710    /// the install dir entirely while a `starts_with('/')`/`starts_with('\\')`
711    /// check waved them through. They are listed explicitly so a future
712    /// refactor back to a hand-rolled check fails here instead of shipping.
713    #[test]
714    fn rejects_path_escapes_and_malformed_package_names() {
715        for bad in [
716            "",
717            "..",
718            "../../../etc/passwd",
719            "@scope/../../escape",
720            "/absolute/path",
721            "\\windows\\absolute",
722            "has\0null",
723            "C:\\Users\\Victim\\AppData",
724            "C:/some/dir",
725            "C:payload.txt",
726            "\\\\server\\share\\evil",
727        ] {
728            assert_eq!(
729                read_installed_version("claude", bad),
730                None,
731                "expected {bad:?} to be rejected"
732            );
733        }
734    }
735
736    /// A legitimate scoped name (`@anthropic-ai/claude-code`) must NOT be
737    /// caught by the escape check — it is the common case, and one nested
738    /// directory is exactly what npm creates for it. Returns None here only
739    /// because no such install exists in the test environment; the assertion
740    /// that matters is that it does not panic and is not rejected for the
741    /// wrong reason.
742    #[test]
743    fn scoped_package_names_are_not_treated_as_escapes() {
744        let _ = read_installed_version("claude", "@anthropic-ai/claude-code");
745    }
746
747    /// Codex P2 on #3927: the version comes from the install whose shim is
748    /// used. A completed shared dir that lost its shim (manifest still there)
749    /// must not lend its version to the legacy binary actually launched.
750    #[test]
751    fn the_version_is_read_from_the_install_whose_shim_is_used() {
752        use super::installed_dir_among;
753        let (pkg, cli) = ("@anthropic-ai/claude-code", "claude");
754        let manifest = |dir: &std::path::Path| {
755            dir.join("node_modules")
756                .join("@anthropic-ai")
757                .join("claude-code")
758                .join("package.json")
759        };
760        let install = |dir: &std::path::Path, version: &str, shim: bool| {
761            let m = manifest(dir);
762            std::fs::create_dir_all(m.parent().unwrap()).unwrap();
763            std::fs::write(&m, format!(r#"{{"version":"{version}"}}"#)).unwrap();
764            if shim {
765                let bin = dir.join("node_modules").join(".bin");
766                std::fs::create_dir_all(&bin).unwrap();
767                let name = if cfg!(windows) {
768                    "claude.cmd"
769                } else {
770                    "claude"
771                };
772                std::fs::write(bin.join(name), "").unwrap();
773            }
774        };
775        let tmp = tempfile::tempdir().unwrap();
776        let (shared, legacy) = (tmp.path().join("shared"), tmp.path().join("legacy"));
777        install(&shared, "2.1.280", false);
778        install(&legacy, "2.1.100", true);
779        let dir = installed_dir_among(vec![shared.clone(), legacy.clone()], cli)
780            .expect("the legacy shim");
781        assert_eq!(dir, legacy);
782        assert_eq!(installed_version_in(&dir, pkg).as_deref(), Some("2.1.100"));
783
784        // With both shims present the shared install wins, with its own version.
785        install(&shared, "2.1.280", true);
786        let dir = installed_dir_among(vec![shared.clone(), legacy], cli).unwrap();
787        assert_eq!(dir, shared);
788        assert_eq!(installed_version_in(&dir, pkg).as_deref(), Some("2.1.280"));
789
790        // The used install's manifest unreadable: "unknown", not another
791        // install's version.
792        std::fs::write(manifest(&shared), "not json").unwrap();
793        assert_eq!(installed_version_in(&shared, pkg), None);
794    }
795
796    /// A release download is an install too, or `install.start` rebuilds a finished one and `install.check` loses
797    /// its version (#6618).
798    #[test]
799    fn a_release_download_counts_as_installed() {
800        use super::installed_dir_among;
801        let tmp = tempfile::tempdir().unwrap();
802        let (download, empty) = (tmp.path().join("dl"), tmp.path().join("none"));
803        let bin = crate::backend::cli_download::download_bin(&download, "grok");
804        std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
805        std::fs::write(&bin, "").unwrap();
806        std::fs::create_dir_all(&empty).unwrap();
807        assert_eq!(installed_dir_among(vec![empty.clone(), download.clone()], "grok"), Some(download));
808        assert_eq!(installed_dir_among(vec![empty], "grok"), None);
809    }
810}
811
812#[cfg(test)]
813mod registry_only_tests {
814    use super::*;
815
816    async fn start(engine: &Arc<WshRpcEngine>, out: &mut tokio::sync::mpsc::UnboundedReceiver<crate::backend::rpc_types::RpcMessage>, data: serde_json::Value) -> crate::backend::rpc_types::RpcMessage {
817        engine.handle_message(crate::backend::rpc_types::RpcMessage {
818            command: COMMAND_INSTALL_START.to_string(),
819            reqid: "r1".to_string(),
820            data: Some(data),
821            ..Default::default()
822        });
823        tokio::time::timeout(std::time::Duration::from_secs(2), out.recv()).await.unwrap().unwrap()
824    }
825
826    #[test]
827    fn every_installable_provider_is_installed_from_its_own_registry_entry() {
828        let mut seen = 0;
829        for p in crate::backend::providers::all_providers().filter(|p| !p.npm_package.is_empty()) {
830            let got = installable_provider(p.id).expect(p.id);
831            assert_eq!(got.id, p.id);
832            assert_eq!(got.npm_package, p.npm_package);
833            seen += 1;
834        }
835        assert!(seen > 0);
836    }
837
838    /// Every provider with no npm package is installed by AgentMux's own download or uv install, so
839    /// each one is accepted here (the refusal for one that is not has no provider to try it on).
840    #[test]
841    fn every_provider_with_no_npm_package_is_installed_by_a_download() {
842        let mut seen = 0;
843        for p in crate::backend::providers::all_providers().filter(|p| p.npm_package.is_empty()) {
844            assert!(crate::backend::cli_download::is_managed_install(p.id), "{} has no npm package and no managed download", p.id);
845            assert!(installable_provider(p.id).is_ok(), "{}", p.id);
846            seen += 1;
847        }
848        assert!(seen >= 2);
849    }
850
851    #[test]
852    fn an_id_outside_the_registry_is_refused() {
853        for id in ["", "no-such-agent", "left-pad", "../claude", "claude/../../x", "@scope/pkg", "claude ", "C:\\x"] {
854            assert!(installable_provider(id).is_err(), "{id:?}");
855        }
856    }
857
858    #[tokio::test]
859    async fn install_start_refuses_an_unknown_provider_even_when_it_names_a_package() {
860        let state = crate::server::tests::test_state();
861        let (engine, mut out) = WshRpcEngine::new();
862        register_install_handlers(&engine, &state);
863        let resp = start(
864            &engine,
865            &mut out,
866            serde_json::json!({
867                "providerId": "no-such-agent",
868                "cliCommand": "no-such-agent",
869                "npmPackage": "left-pad",
870                "pinnedVersion": "1.0.0",
871            }),
872        )
873        .await;
874        assert!(resp.data.is_none(), "{resp:?}");
875        assert!(resp.error.contains("not a known agent CLI"), "{resp:?}");
876        assert!(state.install_sessions.sessions.lock().is_empty(), "no session was started");
877        assert!(state.install_sessions.active_providers.lock().is_empty(), "nothing was claimed");
878    }
879
880    #[tokio::test]
881    async fn cancelling_a_session_nobody_started_says_so() {
882        let state = crate::server::tests::test_state();
883        let result = install_cancel(&state.install_sessions, InstallCancelReq { session_id: "install-nope".into() });
884        assert!(!result.success);
885        assert_eq!(result.error.as_deref(), Some("unknown or already-terminal session: install-nope"));
886    }
887
888    #[tokio::test]
889    async fn install_check_refuses_an_unsafe_provider_id_or_cli_command() {
890        let req = |provider: &str, cli: &str| InstallCheckReq {
891            provider_id: provider.into(),
892            cli_command: cli.into(),
893            npm_package: None,
894        };
895        let err = install_check(req("../claude", "claude")).await.err().unwrap();
896        assert!(err.starts_with("install.check: invalid provider id"), "{err}");
897        let err = install_check(req("claude", "claude; rm -rf /")).await.err().unwrap();
898        assert!(err.starts_with("install.check: invalid cli command"), "{err}");
899    }
900
901    #[tokio::test]
902    async fn resolve_prereqs_refuses_an_unsafe_tool_name_and_answers_nothing_for_no_tools() {
903        let err = resolve_prereqs(ResolvePrereqsReq { tools: vec!["git".into(), "a b".into()], versions: None }).await.err().unwrap();
904        assert!(err.starts_with("resolve.prereqs: invalid tool name"), "{err}");
905        let none = resolve_prereqs(ResolvePrereqsReq { tools: vec![], versions: None }).await.unwrap();
906        assert!(none.results.is_empty());
907    }
908
909    #[tokio::test]
910    async fn install_start_refuses_without_claiming_when_called_directly() {
911        let state = crate::server::tests::test_state();
912        let req = InstallStartReq { provider_id: "no-such-agent".into() };
913        let err = install_start(&state.install_sessions, &state.broker, req).err().unwrap();
914        assert!(err.starts_with("install.start: ") && err.contains("not a known agent CLI"), "{err}");
915        assert!(state.install_sessions.active_providers.lock().is_empty());
916    }
917}