1use std::path::{Path, PathBuf};
35
36use agentmux_common::DataPaths;
37
38const AGENTMUX_VERSION: &str = env!("CARGO_PKG_VERSION");
39
40pub fn is_safe_version_component(v: &str) -> bool {
45 !v.is_empty()
46 && v.len() <= 64
47 && !v.contains("..")
48 && v.chars()
49 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
50}
51
52pub(crate) fn is_safe_provider_component(p: &str) -> bool {
54 !p.is_empty()
55 && p.len() <= 64
56 && p.chars()
57 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
58}
59
60pub fn shared_cli_dir(
63 paths: &DataPaths,
64 provider_id: &str,
65 pinned_version: &str,
66) -> Option<PathBuf> {
67 if !is_safe_provider_component(provider_id) || !is_safe_version_component(pinned_version) {
68 return None;
69 }
70 Some(
71 paths
72 .shared_dir
73 .join("cli")
74 .join(provider_id)
75 .join(pinned_version),
76 )
77}
78
79pub fn legacy_cli_dir(paths: &DataPaths, provider_id: &str) -> PathBuf {
82 paths
83 .home_dir
84 .join("instances")
85 .join(format!("v{AGENTMUX_VERSION}"))
86 .join("cli")
87 .join(provider_id)
88}
89
90pub fn install_dir(paths: &DataPaths, provider_id: &str, pinned_version: &str) -> PathBuf {
93 shared_cli_dir(paths, provider_id, pinned_version)
94 .unwrap_or_else(|| legacy_cli_dir(paths, provider_id))
95}
96
97pub fn npm_bin(dir: &Path, cli_command: &str) -> PathBuf {
100 let bin = dir.join("node_modules").join(".bin");
101 if cfg!(windows) {
102 bin.join(format!("{cli_command}.cmd"))
103 } else {
104 bin.join(cli_command)
105 }
106}
107
108pub const COMPLETE_MARKER: &str = ".agentmux-install-complete";
115
116pub fn is_complete(dir: &Path) -> bool {
118 dir.join(COMPLETE_MARKER).is_file()
119}
120
121pub fn mark_complete(dir: &Path, version: &str) -> std::io::Result<()> {
124 let tmp = dir.join(format!("{COMPLETE_MARKER}.tmp"));
125 std::fs::write(&tmp, version)?;
126 std::fs::rename(&tmp, dir.join(COMPLETE_MARKER))
127}
128
129pub fn is_valid_install(dir: &Path, cli_command: &str) -> bool {
133 is_complete(dir) && installed_bin(dir, cli_command).is_some()
134}
135
136pub fn installed_bin(dir: &Path, cli_command: &str) -> Option<PathBuf> {
139 [
140 npm_bin(dir, cli_command),
141 crate::backend::cli_download::download_bin(dir, cli_command),
142 ]
143 .into_iter()
144 .find(|b| b.is_file())
145}
146
147pub(crate) fn probe_installed(bin: &Path, provider_id: &str) -> Option<String> {
151 let env = crate::backend::providers::get_provider(provider_id).map_or(&[][..], |p| p.auth_extra_env);
152 crate::backend::tool_store::probe_version_when_it_runs(&bin.to_string_lossy(), &Some("--version".to_string()), env)
153}
154
155pub fn clear_unless_valid(dir: &Path, cli_command: &str) -> std::io::Result<()> {
163 if dir.exists() && !is_valid_install(dir, cli_command) {
164 std::fs::remove_dir_all(dir)?;
165 }
166 Ok(())
167}
168
169pub fn find_installed(
173 paths: &DataPaths,
174 provider_id: &str,
175 pinned_version: &str,
176 cli_command: &str,
177) -> Option<PathBuf> {
178 let shared = shared_cli_dir(paths, provider_id, pinned_version)
179 .filter(|d| is_complete(d))
180 .inspect(|d| crate::backend::cli_prune::record_use(d, std::time::SystemTime::now()))
181 .and_then(|d| installed_bin(&d, cli_command));
182 shared.or_else(|| {
183 let legacy = npm_bin(&legacy_cli_dir(paths, provider_id), cli_command);
184 legacy.is_file().then_some(legacy)
185 })
186}
187
188pub fn find_installed_for_provider(paths: &DataPaths, provider_id: &str) -> Option<PathBuf> {
191 let provider = crate::backend::providers::get_provider(provider_id)?;
192 find_installed(
193 paths,
194 provider.id,
195 provider.pinned_version,
196 provider.cli_command,
197 )
198}
199
200pub struct InstallGuard {
204 _file: Option<std::fs::File>,
205}
206
207pub fn lock_install(
213 paths: &DataPaths,
214 provider_id: &str,
215 pinned_version: &str,
216) -> std::io::Result<InstallGuard> {
217 let Some(file) = open_lock_file(paths, provider_id, pinned_version)? else {
218 return Ok(InstallGuard { _file: None });
219 };
220 crate::registry::lock_exclusive(&file)?;
221 Ok(InstallGuard { _file: Some(file) })
222}
223
224pub fn lock_dir(dir: &Path) -> std::io::Result<InstallGuard> {
227 let parent = dir.parent().unwrap_or(dir);
228 std::fs::create_dir_all(parent)?;
229 let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
230 let file = std::fs::OpenOptions::new()
231 .create(true)
232 .write(true)
233 .truncate(false)
234 .open(parent.join(format!("{name}.lock")))?;
235 crate::registry::lock_exclusive(&file)?;
236 Ok(InstallGuard { _file: Some(file) })
237}
238
239pub fn try_lock_install(
243 paths: &DataPaths,
244 provider_id: &str,
245 pinned_version: &str,
246) -> std::io::Result<Option<InstallGuard>> {
247 let Some(file) = open_lock_file(paths, provider_id, pinned_version)? else {
248 return Ok(Some(InstallGuard { _file: None }));
249 };
250 if crate::registry::try_lock_exclusive(&file)? {
251 Ok(Some(InstallGuard { _file: Some(file) }))
252 } else {
253 Ok(None)
254 }
255}
256
257fn open_lock_file(
260 paths: &DataPaths,
261 provider_id: &str,
262 pinned_version: &str,
263) -> std::io::Result<Option<std::fs::File>> {
264 let Some(dir) = shared_cli_dir(paths, provider_id, pinned_version) else {
265 return Ok(None);
266 };
267 let parent = dir.parent().unwrap_or(&dir).to_path_buf();
268 std::fs::create_dir_all(&parent)?;
269 let lock_path = parent.join(format!("{pinned_version}.lock"));
270 let file = std::fs::OpenOptions::new()
271 .create(true)
272 .write(true)
273 .truncate(false)
274 .open(&lock_path)?;
275 Ok(Some(file))
276}
277
278#[derive(Debug, Clone)]
282pub struct NpmInstallRequest {
283 pub provider_id: String,
284 pub npm_package: String,
285 pub pinned_version: String,
286 pub cli_command: String,
287 pub background: bool,
290}
291
292#[derive(Debug)]
294pub struct NpmRun {
295 pub success: bool,
296 pub code: Option<i32>,
297 pub stdout: Vec<u8>,
298 pub stderr: Vec<u8>,
299}
300
301#[derive(Debug)]
302pub enum InstallOutcome {
303 Installed(PathBuf),
305 AlreadyInstalled(PathBuf),
308}
309
310#[derive(Debug)]
311pub enum InstallError {
312 Lock(std::io::Error),
313 Clear(PathBuf, std::io::Error),
314 Spawn(std::io::Error),
315 NpmFailed { code: Option<i32> },
316 ShimMissing { expected: PathBuf },
317 Mark(PathBuf, std::io::Error),
318}
319
320impl std::fmt::Display for InstallError {
321 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322 match self {
323 InstallError::Lock(e) => write!(f, "cannot take the CLI install lock: {e}"),
324 InstallError::Clear(d, e) => write!(
325 f,
326 "cannot clear an incomplete CLI install at {}: {e}",
327 d.display()
328 ),
329 InstallError::Spawn(e) => write!(f, "failed to run npm install: {e}"),
330 InstallError::NpmFailed { code } => {
331 write!(f, "npm install exited {}", code.unwrap_or(-1))
332 }
333 InstallError::ShimMissing { expected } => {
334 write!(f, "npm install left no CLI shim at {}", expected.display())
335 }
336 InstallError::Mark(d, e) => write!(
337 f,
338 "cannot mark the CLI install complete at {}: {e}",
339 d.display()
340 ),
341 }
342 }
343}
344
345pub fn install_pinned_cli(
358 paths: &DataPaths,
359 req: &NpmInstallRequest,
360 on_line: &dyn Fn(&'static str, &str),
361) -> Result<InstallOutcome, InstallError> {
362 install_pinned_cli_with(paths, req, on_line, run_npm_install)
363}
364
365pub fn install_pinned_cli_with(
367 paths: &DataPaths,
368 req: &NpmInstallRequest,
369 on_line: &dyn Fn(&'static str, &str),
370 run_npm: impl FnOnce(&Path, &str, bool) -> std::io::Result<NpmRun>,
371) -> Result<InstallOutcome, InstallError> {
372 let dir = install_dir(paths, &req.provider_id, &req.pinned_version);
373 let bin = npm_bin(&dir, &req.cli_command);
374 let _guard =
375 lock_install(paths, &req.provider_id, &req.pinned_version).map_err(InstallError::Lock)?;
376 let shared = shared_cli_dir(paths, &req.provider_id, &req.pinned_version);
377 if let Some(d) = shared.as_deref() {
378 if is_valid_install(d, &req.cli_command) {
379 return Ok(InstallOutcome::AlreadyInstalled(bin));
380 }
381 clear_unless_valid(d, &req.cli_command)
382 .map_err(|e| InstallError::Clear(d.to_path_buf(), e))?;
383 }
384 let package = match crate::backend::providers::get_provider(&req.provider_id) {
387 Some(p) if p.npm_package == req.npm_package => p.npm_install_specs(&req.pinned_version).join(" "),
388 _ => format!("{}@{}", req.npm_package, req.pinned_version),
389 };
390 tracing::info!(package = %package, prefix = %dir.display(), background = req.background, "running npm install");
391 let run = run_npm(&dir, &package, req.background).map_err(InstallError::Spawn)?;
392 tracing::info!(
393 exit_code = run.code.unwrap_or(-1),
394 stdout_bytes = run.stdout.len(),
395 stderr_bytes = run.stderr.len(),
396 "npm install output collected"
397 );
398 for (stream, bytes) in [("stderr", &run.stderr), ("stdout", &run.stdout)] {
400 for line in String::from_utf8_lossy(bytes).lines() {
401 if !line.trim().is_empty() {
402 on_line(stream, line);
403 }
404 }
405 }
406 if !run.success {
407 return Err(InstallError::NpmFailed { code: run.code });
408 }
409 if !bin.is_file() {
410 return Err(InstallError::ShimMissing { expected: bin });
411 }
412 if let Some(d) = shared.as_deref() {
413 mark_complete(d, &req.pinned_version)
414 .map_err(|e| InstallError::Mark(d.to_path_buf(), e))?;
415 }
416 Ok(InstallOutcome::Installed(bin))
417}
418
419const NPM_REGISTRY: &str = "https://registry.npmjs.org/";
421
422pub fn npm_isolation_args(dir: &Path) -> std::io::Result<Vec<String>> {
430 std::fs::create_dir_all(dir)?;
431 let mut args = vec![format!("--registry={NPM_REGISTRY}")];
432 for (flag, name) in [("--userconfig", ".agentmux-empty-user.npmrc"), ("--globalconfig", ".agentmux-empty-global.npmrc")] {
433 let empty = dir.join(name);
434 std::fs::write(&empty, b"")?;
435 args.push(flag.to_string());
436 args.push(empty.to_string_lossy().into_owned());
437 }
438 Ok(args)
439}
440
441fn run_npm_install(dir: &Path, package: &str, background: bool) -> std::io::Result<NpmRun> {
448 let out = npm_install_command(dir, package, background)?.output()?;
449 Ok(NpmRun {
450 success: out.status.success(),
451 code: out.status.code(),
452 stdout: out.stdout,
453 stderr: out.stderr,
454 })
455}
456
457fn npm_install_command(dir: &Path, package: &str, background: bool) -> std::io::Result<std::process::Command> {
460 let command = {
461 #[cfg(windows)]
462 {
463 use std::os::windows::process::CommandExt;
469 const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000;
472 let mut flags = agentmux_common::win32::CREATE_NO_WINDOW;
473 if background {
474 flags |= BELOW_NORMAL_PRIORITY_CLASS;
475 }
476 let prefix = dir.to_string_lossy().replace('/', "\\");
477 let isolation = npm_isolation_args(dir)?;
478 let (user, global) = (isolation[2].replace('/', "\\"), isolation[4].replace('/', "\\"));
480 let isolation = format!("{} --userconfig \"{user}\" --globalconfig \"{global}\"", isolation[0]);
481 let cmdline = format!(
482 "npm install --loglevel=http --no-audit --no-fund --no-progress --legacy-peer-deps=false {isolation} --prefix \"{prefix}\" {package}"
483 );
484 let mut c = std::process::Command::new("cmd");
485 crate::backend::pane_env::sanitize_external_std_command(&mut c);
488 c.arg("/C")
489 .raw_arg(&cmdline)
490 .creation_flags(flags)
491 .current_dir(dir)
492 .env("CI", "true")
493 .env("FORCE_COLOR", "0");
494 c
495 }
496 #[cfg(not(windows))]
497 {
498 let mut c = std::process::Command::new("npm");
499 crate::backend::pane_env::sanitize_external_std_command(&mut c);
500 c.args([
501 "install",
502 "--loglevel=http",
503 "--no-audit",
504 "--no-fund",
505 "--no-progress",
506 "--legacy-peer-deps=false",
507 ])
508 .args(npm_isolation_args(dir)?)
509 .arg("--prefix")
510 .arg(dir)
511 .args(package.split_whitespace())
512 .current_dir(dir)
513 .env("CI", "true")
514 .env("FORCE_COLOR", "0");
515 if background {
516 use std::os::unix::process::CommandExt;
517 unsafe {
520 c.pre_exec(|| {
521 let _ = libc::setpriority(libc::PRIO_PROCESS, 0, 10);
522 Ok(())
523 });
524 }
525 }
526 c
527 }
528 };
529 Ok(command)
530}
531
532#[derive(Debug)]
536pub enum EnsureError {
537 Failed(String),
539 StillInstalling,
543}
544
545pub async fn ensure_installed_with<F>(
552 paths: DataPaths,
553 req: NpmInstallRequest,
554 wait: std::time::Duration,
555 install: F,
556) -> Result<PathBuf, EnsureError>
557where
558 F: FnOnce(&DataPaths, &NpmInstallRequest) -> Result<InstallOutcome, InstallError>
559 + Send
560 + 'static,
561{
562 let task = tokio::task::spawn_blocking(move || install(&paths, &req));
563 match tokio::time::timeout(wait, task).await {
564 Ok(Ok(Ok(InstallOutcome::Installed(bin) | InstallOutcome::AlreadyInstalled(bin)))) => {
565 Ok(bin)
566 }
567 Ok(Ok(Err(e))) => Err(EnsureError::Failed(e.to_string())),
568 Ok(Err(join)) => Err(EnsureError::Failed(format!(
569 "the install task failed: {join}"
570 ))),
571 Err(_elapsed) => Err(EnsureError::StillInstalling),
572 }
573}
574
575pub async fn ensure_installed(
577 paths: DataPaths,
578 req: NpmInstallRequest,
579 wait: std::time::Duration,
580) -> Result<PathBuf, EnsureError> {
581 ensure_installed_with(paths, req, wait, |p, r| {
582 install_pinned_cli(p, r, &|_, _| {})
583 })
584 .await
585}
586
587pub const WARM_INSTALL_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
592
593pub fn providers_needing_install(
597 paths: &DataPaths,
598 provider_ids: &[String],
599) -> Vec<NpmInstallRequest> {
600 let mut seen = std::collections::HashSet::new();
601 let mut out = Vec::new();
602 for id in provider_ids {
603 let Some(p) = crate::backend::providers::get_provider(id) else {
604 continue;
605 };
606 if p.npm_package.is_empty() || !seen.insert(p.id) {
607 continue;
608 }
609 if find_installed(paths, p.id, p.pinned_version, p.cli_command).is_some() {
610 continue;
611 }
612 out.push(NpmInstallRequest {
613 provider_id: p.id.to_string(),
614 npm_package: p.npm_package.to_string(),
615 pinned_version: p.pinned_version.to_string(),
616 cli_command: p.cli_command.to_string(),
617 background: true,
618 });
619 }
620 out
621}
622
623pub fn warm_used_providers(
631 paths: DataPaths,
632 provider_ids: Vec<String>,
633) -> std::thread::JoinHandle<()> {
634 std::thread::Builder::new()
635 .name("cli-install-warm".into())
636 .spawn(move || {
637 std::thread::sleep(WARM_INSTALL_DELAY);
638 let todo = providers_needing_install(&paths, &provider_ids);
639 if todo.is_empty() {
640 tracing::info!(
641 providers = provider_ids.len(),
642 "cli warm-up: every used provider's pinned CLI is installed"
643 );
644 return;
645 }
646 for req in todo {
647 let started = std::time::Instant::now();
648 let quiet = |_: &'static str, _: &str| {};
649 match install_pinned_cli(&paths, &req, &quiet) {
650 Ok(outcome) => tracing::info!(
651 provider = %req.provider_id,
652 pinned_version = %req.pinned_version,
653 duration_ms = started.elapsed().as_millis() as u64,
654 outcome = ?outcome,
655 "cli warm-up: installed"
656 ),
657 Err(e) => tracing::info!(
658 provider = %req.provider_id,
659 pinned_version = %req.pinned_version,
660 error = %e,
661 "cli warm-up: install failed; the first open will retry and report it"
662 ),
663 }
664 }
665 })
666 .expect("spawn cli-install-warm thread")
667}
668
669#[cfg(test)]
670mod tests {
671
672 #[test]
674 fn the_npm_install_runs_in_the_install_folder() {
675 let tmp = tempfile::tempdir().unwrap();
676 let dir = tmp.path().join("cli").join("claude").join("1.0.0");
677 for background in [false, true] {
678 let command = super::npm_install_command(&dir, "@anthropic-ai/claude-code@1.0.0", background).unwrap();
679 assert_eq!(command.get_current_dir(), Some(dir.as_path()), "background {background}");
680 }
681 }
682
683 #[test]
687 fn every_npm_install_uses_the_public_registry_and_an_empty_config() {
688 let tmp = tempfile::tempdir().unwrap();
689 let dir = tmp.path().join("cli").join("claude").join("1.0.0");
690 let args = super::npm_isolation_args(&dir).unwrap();
691 assert_eq!(args[0], "--registry=https://registry.npmjs.org/");
692 assert_eq!((args[1].as_str(), args[3].as_str()), ("--userconfig", "--globalconfig"));
693 assert_ne!(args[2], args[4], "npm refuses one file as both the user and the global config");
694 for config in [&args[2], &args[4]] {
695 let empty = std::path::Path::new(config);
696 assert!(empty.starts_with(&dir), "the empty config is inside the install folder: {empty:?}");
697 assert_eq!(std::fs::read(empty).unwrap(), b"", "the config npm reads is empty");
698 }
699 }
700
701 use super::*;
702
703 fn paths_in(root: &Path) -> DataPaths {
704 let version_dir = root
705 .join("channels")
706 .join("c")
707 .join("versions")
708 .join("1.0.0");
709 DataPaths {
710 home_dir: version_dir.join("data"),
711 instance_dir: root.join("channels").join("c"),
712 channel: "c".to_string(),
713 data_dir: version_dir.join("data"),
714 config_dir: root.join("channels").join("c").join("config"),
715 logs_dir: version_dir.join("logs"),
716 cef_cache_dir: version_dir.join("cef-cache"),
717 agents_dir: root.join("channels").join("c").join("agents"),
718 instance_runtime_dir: version_dir.join("runtime"),
719 shared_dir: root.join("shared"),
720 mode: agentmux_common::RuntimeMode::Portable,
721 }
722 }
723
724 #[test]
725 fn shared_dir_is_keyed_by_provider_and_pinned_version_not_agentmux_version() {
726 let tmp = tempfile::tempdir().unwrap();
727 let p = paths_in(tmp.path());
728 let d = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
729 assert_eq!(
730 d,
731 tmp.path()
732 .join("shared")
733 .join("cli")
734 .join("claude")
735 .join("2.1.280")
736 );
737 assert!(!d.to_string_lossy().contains(AGENTMUX_VERSION) || AGENTMUX_VERSION == "2.1.280");
738 }
739
740 #[test]
741 fn unsafe_components_have_no_shared_dir_and_fall_back_to_legacy() {
742 let tmp = tempfile::tempdir().unwrap();
743 let p = paths_in(tmp.path());
744 for bad in ["", "..", "../x", "1.0/2", "1.0\\2", "a b"] {
745 assert!(shared_cli_dir(&p, "claude", bad).is_none(), "{bad:?}");
746 assert_eq!(install_dir(&p, "claude", bad), legacy_cli_dir(&p, "claude"));
747 }
748 assert!(shared_cli_dir(&p, "../claude", "1.0.0").is_none());
749 assert!(is_safe_version_component("2.1.280"));
750 assert!(is_safe_version_component("1.0.0-beta.1+build_7"));
751 }
752
753 fn touch_bin(dir: &Path, cli: &str) -> PathBuf {
754 let b = npm_bin(dir, cli);
755 std::fs::create_dir_all(b.parent().unwrap()).unwrap();
756 std::fs::write(&b, "").unwrap();
757 b
758 }
759
760 #[test]
761 fn finds_the_shared_install_first_then_the_legacy_one() {
762 let tmp = tempfile::tempdir().unwrap();
763 let p = paths_in(tmp.path());
764 assert!(find_installed(&p, "claude", "2.1.280", "claude").is_none());
765
766 let legacy = touch_bin(&legacy_cli_dir(&p, "claude"), "claude");
767 assert_eq!(
768 find_installed(&p, "claude", "2.1.280", "claude"),
769 Some(legacy.clone())
770 );
771
772 let shared_dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
773 let shared = touch_bin(&shared_dir, "claude");
774 assert_eq!(
776 find_installed(&p, "claude", "2.1.280", "claude"),
777 Some(legacy.clone())
778 );
779 mark_complete(&shared_dir, "2.1.280").unwrap();
780 assert_eq!(
781 find_installed(&p, "claude", "2.1.280", "claude"),
782 Some(shared)
783 );
784
785 assert_eq!(
787 find_installed(&p, "claude", "2.1.281", "claude"),
788 Some(legacy)
789 );
790 }
791
792 #[test]
793 fn an_upgraded_agentmux_version_reuses_the_shared_install() {
794 let tmp = tempfile::tempdir().unwrap();
795 let old = paths_in(tmp.path());
796 let shared_dir = shared_cli_dir(&old, "claude", "2.1.280").unwrap();
797 let shared = touch_bin(&shared_dir, "claude");
798 mark_complete(&shared_dir, "2.1.280").unwrap();
799
800 let mut new = paths_in(tmp.path());
802 new.home_dir = tmp
803 .path()
804 .join("channels")
805 .join("c")
806 .join("versions")
807 .join("9.9.9")
808 .join("data");
809 assert_eq!(
810 find_installed(&new, "claude", "2.1.280", "claude"),
811 Some(shared)
812 );
813 }
814
815 #[test]
816 fn the_install_lock_serializes_two_holders() {
817 let tmp = tempfile::tempdir().unwrap();
818 let p = paths_in(tmp.path());
819 let first = lock_install(&p, "claude", "2.1.280").unwrap();
820 assert!(tmp
821 .path()
822 .join("shared")
823 .join("cli")
824 .join("claude")
825 .join("2.1.280.lock")
826 .is_file());
827
828 let p2 = paths_in(tmp.path());
829 let (tx, rx) = std::sync::mpsc::channel();
830 let waiter = std::thread::spawn(move || {
831 let _second = lock_install(&p2, "claude", "2.1.280").unwrap();
832 tx.send(()).unwrap();
833 });
834 assert!(rx
836 .recv_timeout(std::time::Duration::from_millis(300))
837 .is_err());
838 drop(first);
839 rx.recv_timeout(std::time::Duration::from_secs(5))
840 .expect("second holder acquires after release");
841 waiter.join().unwrap();
842 }
843
844 #[test]
845 fn the_legacy_dir_needs_no_lock() {
846 let tmp = tempfile::tempdir().unwrap();
847 let p = paths_in(tmp.path());
848 let g = lock_install(&p, "claude", "").unwrap();
849 assert!(g._file.is_none());
850 }
851
852 #[test]
856 fn a_shim_without_the_completion_marker_is_not_an_install() {
857 let tmp = tempfile::tempdir().unwrap();
858 let p = paths_in(tmp.path());
859 let dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
860 touch_bin(&dir, "claude");
861 assert!(!is_complete(&dir));
862 assert!(find_installed(&p, "claude", "2.1.280", "claude").is_none());
863 }
864
865 #[test]
866 fn clear_unless_valid_removes_leftovers_but_keeps_a_finished_install() {
867 let tmp = tempfile::tempdir().unwrap();
868 let p = paths_in(tmp.path());
869 let dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
870 touch_bin(&dir, "claude");
871 clear_unless_valid(&dir, "claude").unwrap();
872 assert!(!dir.exists(), "a partial install is cleared");
873
874 touch_bin(&dir, "claude");
875 mark_complete(&dir, "2.1.280").unwrap();
876 clear_unless_valid(&dir, "claude").unwrap();
877 assert!(
878 is_valid_install(&dir, "claude"),
879 "a finished install is kept"
880 );
881 clear_unless_valid(&tmp.path().join("missing"), "claude").unwrap();
882 }
883
884 #[test]
888 fn a_completed_install_that_lost_its_shim_is_cleared_marker_and_all() {
889 let tmp = tempfile::tempdir().unwrap();
890 let p = paths_in(tmp.path());
891 let dir = shared_cli_dir(&p, "claude", "2.1.280").unwrap();
892 let shim = touch_bin(&dir, "claude");
893 mark_complete(&dir, "2.1.280").unwrap();
894 std::fs::remove_file(&shim).unwrap();
895 assert!(is_complete(&dir) && !is_valid_install(&dir, "claude"));
896
897 clear_unless_valid(&dir, "claude").unwrap();
898 assert!(!dir.exists(), "stale marker and leftovers are gone");
899
900 touch_bin(&dir, "claude");
902 assert!(find_installed(&p, "claude", "2.1.280", "claude").is_none());
903 }
904
905 #[test]
906 fn try_lock_install_reports_a_held_lock_instead_of_waiting() {
907 let tmp = tempfile::tempdir().unwrap();
908 let p = paths_in(tmp.path());
909 let held = lock_install(&p, "claude", "2.1.280").unwrap();
910 let p2 = paths_in(tmp.path());
911 let busy = std::thread::spawn(move || {
914 try_lock_install(&p2, "claude", "2.1.280")
915 .unwrap()
916 .is_none()
917 })
918 .join()
919 .unwrap();
920 assert!(
921 busy,
922 "try_lock_install must report the held lock, not block"
923 );
924 drop(held);
925 let p3 = paths_in(tmp.path());
926 let got = std::thread::spawn(move || {
927 try_lock_install(&p3, "claude", "2.1.280")
928 .unwrap()
929 .is_some()
930 })
931 .join()
932 .unwrap();
933 assert!(got, "acquired once released");
934 assert!(
935 try_lock_install(&p, "claude", "").unwrap().is_some(),
936 "no lock needed without a shared dir"
937 );
938 }
939
940 fn claude_req(background: bool) -> NpmInstallRequest {
941 NpmInstallRequest {
942 provider_id: "claude".into(),
943 npm_package: "@anthropic-ai/claude-code".into(),
944 pinned_version: "2.1.280".into(),
945 cli_command: "claude".into(),
946 background,
947 }
948 }
949
950 fn fake_npm(
952 write_shim: bool,
953 success: bool,
954 ) -> impl FnOnce(&Path, &str, bool) -> std::io::Result<NpmRun> {
955 move |dir: &Path, _pkg: &str, _bg: bool| {
956 if write_shim {
957 let bin = npm_bin(dir, "claude");
958 std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
959 std::fs::write(&bin, "").unwrap();
960 }
961 Ok(NpmRun {
962 success,
963 code: Some(if success { 0 } else { 1 }),
964 stdout: b"added 3 packages\n".to_vec(),
965 stderr: b"npm http fetch\n\n".to_vec(),
966 })
967 }
968 }
969
970 #[test]
971 fn install_runs_npm_verifies_the_shim_and_marks_it_complete() {
972 let _tmp = tempfile::tempdir().unwrap();
973 let paths = paths_in(_tmp.path());
974 let lines = std::sync::Mutex::new(Vec::new());
975 let on_line = |s: &'static str, l: &str| lines.lock().unwrap().push(format!("{s}:{l}"));
976 let out =
977 install_pinned_cli_with(&paths, &claude_req(false), &on_line, fake_npm(true, true))
978 .unwrap();
979 let dir = shared_cli_dir(&paths, "claude", "2.1.280").unwrap();
980 assert!(matches!(out, InstallOutcome::Installed(ref b) if *b == npm_bin(&dir, "claude")));
981 assert!(is_valid_install(&dir, "claude"));
982 assert_eq!(
983 *lines.lock().unwrap(),
984 vec!["stderr:npm http fetch", "stdout:added 3 packages"]
985 );
986 }
987
988 #[test]
989 fn a_finished_install_is_reused_without_running_npm() {
990 let _tmp = tempfile::tempdir().unwrap();
991 let paths = paths_in(_tmp.path());
992 install_pinned_cli_with(&paths, &claude_req(true), &|_, _| {}, fake_npm(true, true))
993 .unwrap();
994 let out = install_pinned_cli_with(
995 &paths,
996 &claude_req(false),
997 &|_, _| {},
998 |_: &Path, _: &str, _: bool| -> std::io::Result<NpmRun> {
999 panic!("npm must not run again")
1000 },
1001 )
1002 .unwrap();
1003 assert!(matches!(out, InstallOutcome::AlreadyInstalled(_)));
1004 }
1005
1006 #[test]
1007 fn a_failed_npm_leaves_no_marker_and_the_next_attempt_starts_clean() {
1008 let _tmp = tempfile::tempdir().unwrap();
1009 let paths = paths_in(_tmp.path());
1010 let dir = shared_cli_dir(&paths, "claude", "2.1.280").unwrap();
1011 let err = install_pinned_cli_with(
1013 &paths,
1014 &claude_req(false),
1015 &|_, _| {},
1016 fake_npm(true, false),
1017 )
1018 .unwrap_err();
1019 assert!(matches!(err, InstallError::NpmFailed { code: Some(1) }));
1020 assert!(!is_complete(&dir));
1021 assert!(find_installed(&paths, "claude", "2.1.280", "claude").is_none());
1022 let retry = install_pinned_cli_with(
1024 &paths,
1025 &claude_req(false),
1026 &|_, _| {},
1027 |d: &Path, p: &str, b: bool| {
1028 assert!(
1029 !npm_bin(d, "claude").exists(),
1030 "leftover shim must be cleared first"
1031 );
1032 fake_npm(true, true)(d, p, b)
1033 },
1034 );
1035 assert!(matches!(retry, Ok(InstallOutcome::Installed(_))));
1036 }
1037
1038 #[test]
1039 fn npm_success_without_a_shim_is_an_error_and_unmarked() {
1040 let _tmp = tempfile::tempdir().unwrap();
1041 let paths = paths_in(_tmp.path());
1042 let err = install_pinned_cli_with(
1043 &paths,
1044 &claude_req(false),
1045 &|_, _| {},
1046 fake_npm(false, true),
1047 )
1048 .unwrap_err();
1049 assert!(matches!(err, InstallError::ShimMissing { .. }));
1050 assert!(!is_complete(
1051 &shared_cli_dir(&paths, "claude", "2.1.280").unwrap()
1052 ));
1053 }
1054
1055 #[test]
1056 fn the_install_holds_the_lock_until_npm_returns() {
1057 let _tmp = tempfile::tempdir().unwrap();
1058 let paths = paths_in(_tmp.path());
1059 let p2 = paths.clone();
1060 install_pinned_cli_with(
1061 &paths,
1062 &claude_req(false),
1063 &|_, _| {},
1064 move |d: &Path, pk: &str, b: bool| {
1065 assert!(try_lock_install(&p2, "claude", "2.1.280")
1067 .unwrap()
1068 .is_none());
1069 fake_npm(true, true)(d, pk, b)
1070 },
1071 )
1072 .unwrap();
1073 assert!(try_lock_install(&paths, "claude", "2.1.280")
1074 .unwrap()
1075 .is_some());
1076 }
1077
1078 #[test]
1079 fn warm_up_picks_used_npm_providers_with_no_install_once_each() {
1080 let _tmp = tempfile::tempdir().unwrap();
1081 let paths = paths_in(_tmp.path());
1082 let ids: Vec<String> = ["claude", "claude", "codex", "not-a-provider"]
1083 .iter()
1084 .map(|s| s.to_string())
1085 .collect();
1086 let todo: Vec<String> = providers_needing_install(&paths, &ids)
1087 .into_iter()
1088 .map(|r| r.provider_id)
1089 .collect();
1090 assert_eq!(todo, vec!["claude", "codex"]);
1091 assert!(providers_needing_install(&paths, &ids)
1092 .iter()
1093 .all(|r| r.background));
1094
1095 let live_claude = crate::backend::providers::get_provider("claude").unwrap();
1101 let live_req = NpmInstallRequest {
1102 provider_id: "claude".into(),
1103 npm_package: live_claude.npm_package.into(),
1104 pinned_version: live_claude.pinned_version.into(),
1105 cli_command: live_claude.cli_command.into(),
1106 background: true,
1107 };
1108 install_pinned_cli_with(&paths, &live_req, &|_, _| {}, fake_npm(true, true)).unwrap();
1109 let todo: Vec<String> = providers_needing_install(&paths, &ids)
1110 .into_iter()
1111 .map(|r| r.provider_id)
1112 .collect();
1113 assert_eq!(todo, vec!["codex"]);
1114 }
1115
1116 fn with_previous_pin_installed() -> (tempfile::TempDir, DataPaths, String, PathBuf) {
1126 let tmp = tempfile::tempdir().unwrap();
1127 let paths = paths_in(tmp.path());
1128 let live = crate::backend::providers::get_provider("claude").unwrap();
1129 let previous = "1.0.0-previous".to_string();
1130 assert_ne!(previous, live.pinned_version);
1131 let req = NpmInstallRequest {
1132 provider_id: "claude".into(),
1133 npm_package: live.npm_package.into(),
1134 pinned_version: previous.clone(),
1135 cli_command: live.cli_command.into(),
1136 background: true,
1137 };
1138 install_pinned_cli_with(&paths, &req, &|_, _| {}, fake_npm(true, true)).unwrap();
1139 let old_bin = npm_bin(
1140 &shared_cli_dir(&paths, "claude", &previous).unwrap(),
1141 "claude",
1142 );
1143 assert!(old_bin.is_file());
1144 (tmp, paths, previous, old_bin)
1145 }
1146
1147 fn live_claude_req(background: bool) -> NpmInstallRequest {
1148 let live = crate::backend::providers::get_provider("claude").unwrap();
1149 NpmInstallRequest {
1150 provider_id: "claude".into(),
1151 npm_package: live.npm_package.into(),
1152 pinned_version: live.pinned_version.into(),
1153 cli_command: live.cli_command.into(),
1154 background,
1155 }
1156 }
1157
1158 #[test]
1159 fn after_a_pin_bump_the_previous_install_is_not_mistaken_for_the_new_pin() {
1160 let (_tmp, paths, _prev, _old_bin) = with_previous_pin_installed();
1161 assert_eq!(
1162 find_installed_for_provider(&paths, "claude"),
1163 None,
1164 "an open must resolve the NEW pin (installing it), not run whatever was there"
1165 );
1166 let todo = providers_needing_install(&paths, &["claude".to_string()]);
1168 assert_eq!(todo.len(), 1);
1169 let live = crate::backend::providers::get_provider("claude").unwrap();
1170 assert_eq!(todo[0].pinned_version, live.pinned_version);
1171 }
1172
1173 #[test]
1174 fn installing_the_new_pin_leaves_the_previous_one_runnable_for_panes_that_hold_its_path() {
1175 let (_tmp, paths, previous, old_bin) = with_previous_pin_installed();
1178 install_pinned_cli_with(
1179 &paths,
1180 &live_claude_req(false),
1181 &|_, _| {},
1182 fake_npm(true, true),
1183 )
1184 .unwrap();
1185
1186 let new_bin = find_installed_for_provider(&paths, "claude").expect("new pin resolves");
1187 assert_ne!(new_bin, old_bin);
1188 assert!(is_valid_install(
1189 &shared_cli_dir(&paths, "claude", &previous).unwrap(),
1190 "claude"
1191 ));
1192 assert!(old_bin.is_file(), "the previous pin's shim is untouched");
1193 assert_eq!(find_installed_for_provider(&paths, "claude"), Some(new_bin));
1195 }
1196
1197 #[test]
1198 fn a_failed_install_of_the_new_pin_does_not_fall_back_to_the_previous_one() {
1199 let (_tmp, paths, previous, old_bin) = with_previous_pin_installed();
1204 let out = install_pinned_cli_with(
1205 &paths,
1206 &live_claude_req(false),
1207 &|_, _| {},
1208 fake_npm(false, false),
1209 );
1210 assert!(
1211 matches!(out, Err(InstallError::NpmFailed { .. })),
1212 "{out:?}"
1213 );
1214 assert_eq!(find_installed_for_provider(&paths, "claude"), None);
1215 assert!(old_bin.is_file());
1216 assert!(is_valid_install(
1217 &shared_cli_dir(&paths, "claude", &previous).unwrap(),
1218 "claude"
1219 ));
1220 let live = crate::backend::providers::get_provider("claude").unwrap();
1222 assert!(!shared_cli_dir(&paths, "claude", live.pinned_version)
1223 .unwrap()
1224 .exists());
1225 }
1226
1227 fn live_req() -> NpmInstallRequest {
1230 live_claude_req(false)
1231 }
1232
1233 #[tokio::test]
1234 async fn ensure_installed_installs_the_missing_pin_and_returns_the_shim() {
1235 let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1236 let live = crate::backend::providers::get_provider("claude").unwrap();
1237 let want = npm_bin(
1238 &shared_cli_dir(&paths, "claude", live.pinned_version).unwrap(),
1239 "claude",
1240 );
1241 let bin = ensure_installed_with(
1242 paths.clone(),
1243 live_req(),
1244 std::time::Duration::from_secs(30),
1245 |p, r| install_pinned_cli_with(p, r, &|_, _| {}, fake_npm(true, true)),
1246 )
1247 .await
1248 .expect("installs");
1249 assert_eq!(bin, want);
1250 assert!(bin.is_file());
1251 assert_eq!(find_installed_for_provider(&paths, "claude"), Some(bin));
1252 }
1253
1254 #[tokio::test]
1255 async fn ensure_installed_reuses_an_install_that_finished_meanwhile() {
1256 let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1257 install_pinned_cli_with(
1258 &paths,
1259 &live_claude_req(true),
1260 &|_, _| {},
1261 fake_npm(true, true),
1262 )
1263 .unwrap();
1264 let bin = ensure_installed_with(
1265 paths,
1266 live_req(),
1267 std::time::Duration::from_secs(30),
1268 |p, r| {
1269 install_pinned_cli_with(
1270 p,
1271 r,
1272 &|_, _| {},
1273 |_: &Path, _: &str, _: bool| -> std::io::Result<NpmRun> {
1274 panic!("npm must not run again")
1275 },
1276 )
1277 },
1278 )
1279 .await
1280 .expect("reuses");
1281 assert!(bin.is_file());
1282 }
1283
1284 #[tokio::test]
1285 async fn ensure_installed_reports_a_failed_install_with_its_reason() {
1286 let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1287 let err = ensure_installed_with(
1288 paths.clone(),
1289 live_req(),
1290 std::time::Duration::from_secs(30),
1291 |p, r| install_pinned_cli_with(p, r, &|_, _| {}, fake_npm(false, false)),
1292 )
1293 .await
1294 .unwrap_err();
1295 assert!(
1296 matches!(&err, EnsureError::Failed(m) if m.contains("npm install exited 1")),
1297 "{err:?}"
1298 );
1299 assert_eq!(find_installed_for_provider(&paths, "claude"), None);
1300 }
1301
1302 #[tokio::test]
1303 async fn ensure_installed_stops_waiting_but_does_not_cancel_a_slow_install() {
1304 let (_tmp, paths, _prev, _old) = with_previous_pin_installed();
1305 let finished = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1306 let flag = finished.clone();
1307 let err = ensure_installed_with(
1308 paths.clone(),
1309 live_req(),
1310 std::time::Duration::from_millis(50),
1311 move |p, r| {
1312 std::thread::sleep(std::time::Duration::from_millis(400));
1313 let out = install_pinned_cli_with(p, r, &|_, _| {}, fake_npm(true, true));
1314 flag.store(true, std::sync::atomic::Ordering::SeqCst);
1315 out
1316 },
1317 )
1318 .await
1319 .unwrap_err();
1320 assert!(matches!(err, EnsureError::StillInstalling), "{err:?}");
1321 for _ in 0..100 {
1323 if finished.load(std::sync::atomic::Ordering::SeqCst) {
1324 break;
1325 }
1326 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1327 }
1328 assert!(
1329 finished.load(std::sync::atomic::Ordering::SeqCst),
1330 "the install must keep running"
1331 );
1332 assert!(
1333 find_installed_for_provider(&paths, "claude").is_some(),
1334 "and a later open finds it"
1335 );
1336 }
1337}