Skip to main content

agentmux_srv/server/
install_task.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The background task an `install.start` runs: take the install lock, reuse or
5//! clear what another instance left, run `npm install` (or a release download),
6//! publish every line of its output as `install_chunk` events, and end with one
7//! `done` event. Every way out releases the session and the provider.
8//!
9//! `install_handlers.rs` owns the RPC handlers and the lookups; this file owns the
10//! run, one step per function, in the order the run takes them.
11
12#[cfg(windows)]
13use agentmux_common::win32::NoWindow;
14use std::path::Path;
15use std::sync::Arc;
16
17use parking_lot::Mutex;
18use serde_json::json;
19use tokio::task::JoinHandle;
20
21use super::install_handlers::{effective_pin, installed_bin_in, provider_install_dir, InstallChunkEvent, InstallSessionRegistry, InstallStream};
22use crate::backend::cli_install;
23use crate::backend::mps::Broker;
24
25/// How many lines of npm output a failed install logs.
26const INSTALL_LOG_TAIL_LINES: usize = 20;
27
28type OutputTail = Arc<Mutex<std::collections::VecDeque<String>>>;
29
30/// What one install session publishes to, and releases when it ends.
31struct InstallRun {
32    broker: Arc<Broker>,
33    registry: Arc<InstallSessionRegistry>,
34    session_id: String,
35    provider_id: String,
36    /// `install:<sessionId>`, the scope every event of the session carries.
37    scope: String,
38    /// The last lines npm printed, for the log when an install fails: the dialog
39    /// shows the whole output, but nothing else kept it, so a failed install left
40    /// no trace of why (only `install.start` was logged).
41    tail: OutputTail,
42}
43
44/// What `install.start` asked for, as the registry resolved it.
45struct InstallJob {
46    cli_command: String,
47    npm_package: String,
48    pinned_version: String,
49}
50
51impl InstallRun {
52    fn log_done(&self, ok: bool, error: Option<&str>) {
53        if ok {
54            tracing::info!(session_id = %self.session_id, provider_id = %self.provider_id, "install.done");
55        } else {
56            let tail = self.tail.lock().iter().cloned().collect::<Vec<_>>().join(" | ");
57            tracing::warn!(
58                session_id = %self.session_id,
59                provider_id = %self.provider_id,
60                error = error.unwrap_or(""),
61                npm_tail = %tail,
62                "install.failed"
63            );
64        }
65    }
66
67    fn emit_line(&self, line: String, stream: InstallStream) {
68        self.broker.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::line(&self.session_id, line, stream), vec![self.scope.clone()], 1024);
69    }
70
71    /// The `done` event with a free-text `error`.
72    fn emit_done(&self, ok: bool, error: Option<String>) {
73        self.log_done(ok, error.as_deref());
74        self.broker.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::done(&self.session_id, ok, json!(error)), vec![self.scope.clone()], 1024);
75    }
76
77    /// The `done` event with the wire-format `AgentMuxError`, so the frontend can
78    /// render a friendly `<ErrorBanner />`.
79    fn emit_done_typed(&self, err: agentmux_common::AgentMuxError) {
80        self.log_done(false, Some(&err.to_string()));
81        self.broker.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::done(&self.session_id, false, err.to_wire()), vec![self.scope.clone()], 1024);
82    }
83
84    /// Forget the session and let another one install this provider.
85    fn end(&self) {
86        self.registry.drop_session(&self.session_id);
87        self.registry.release_provider(&self.provider_id);
88    }
89
90    /// A failed install: the `done` event, then release.
91    fn fail(&self, error: String) {
92        self.emit_done(false, Some(error));
93        self.end();
94    }
95
96    /// Publish each line `reader` yields, and keep it in the tail for the log.
97    fn pipe_lines<R>(&self, reader: R, stream: InstallStream) -> JoinHandle<()>
98    where
99        R: tokio::io::AsyncRead + Send + Unpin + 'static,
100    {
101        use tokio::io::{AsyncBufReadExt, BufReader};
102        let (broker, session_id, scope, tail) = (self.broker.clone(), self.session_id.clone(), self.scope.clone(), self.tail.clone());
103        tokio::spawn(async move {
104            let mut lines = BufReader::new(reader).lines();
105            while let Ok(Some(line)) = lines.next_line().await {
106                push_tail(&tail, &line);
107                broker.publish_event::<crate::backend::mps_events::InstallChunk>(&InstallChunkEvent::line(&session_id, line, stream), vec![scope.clone()], 1024);
108            }
109        })
110    }
111}
112
113/// Run an `install.start` in the background.
114#[allow(clippy::too_many_arguments)]
115pub(crate) fn spawn_install_task(
116    broker: Arc<Broker>,
117    registry: Arc<InstallSessionRegistry>,
118    session_id: String,
119    provider_id: String,
120    cli_command: String,
121    npm_package: String,
122    pinned_version: String,
123    cancel_rx: tokio::sync::oneshot::Receiver<()>,
124) {
125    let scope = format!("install:{}", session_id);
126    let run = InstallRun { broker, registry, session_id, provider_id, scope, tail: Arc::default() };
127    let job = InstallJob { cli_command, npm_package, pinned_version };
128    tokio::spawn(run_install(run, job, cancel_rx));
129}
130
131async fn run_install(run: InstallRun, job: InstallJob, mut cancel_rx: tokio::sync::oneshot::Receiver<()>) {
132    // One pin decides both the dir and the package version, so an
133    // install can never put version X in a dir named for version Y.
134    let pin = effective_pin(&run.provider_id, &job.pinned_version);
135    let Some(provider_dir) = provider_install_dir(&run.provider_id, &pin) else {
136        run.fail("cannot determine home directory".into());
137        return;
138    };
139    let shared_dir = agentmux_common::DataPaths::from_env().and_then(|p| cli_install::shared_cli_dir(&p, &run.provider_id, &pin));
140
141    // Held until this task ends.
142    let _install_guard = match acquire_install_lock(&run, &pin, &mut cancel_rx).await {
143        Ok(guard) => guard,
144        Err(error) => return run.fail(error),
145    };
146    if let Some(dir) = shared_dir.as_deref() {
147        match reuse_or_clear(dir, &job.cli_command) {
148            Ok(true) => {
149                run.emit_line("already installed by another AgentMux instance".to_string(), InstallStream::Stdout);
150                run.emit_done(true, None);
151                return run.end();
152            }
153            Ok(false) => {}
154            Err(error) => return run.fail(error),
155        }
156    }
157    // A release download, not an npm package (`backend::cli_download`).
158    if crate::backend::cli_download::is_managed_install(&run.provider_id) {
159        let res = run_download_install(&run.provider_id, &job.cli_command, &run.broker, (&run.session_id, &run.scope), &mut cancel_rx).await;
160        run.emit_done(res.is_ok(), res.err());
161        return run.end();
162    }
163    // Makes the folder too, with the public registry and an empty npm config (cli_install.rs).
164    let isolation = match cli_install::npm_isolation_args(&provider_dir) {
165        Ok(isolation) => isolation,
166        Err(e) => {
167            // Disk-full, permission-denied and path-not-found go to the typed catalog so the
168            // frontend shows a friendly message, not the raw OS error; other kinds stay Legacy.
169            run.emit_done_typed(agentmux_common::AgentMuxError::from_io_with_path(provider_dir.display().to_string(), e));
170            return run.end();
171        }
172    };
173    let npm_args = npm_install_args(&run.provider_id, &job, &pin, &provider_dir, isolation);
174    run.emit_line(format!("$ npm {}", npm_args.join(" ")), InstallStream::Stdout);
175
176    let mut child = match spawn_npm(&npm_args) {
177        Ok(c) => c,
178        Err(e) => return run.fail(format!("spawn npm: {e}")),
179    };
180    let stdout_task = run.pipe_lines(child.stdout.take().expect("piped"), InstallStream::Stdout);
181    let stderr_task = run.pipe_lines(child.stderr.take().expect("piped"), InstallStream::Stderr);
182
183    tokio::select! {
184        wait = child.wait() => {
185            let _ = stdout_task.await;
186            let _ = stderr_task.await;
187            conclude_npm_exit(&run, wait, &provider_dir, shared_dir.as_deref(), &job.cli_command, &pin);
188        }
189        _ = &mut cancel_rx => {
190            tracing::info!(session_id = %run.session_id, "install.cancel: killing child");
191            let _ = child.kill().await;
192            let _ = stdout_task.await;
193            let _ = stderr_task.await;
194            remove_partial_install(&run, &provider_dir);
195            run.emit_done(false, Some("cancelled".into()));
196        }
197    }
198    run.end();
199}
200
201/// The shared dir is written by every AgentMux instance on this
202/// machine: serialize on its install lock. Waiting for another instance's
203/// install must stay cancellable, so poll the lock and race `install.cancel`
204/// instead of blocking in it: a blocking wait would ignore cancel, keep the
205/// provider claimed, and could later report success for a cancelled session
206/// (#3927). The error is the message of the `done` event.
207async fn acquire_install_lock(
208    run: &InstallRun,
209    pin: &str,
210    cancel_rx: &mut tokio::sync::oneshot::Receiver<()>,
211) -> Result<cli_install::InstallGuard, String> {
212    loop {
213        let lock_provider = run.provider_id.clone();
214        let lock_pin = pin.to_string();
215        let res = tokio::task::spawn_blocking(move || {
216            let paths = agentmux_common::DataPaths::from_env().ok_or_else(|| std::io::Error::other("DataPaths::from_env() failed"))?;
217            cli_install::try_lock_install(&paths, &lock_provider, &lock_pin)
218        })
219        .await;
220        match res {
221            Ok(Ok(Some(guard))) => return Ok(guard),
222            Ok(Ok(None)) => {
223                tokio::select! {
224                    _ = tokio::time::sleep(std::time::Duration::from_millis(200)) => continue,
225                    _ = &mut *cancel_rx => {
226                        tracing::info!(session_id = %run.session_id, "install.cancel: cancelled while waiting for another instance's install");
227                        return Err("cancelled".into());
228                    }
229                }
230            }
231            Ok(Err(e)) => return Err(format!("cannot take the CLI install lock: {e}")),
232            Err(e) => return Err(format!("install lock task panicked: {e}")),
233        }
234    }
235}
236
237/// Reuse only a FINISHED install (completion marker, not just a shim npm may
238/// have written early); clear a failed or interrupted one. `Ok(true)`: there is
239/// a finished install to reuse.
240fn reuse_or_clear(dir: &Path, cli_command: &str) -> Result<bool, String> {
241    if cli_install::is_complete(dir) && installed_bin_in(dir, cli_command).is_some() {
242        return Ok(true);
243    }
244    cli_install::clear_unless_valid(dir, cli_command)
245        .map(|()| false)
246        .map_err(|e| format!("cannot clear an incomplete install at {}: {e}", dir.display()))
247}
248
249/// The arguments of the one `npm install` run: the pinned package plus any
250/// companions (pi-acp's `pi`) in one run, one dir, one completion marker, then
251/// the isolation flags.
252fn npm_install_args(provider_id: &str, job: &InstallJob, pin: &str, provider_dir: &Path, isolation: Vec<String>) -> Vec<String> {
253    let pkg_args: Vec<String> = match crate::backend::providers::get_provider(provider_id) {
254        Some(p) if p.npm_package == job.npm_package => p.npm_install_specs(pin),
255        _ if pin.is_empty() => vec![job.npm_package.clone()],
256        _ => vec![format!("{}@{}", job.npm_package, pin)],
257    };
258    // `--progress=false` is unconditional: npm only renders the
259    // progress bar when both stdout and stderr are TTYs, and this
260    // task pipes both, so leaving progress at the default would
261    // produce no visible spinner anyway. `--loglevel=verbose` is
262    // also unconditional: the user's only signal of progress
263    // during long installs is the per-package fetch/extract
264    // chatter, so we always pay for the noise to gain the signal.
265    let mut args: Vec<String> = std::iter::once("install".to_string())
266        .chain(pkg_args)
267        .chain([
268            "--prefix".to_string(),
269            provider_dir.to_string_lossy().to_string(),
270            "--no-audit".to_string(),
271            "--no-fund".to_string(),
272            "--progress=false".to_string(),
273            "--loglevel=verbose".to_string(),
274            // A user's legacy-peer-deps would skip a package's peers.
275            "--legacy-peer-deps=false".to_string(),
276        ])
277        .collect();
278    args.extend(isolation);
279    args
280}
281
282fn spawn_npm(args: &[String]) -> std::io::Result<tokio::process::Child> {
283    use std::process::Stdio;
284    let mut cmd = tokio::process::Command::new(if cfg!(windows) { "npm.cmd" } else { "npm" });
285    // `npm install` runs arbitrary postinstall scripts — the textbook case for
286    // not handing a process this instance's identity or API endpoint.
287    crate::backend::pane_env::sanitize_external_command(&mut cmd);
288    cmd.args(args);
289    cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
290    #[cfg(windows)]
291    {
292        cmd.no_window(); // CREATE_NO_WINDOW
293    }
294    cmd.spawn()
295}
296
297/// npm ended on its own: publish the one `done` event for how.
298fn conclude_npm_exit(
299    run: &InstallRun,
300    wait: std::io::Result<std::process::ExitStatus>,
301    provider_dir: &Path,
302    shared_dir: Option<&Path>,
303    cli_command: &str,
304    pin: &str,
305) {
306    match wait {
307        Ok(s) if s.success() => {
308            // npm exit 0 ≠ "binary is on disk". Verify the
309            // expected bin shim exists so a package/bin
310            // rename or provider-config mismatch surfaces
311            // as an install failure rather than a phantom
312            // launch with a non-existent cmd path.
313            if installed_bin_in(provider_dir, cli_command).is_some() {
314                // Still under the install lock: publish the shared
315                // install to every reader only now that it's verified.
316                let marked = match shared_dir {
317                    Some(dir) => cli_install::mark_complete(dir, pin),
318                    None => Ok(()),
319                };
320                match marked {
321                    Ok(()) => run.emit_done(true, None),
322                    Err(e) => run.emit_done(false, Some(format!("cannot mark the install complete: {e}"))),
323                }
324            } else {
325                run.emit_done(
326                    false,
327                    Some(format!("npm install reported success but {} not found in {}/node_modules/.bin/", cli_command, provider_dir.display())),
328                );
329            }
330        }
331        Ok(s) => run.emit_done(false, Some(format!("npm exited {:?}", s.code()))),
332        Err(e) => run.emit_done(false, Some(format!("wait: {e}"))),
333    }
334}
335
336/// Wipe the partial install of a cancelled run so a retry doesn't inherit a
337/// half-written package-lock.json. Best-effort — logging only on failure.
338fn remove_partial_install(run: &InstallRun, provider_dir: &Path) {
339    if let Err(e) = std::fs::remove_dir_all(provider_dir) {
340        // Best-effort cleanup; tag the log with the typed
341        // code so grouped support requests can grep by
342        // `amx_code` rather than free-text matching.
343        let mux = agentmux_common::AgentMuxError::from_io_with_path(provider_dir.display().to_string(), e);
344        tracing::warn!(
345            target: "amx::error",
346            session_id = %run.session_id,
347            amx_code = %mux.code(),
348            provider_dir = %provider_dir.display(),
349            error = %mux,
350            "install.cancel: remove partial dir failed"
351        );
352    }
353}
354
355/// An `install.start` for a provider that is a release download: fetch the
356/// pinned file, check its hash, unpack, publish. Output lines go to the
357/// session; `install.cancel` stops the transfer and removes the partial dir.
358async fn run_download_install(
359    provider_id: &str,
360    cli_command: &str,
361    broker: &Arc<Broker>,
362    (session_id, scope): (&str, &str),
363    cancel_rx: &mut tokio::sync::oneshot::Receiver<()>,
364) -> Result<(), String> {
365    let paths = agentmux_common::DataPaths::from_env().ok_or("cannot determine home directory")?;
366    let on_line = |_: &'static str, line: &str| {
367        broker.publish_event::<crate::backend::mps_events::InstallChunk>(
368            &InstallChunkEvent::line(session_id, line.to_string(), InstallStream::Stdout),
369            vec![scope.to_string()],
370            1024,
371        );
372    };
373    let stop = std::sync::atomic::AtomicBool::new(false);
374    let run = crate::backend::cli_download::install_managed_into(&paths, provider_id, cli_command, &on_line, &stop);
375    tokio::pin!(run);
376    let outcome = tokio::select! {
377        r = &mut run => r,
378        _ = &mut *cancel_rx => {
379            stop.store(true, std::sync::atomic::Ordering::Relaxed);
380            (&mut run).await
381        }
382    };
383    outcome.map(|_| ()).map_err(|e| e.to_string())
384}
385
386fn push_tail(tail: &Mutex<std::collections::VecDeque<String>>, line: &str) {
387    let mut tail = tail.lock();
388    if tail.len() == INSTALL_LOG_TAIL_LINES {
389        tail.pop_front();
390    }
391    tail.push_back(line.to_string());
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn the_log_keeps_only_the_last_lines_of_npm_output() {
400        let tail = parking_lot::Mutex::new(std::collections::VecDeque::new());
401        for i in 0..(INSTALL_LOG_TAIL_LINES + 5) {
402            push_tail(&tail, &format!("line {i}"));
403        }
404        let tail = tail.lock();
405        assert_eq!(tail.len(), INSTALL_LOG_TAIL_LINES);
406        assert_eq!(tail.front().map(String::as_str), Some("line 5"));
407        assert_eq!(tail.back().cloned(), Some(format!("line {}", INSTALL_LOG_TAIL_LINES + 4)));
408    }
409
410    #[test]
411    fn the_npm_arguments_name_the_pinned_package_the_prefix_and_then_the_isolation_flags() {
412        let job = InstallJob { cli_command: "tool".into(), npm_package: "@scope/not-a-provider".into(), pinned_version: String::new() };
413        let args = npm_install_args("no-such-provider", &job, "1.2.3", Path::new("/p/dir"), vec!["--registry=x".into()]);
414        assert_eq!(
415            args,
416            [
417                "install",
418                "@scope/not-a-provider@1.2.3",
419                "--prefix",
420                "/p/dir",
421                "--no-audit",
422                "--no-fund",
423                "--progress=false",
424                "--loglevel=verbose",
425                "--legacy-peer-deps=false",
426                "--registry=x"
427            ]
428        );
429        let unpinned = npm_install_args("no-such-provider", &job, "", Path::new("/p/dir"), Vec::new());
430        assert_eq!(unpinned[1], "@scope/not-a-provider");
431    }
432}