agentmux_srv_core/backend/
shellintegration.rs1use std::path::{Path, PathBuf};
14
15const BASH_SCRIPT: &str = include_str!("shellintegration/bash.sh");
18const ZSH_SCRIPT: &str = include_str!("shellintegration/zsh.sh");
19const PWSH_SCRIPT: &str = include_str!("shellintegration/pwsh.ps1");
20const FISH_SCRIPT: &str = include_str!("shellintegration/fish.fish");
21const MUXLOG_JS: &str = include_str!("shellintegration/muxlog.mjs");
25const MUXSPECT_JS: &str = include_str!("shellintegration/muxspect.mjs");
29const MUXOPEN_JS: &str = include_str!("shellintegration/muxopen.mjs");
34const MUXSH_JS: &str = include_str!("shellintegration/muxsh.mjs");
39const MUXCLIENT_JS: &str = include_str!("shellintegration/lib/muxclient.mjs");
45
46fn version_marker() -> String {
59 use std::collections::hash_map::DefaultHasher;
60 use std::hash::{Hash, Hasher};
61 let mut hasher = DefaultHasher::new();
62 BASH_SCRIPT.hash(&mut hasher);
63 ZSH_SCRIPT.hash(&mut hasher);
64 PWSH_SCRIPT.hash(&mut hasher);
65 FISH_SCRIPT.hash(&mut hasher);
66 MUXLOG_JS.hash(&mut hasher);
67 MUXSPECT_JS.hash(&mut hasher);
68 MUXOPEN_JS.hash(&mut hasher);
73 MUXSH_JS.hash(&mut hasher);
74 MUXCLIENT_JS.hash(&mut hasher);
75 format!("{}-{:x}", env!("CARGO_PKG_VERSION"), hasher.finish())
76}
77
78#[derive(Debug, Clone, Copy, PartialEq)]
81pub enum ShellType {
82 Bash,
83 Zsh,
84 Pwsh,
85 Fish,
86 Unknown,
87}
88
89pub fn detect_shell_type(shell_path: &str) -> ShellType {
91 let name = Path::new(shell_path)
92 .file_stem()
93 .and_then(|s| s.to_str())
94 .unwrap_or("")
95 .to_lowercase();
96
97 match name.as_str() {
98 "pwsh" | "powershell" => ShellType::Pwsh,
99 "bash" => ShellType::Bash,
100 "zsh" => ShellType::Zsh,
101 "fish" => ShellType::Fish,
102 _ => ShellType::Unknown,
103 }
104}
105
106pub fn integration_base_for(data_dir: &Path, home_dir: &Path) -> PathBuf {
129 home_dir.join(".agentmux").join("shell").join(instance_key(data_dir))
130}
131
132pub(super) fn instance_key(data_dir: &Path) -> String {
134 let canonical = data_dir.canonicalize().unwrap_or_else(|_| data_dir.to_path_buf());
135 format!("{:016x}", agentmux_common::runtime_mode::fnv1a_64(
136 canonical.to_string_lossy().to_lowercase().as_bytes(),
137 ))
138}
139
140pub fn documented_shell_root() -> PathBuf {
149 crate::backend::base::get_mux_data_dir().join("shell")
150}
151
152pub fn integration_base() -> PathBuf {
164 integration_base_for(
165 &crate::backend::base::get_mux_data_dir(),
166 &crate::backend::base::get_home_dir(),
167 )
168}
169
170pub fn deploy_scripts(shell_root: &Path) {
171 let shell_base = shell_root.to_path_buf();
172 let version_file = shell_base.join(".version");
173 let marker = version_marker();
174
175 if let Ok(existing) = std::fs::read_to_string(&version_file) {
177 if existing.trim() == marker {
178 return;
179 }
180 }
181
182 tracing::info!("Deploying shell integration scripts ({})", marker);
183
184 let deploys: &[(&str, &str, &str)] = &[
185 ("bash", ".bashrc", BASH_SCRIPT),
186 ("zsh", ".zshrc", ZSH_SCRIPT),
187 ("pwsh", "wavepwsh.ps1", PWSH_SCRIPT),
188 ("fish", "wave.fish", FISH_SCRIPT),
189 ];
190
191 let mut all_ok = true;
192 for (dir_name, file_name, content) in deploys {
193 let dir = shell_base.join(dir_name);
194 if let Err(e) = std::fs::create_dir_all(&dir) {
195 tracing::warn!("shell integration: failed to create {}: {}", dir.display(), e);
196 all_ok = false;
197 continue;
198 }
199 let path = dir.join(file_name);
200 if let Err(e) = std::fs::write(&path, content) {
201 tracing::warn!("shell integration: failed to write {}: {}", path.display(), e);
202 all_ok = false;
203 }
204 }
205
206 let muxlog_path = shell_base.join("muxlog.mjs");
209 if let Err(e) = std::fs::write(&muxlog_path, MUXLOG_JS) {
210 tracing::warn!("shell integration: failed to write {}: {}", muxlog_path.display(), e);
211 all_ok = false;
212 }
213
214 let muxspect_path = shell_base.join("muxspect.mjs");
216 if let Err(e) = std::fs::write(&muxspect_path, MUXSPECT_JS) {
217 tracing::warn!("shell integration: failed to write {}: {}", muxspect_path.display(), e);
218 }
219 let muxopen_path = shell_base.join("muxopen.mjs");
221 if let Err(e) = std::fs::write(&muxopen_path, MUXOPEN_JS) {
222 tracing::warn!("shell integration: failed to write {}: {}", muxopen_path.display(), e);
223 all_ok = false;
224 }
225 let muxsh_path = shell_base.join("muxsh.mjs");
227 if let Err(e) = std::fs::write(&muxsh_path, MUXSH_JS) {
228 tracing::warn!("shell integration: failed to write {}: {}", muxsh_path.display(), e);
229 all_ok = false;
230 }
231 let lib_dir = shell_base.join("lib");
235 if let Err(e) = std::fs::create_dir_all(&lib_dir) {
236 tracing::warn!("shell integration: failed to create {}: {}", lib_dir.display(), e);
237 all_ok = false;
238 } else {
239 let muxclient_path = lib_dir.join("muxclient.mjs");
240 if let Err(e) = std::fs::write(&muxclient_path, MUXCLIENT_JS) {
241 tracing::warn!("shell integration: failed to write {}: {}", muxclient_path.display(), e);
242 all_ok = false;
243 }
244 }
245
246 if all_ok {
248 let _ = std::fs::write(&version_file, &marker);
249 }
250}
251
252pub struct ShellStartup {
256 pub extra_args: Vec<String>,
258 pub env_vars: Vec<(String, String)>,
260}
261
262pub fn get_shell_startup(
265 shell_type: ShellType,
266 shell_root: &Path,
267) -> Option<ShellStartup> {
268 match shell_type {
269 ShellType::Bash => {
270 let rcfile = shell_root.join("bash").join(".bashrc");
271 Some(ShellStartup {
272 extra_args: vec![
273 "--rcfile".to_string(),
274 rcfile.to_string_lossy().into_owned(),
275 ],
276 env_vars: vec![],
277 })
278 }
279 ShellType::Zsh => {
280 let zdotdir = shell_root.join("zsh");
281 Some(ShellStartup {
282 extra_args: vec![],
283 env_vars: vec![
284 ("ZDOTDIR".to_string(), zdotdir.to_string_lossy().into_owned()),
285 ("AGENTMUX_ZDOTDIR".to_string(), zdotdir.to_string_lossy().into_owned()),
287 ],
288 })
289 }
290 ShellType::Pwsh => {
291 let script = shell_root
292 .join("pwsh")
293 .join("wavepwsh.ps1");
294 Some(ShellStartup {
295 extra_args: vec![
296 "-ExecutionPolicy".to_string(),
297 "Bypass".to_string(),
298 "-NoExit".to_string(),
299 "-File".to_string(),
300 script.to_string_lossy().into_owned(),
301 ],
302 env_vars: vec![],
303 })
304 }
305 ShellType::Fish => {
306 let script = shell_root
307 .join("fish")
308 .join("wave.fish");
309 Some(ShellStartup {
310 extra_args: vec![
311 "-C".to_string(),
312 format!("source {}", agentmux_common::shell_quote::posix_single_quote(&script.to_string_lossy())),
313 ],
314 env_vars: vec![],
315 })
316 }
317 ShellType::Unknown => None,
318 }
319}
320
321#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn test_detect_shell_type() {
334 assert_eq!(detect_shell_type("bash"), ShellType::Bash);
335 assert_eq!(detect_shell_type("/bin/bash"), ShellType::Bash);
336 assert_eq!(detect_shell_type("zsh"), ShellType::Zsh);
337 assert_eq!(detect_shell_type("/usr/bin/zsh"), ShellType::Zsh);
338 assert_eq!(detect_shell_type("pwsh"), ShellType::Pwsh);
339 assert_eq!(detect_shell_type("powershell"), ShellType::Pwsh);
340 assert_eq!(detect_shell_type("fish"), ShellType::Fish);
341 assert_eq!(detect_shell_type("cmd.exe"), ShellType::Unknown);
342 assert_eq!(detect_shell_type("cmd"), ShellType::Unknown);
343 }
344
345 #[test]
346 fn test_bash_startup_args() {
347 let dir = Path::new("/home/user/.agentmux");
348 let startup = get_shell_startup(ShellType::Bash, dir).unwrap();
349 assert_eq!(startup.extra_args[0], "--rcfile");
350 assert!(startup.extra_args[1].contains("bash"));
351 assert!(startup.extra_args[1].ends_with(".bashrc"));
352 }
353
354 #[test]
355 fn test_pwsh_startup_args() {
356 let dir = Path::new("/home/user/.agentmux");
357 let startup = get_shell_startup(ShellType::Pwsh, dir).unwrap();
358 assert!(startup.extra_args.contains(&"-NoExit".to_string()));
359 assert!(startup.extra_args.contains(&"-File".to_string()));
360 }
361
362 #[test]
363 fn test_zsh_uses_zdotdir() {
364 let dir = Path::new("/home/user/.agentmux");
365 let startup = get_shell_startup(ShellType::Zsh, dir).unwrap();
366 assert!(startup.extra_args.is_empty());
367 assert!(startup.env_vars.iter().any(|(k, _)| k == "ZDOTDIR"));
368 }
369
370 #[test]
371 fn test_unknown_shell_returns_none() {
372 let dir = Path::new("/tmp");
373 assert!(get_shell_startup(ShellType::Unknown, dir).is_none());
374 }
375
376 #[test]
380 fn deploy_scripts_writes_muxlog_and_muxspect_side_by_side() {
381 let tmp = std::env::temp_dir().join(format!(
382 "agentmux-shellintegration-test-{}",
383 std::process::id()
384 ));
385 let _ = std::fs::remove_dir_all(&tmp);
386 deploy_scripts(&tmp.join("shell"));
387
388 let shell_base = tmp.join("shell");
389 let muxlog = shell_base.join("muxlog.mjs");
390 let muxspect = shell_base.join("muxspect.mjs");
391 let muxopen = shell_base.join("muxopen.mjs");
392 let muxsh = shell_base.join("muxsh.mjs");
393 let muxclient = shell_base.join("lib").join("muxclient.mjs");
394 assert!(muxlog.exists(), "muxlog.mjs should be deployed");
395 assert!(muxspect.exists(), "muxspect.mjs should be deployed alongside it");
396 assert!(muxopen.exists(), "muxopen.mjs should be deployed alongside them");
397 assert!(muxsh.exists(), "muxsh.mjs should be deployed alongside them");
398 assert!(
399 muxclient.exists(),
400 "lib/muxclient.mjs should be deployed — muxspect/muxopen/muxsh import it via a relative path"
401 );
402 assert_eq!(std::fs::read_to_string(&muxspect).unwrap(), MUXSPECT_JS);
403 assert_eq!(std::fs::read_to_string(&muxsh).unwrap(), MUXSH_JS);
404 assert_eq!(std::fs::read_to_string(&muxclient).unwrap(), MUXCLIENT_JS);
405
406 let _ = std::fs::remove_dir_all(&tmp);
407 }
408
409 #[test]
416 fn deploy_scripts_redeploys_when_marker_predates_a_content_change() {
417 let tmp = std::env::temp_dir().join(format!(
418 "agentmux-shellintegration-test-stale-{}",
419 std::process::id()
420 ));
421 let _ = std::fs::remove_dir_all(&tmp);
422 let shell_base = tmp.join("shell");
423 std::fs::create_dir_all(&shell_base).unwrap();
424
425 std::fs::write(shell_base.join(".version"), env!("CARGO_PKG_VERSION")).unwrap();
430 assert!(!shell_base.join("muxspect.mjs").exists(), "precondition: not deployed yet");
431
432 deploy_scripts(&tmp.join("shell"));
433
434 assert!(
435 shell_base.join("muxspect.mjs").exists(),
436 "a stale version-only marker must not suppress deployment of a script that was never written"
437 );
438 assert_eq!(
439 std::fs::read_to_string(shell_base.join(".version")).unwrap(),
440 version_marker(),
441 "marker must be updated to the new content-hashed form"
442 );
443
444 let _ = std::fs::remove_dir_all(&tmp);
445 }
446
447 #[test]
453 fn two_instances_never_share_a_shell_integration_dir() {
454 let home = Path::new("/home/u");
455 let a = integration_base_for(Path::new("/ch/alpha/versions/0.56.2/data"), home);
456 let b = integration_base_for(Path::new("/ch/alpha/versions/0.56.3/data"), home);
457 let c = integration_base_for(Path::new("/ch/beta/versions/0.56.3/data"), home);
458 assert_ne!(a, b, "same channel, different version must not collide");
459 assert_ne!(b, c, "same version, different channel must not collide");
460 assert_ne!(a, c);
461 }
462
463 #[test]
466 fn the_same_instance_always_resolves_to_the_same_dir() {
467 let home = Path::new("/home/u");
468 let d = Path::new("/ch/alpha/versions/0.56.3/data");
469 assert_eq!(integration_base_for(d, home), integration_base_for(d, home));
470 }
471
472 #[test]
475 fn deployment_stays_under_the_never_virtualised_home_dir() {
476 let home = Path::new("/home/u");
477 let base = integration_base_for(Path::new("/ch/alpha/versions/0.56.3/data"), home);
478 assert!(base.starts_with(home), "must live under home, got {}", base.display());
479 assert!(!base.starts_with("/ch/alpha"), "must not live under the data dir");
480 }
481
482 #[test]
489 fn the_deployed_rcfile_is_exactly_the_one_the_shell_is_told_to_load() {
490 let tmp = std::env::temp_dir().join(format!("am-si-couple-{}", std::process::id()));
491 let _ = std::fs::remove_dir_all(&tmp);
492 let root = tmp.join("shell");
493 deploy_scripts(&root);
494
495 let startup = get_shell_startup(ShellType::Bash, &root).expect("bash startup");
496 assert_eq!(startup.extra_args[0], "--rcfile");
497 let rcfile = Path::new(&startup.extra_args[1]);
498 assert!(
499 rcfile.exists(),
500 "shell is told to load {} but deploy_scripts never wrote it",
501 rcfile.display()
502 );
503
504 let body = std::fs::read_to_string(rcfile).expect("read rcfile");
506 assert!(body.contains("_agentmux_si_prompt_command"), "rcfile is not the integration script");
507
508 let _ = std::fs::remove_dir_all(&tmp);
509 }
510}