1#[cfg(windows)]
59use agentmux_common::win32::NoWindow;
60use std::path::Path;
61
62pub mod login_item;
63#[cfg(target_os = "windows")]
64pub mod packaged;
65
66#[cfg(any(target_os = "windows", test))]
67mod task_xml;
68#[cfg(any(target_os = "windows", test))]
69pub use task_xml::scheduled_task_xml;
70
71pub const BACKGROUND_FLAG: &str = "--background";
79
80pub fn background_requested(args: &[String]) -> bool {
86 args.iter().any(|a| a == BACKGROUND_FLAG) || started_by_login_task()
87}
88
89fn started_by_login_task() -> bool {
92 #[cfg(target_os = "windows")]
93 {
94 packaged::started_by_startup_task()
95 }
96 #[cfg(not(target_os = "windows"))]
97 {
98 false
99 }
100}
101
102pub fn login_start() -> bool {
105 background_requested(&crate::launch_link::own_args())
106}
107
108pub fn second_instance_opens_window(args: &[String]) -> bool {
113 !background_requested(args)
114}
115
116pub fn background_env_for(args: &[String]) -> Vec<(&'static str, &'static str)> {
128 if background_requested(args) {
129 vec![
130 ("AGENTMUX_BACKGROUND_SERVICE", "1"),
131 ("AGENTMUX_TRAY", "1"),
132 ]
133 } else {
134 Vec::new()
135 }
136}
137
138#[cfg(any(target_os = "windows", target_os = "linux", test))]
143pub const AUTOSTART_ID: &str = "AgentMux";
144
145#[cfg(any(not(target_os = "windows"), test))]
147pub const MACOS_LABEL: &str = "com.agentmux.launcher";
148
149const TASK_CHANNEL_MARKER: &str = "[agentmux-channel=";
152
153#[cfg(any(not(target_os = "windows"), test))]
161pub fn launch_agent_plist(exe: &Path, channel: &str) -> String {
162 let exe = xml_escape(&exe.display().to_string());
163 let channel = xml_escape(channel);
164 format!(
165 r#"<?xml version="1.0" encoding="UTF-8"?>
166<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
167<plist version="1.0">
168<dict>
169 <key>Label</key>
170 <string>{label}</string>
171 <key>ProgramArguments</key>
172 <array>
173 <string>{exe}</string>
174 <string>--background</string>
175 </array>
176 <key>RunAtLoad</key>
177 <true/>
178 <key>KeepAlive</key>
179 <false/>
180 <key>ProcessType</key>
181 <string>Interactive</string>
182 <key>{channel_key}</key>
183 <string>{channel}</string>
184</dict>
185</plist>
186"#,
187 label = MACOS_LABEL,
188 exe = exe,
189 channel_key = PLIST_CHANNEL_KEY,
190 channel = channel,
191 )
192}
193
194const PLIST_CHANNEL_KEY: &str = "AgentMuxChannel";
196
197#[cfg(any(not(target_os = "windows"), test))]
209pub fn xdg_desktop_entry(exe: &Path, channel: &str) -> String {
210 format!(
211 "[Desktop Entry]\n\
212 Type=Application\n\
213 Name=AgentMux\n\
214 Comment=Starts AgentMux in the background at login\n\
215 TryExec={try_exec}\n\
216 Exec={prefix}\"{exe}\" {flag}\n\
217 Terminal=false\n\
218 X-GNOME-Autostart-enabled=true\n\
219 X-GNOME-Autostart-Delay=10\n\
220 {channel_key}={channel}\n",
221 try_exec = desktop_string_escape(&exe.display().to_string()),
222 prefix = exec_prefix(exe),
223 exe = desktop_exec_escape(exe),
224 flag = BACKGROUND_FLAG,
225 channel_key = XDG_CHANNEL_KEY,
226 channel = desktop_string_escape(channel),
227 )
228}
229
230const XDG_CHANNEL_KEY: &str = "X-AgentMux-Channel";
232
233#[cfg(any(not(target_os = "windows"), test))]
237fn exec_prefix(exe: &Path) -> &'static str {
238 if is_appimage(exe) {
239 APPIMAGELAUNCHER_OFF_PREFIX
240 } else {
241 ""
242 }
243}
244
245const APPIMAGELAUNCHER_OFF_PREFIX: &str = "env APPIMAGELAUNCHER_DISABLE=1 ";
247
248fn is_appimage(exe: &Path) -> bool {
249 exe.extension().is_some_and(|e| e.eq_ignore_ascii_case("appimage"))
250}
251
252#[cfg(any(not(target_os = "windows"), test))]
256fn desktop_string_escape(s: &str) -> String {
257 let mut out = String::with_capacity(s.len());
258 for c in s.chars() {
259 match c {
260 '\\' => out.push_str("\\\\"),
261 '\n' => out.push_str("\\n"),
262 '\t' => out.push_str("\\t"),
263 '\r' => out.push_str("\\r"),
264 _ => out.push(c),
265 }
266 }
267 out
268}
269
270fn desktop_string_unescape(s: &str) -> String {
271 let mut out = String::with_capacity(s.len());
272 let mut it = s.chars();
273 while let Some(c) = it.next() {
274 if c != '\\' {
275 out.push(c);
276 continue;
277 }
278 match it.next() {
279 Some('n') => out.push('\n'),
280 Some('t') => out.push('\t'),
281 Some('r') => out.push('\r'),
282 Some('s') => out.push(' '),
283 Some(o) => out.push(o),
284 None => out.push('\\'),
285 }
286 }
287 out
288}
289
290#[cfg(any(not(target_os = "windows"), test))]
309fn desktop_exec_escape(exe: &Path) -> String {
310 let raw = exe.display().to_string();
311 let mut out = String::with_capacity(raw.len());
312 for c in raw.chars() {
313 match c {
314 '"' | '\\' | '`' | '$' => {
316 out.push('\\');
317 out.push(c);
318 }
319 '%' => out.push_str("%%"),
321 '\n' | '\r' => {}
323 _ => out.push(c),
324 }
325 }
326 out
327}
328
329fn xml_escape(s: &str) -> String {
337 let mut out = String::with_capacity(s.len());
338 for c in s.chars() {
339 match c {
340 '&' => out.push_str("&"),
341 '<' => out.push_str("<"),
342 '>' => out.push_str(">"),
343 '"' => out.push_str("""),
344 '\'' => out.push_str("'"),
345 _ => out.push(c),
346 }
347 }
348 out
349}
350
351#[cfg(not(target_os = "windows"))]
355pub fn artifact_path() -> Option<std::path::PathBuf> {
356 #[cfg(target_os = "macos")]
357 {
358 let home = std::env::var("HOME").ok()?;
359 Some(
360 Path::new(&home)
361 .join("Library/LaunchAgents")
362 .join(format!("{}.plist", MACOS_LABEL)),
363 )
364 }
365 #[cfg(target_os = "linux")]
366 {
367 let base = std::env::var("XDG_CONFIG_HOME")
369 .ok()
370 .filter(|s| !s.is_empty())
371 .unwrap_or_else(|| format!("{}/.config", std::env::var("HOME").unwrap_or_default()));
372 Some(
373 Path::new(&base)
374 .join("autostart")
375 .join(format!("{}.desktop", AUTOSTART_ID.to_lowercase())),
376 )
377 }
378 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
379 {
380 None
381 }
382}
383
384#[cfg(target_os = "windows")]
390fn schtasks_command() -> std::process::Command {
391 let mut cmd = std::process::Command::new("schtasks");
392 cmd.no_window();
393 cmd
394}
395
396#[cfg(target_os = "windows")]
405fn scheduled_task_exists() -> bool {
406 schtasks_command()
407 .args(["/Query", "/TN", AUTOSTART_ID])
408 .stdout(std::process::Stdio::null())
409 .stderr(std::process::Stdio::null())
410 .status()
411 .map(|s| s.success())
412 .unwrap_or(false)
413}
414
415pub fn is_enabled() -> bool {
416 #[cfg(target_os = "windows")]
417 {
418 if packaged::is_packaged() {
420 return packaged::state().map(packaged::TaskState::is_on).unwrap_or(false);
421 }
422 scheduled_task_exists()
423 }
424 #[cfg(not(target_os = "windows"))]
425 {
426 artifact_path().map(|p| p.exists()).unwrap_or(false) || login_item::registration().is_some_and(|r| r.is_registered())
429 }
430}
431
432pub fn enable(exe: &Path, channel: &str) -> Result<(), String> {
436 #[cfg(target_os = "windows")]
437 {
438 if packaged::is_packaged() {
439 let _ = (exe, channel);
442 if scheduled_task_exists() {
446 return Err(
447 "start at login is already on for the AgentMux installed with the setup program: turn it off there first, so AgentMux does not start twice".to_string(),
448 );
449 }
450 return match packaged::request_enable()? {
451 s if s.is_on() => Ok(()),
452 packaged::TaskState::DisabledByUser => Err(
453 "Windows has start at login turned off for AgentMux: turn it on in Settings > Apps > Startup".to_string(),
454 ),
455 packaged::TaskState::DisabledByPolicy => {
456 Err("start at login is turned off for AgentMux by your organisation's policy".to_string())
457 }
458 _ => Err("Windows did not turn start at login on".to_string()),
459 };
460 }
461 let xml = scheduled_task_xml(exe, channel);
466 let dir = std::env::temp_dir();
467 let path = dir.join(format!("agentmux-autostart-{}.xml", std::process::id()));
468 let mut bytes: Vec<u8> = vec![0xFF, 0xFE]; for unit in xml.encode_utf16() {
470 bytes.extend_from_slice(&unit.to_le_bytes());
471 }
472 std::fs::write(&path, &bytes).map_err(|e| format!("write task xml: {}", e))?;
473
474 let out = schtasks_command()
479 .args(["/Create", "/TN", AUTOSTART_ID, "/XML"])
480 .arg(&path)
481 .arg("/F") .output();
483 let _ = std::fs::remove_file(&path);
485
486 match out {
487 Ok(o) if o.status.success() => Ok(()),
488 Ok(o) => Err(format!(
489 "schtasks /Create failed ({}): {}{}",
490 o.status,
491 String::from_utf8_lossy(&o.stderr).trim(),
492 String::from_utf8_lossy(&o.stdout).trim()
493 )),
494 Err(e) => Err(format!("run schtasks: {}", e)),
495 }
496 }
497 #[cfg(not(target_os = "windows"))]
498 {
499 if login_item::available() {
502 let _ = (exe, channel);
503 login_item::register()?;
504 return remove_launch_agent_plist();
505 }
506 let path = artifact_path().ok_or_else(|| "unsupported platform".to_string())?;
507 let contents = if cfg!(target_os = "macos") {
508 launch_agent_plist(exe, channel)
509 } else {
510 xdg_desktop_entry(exe, channel)
511 };
512 if let Some(parent) = path.parent() {
513 std::fs::create_dir_all(parent)
514 .map_err(|e| format!("create {}: {}", parent.display(), e))?;
515 }
516 std::fs::write(&path, contents).map_err(|e| format!("write {}: {}", path.display(), e))
517 }
518}
519
520pub fn disable() -> Result<(), String> {
528 #[cfg(target_os = "windows")]
529 {
530 if packaged::is_packaged() {
531 return packaged::disable();
532 }
533 if !is_enabled() {
534 return Ok(());
535 }
536 match schtasks_command()
537 .args(["/Delete", "/TN", AUTOSTART_ID, "/F"])
538 .stdout(std::process::Stdio::null())
539 .stderr(std::process::Stdio::null())
540 .status()
541 {
542 Ok(s) if s.success() => Ok(()),
543 Ok(s) => Err(format!("schtasks /Delete failed: {}", s)),
544 Err(e) => Err(format!("run schtasks: {}", e)),
545 }
546 }
547 #[cfg(not(target_os = "windows"))]
548 {
549 login_item::unregister()?;
551 remove_launch_agent_plist()
552 }
553}
554
555#[cfg(not(target_os = "windows"))]
558fn remove_launch_agent_plist() -> Result<(), String> {
559 let Some(path) = artifact_path() else {
560 return Ok(());
561 };
562 match std::fs::remove_file(&path) {
563 Ok(()) => Ok(()),
564 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
565 Err(e) => Err(format!("remove {}: {}", path.display(), e)),
566 }
567}
568
569pub fn current_channel() -> String {
591 std::env::current_exe()
592 .ok()
593 .and_then(|exe| {
594 let dir = exe.parent()?.to_path_buf();
595 crate::data_dir::resolve_paths(&dir, env!("CARGO_PKG_VERSION")).ok()
596 })
597 .map(|p| p.common.channel)
598 .unwrap_or_else(|| "unknown".to_string())
599}
600
601const STABLE_EXE_ENV: &str = "AGENTMUX_STABLE_EXE";
604
605static STABLE_EXE: std::sync::OnceLock<Option<std::ffi::OsString>> = std::sync::OnceLock::new();
606
607pub fn take_stable_exe_env() {
614 let value = std::env::var_os(STABLE_EXE_ENV).filter(|v| !v.is_empty());
615 std::env::remove_var(STABLE_EXE_ENV);
616 let _ = STABLE_EXE.set(value);
617}
618
619pub fn stable_target() -> Result<std::path::PathBuf, String> {
627 stable_target_from(
628 STABLE_EXE.get().cloned().flatten(),
629 std::env::current_exe().map_err(|e| e.to_string()),
630 )
631}
632
633fn stable_target_from(
634 stable: Option<std::ffi::OsString>,
635 current: Result<std::path::PathBuf, String>,
636) -> Result<std::path::PathBuf, String> {
637 match stable.map(std::path::PathBuf::from) {
638 Some(p) if p.is_file() => Ok(p),
639 _ => current,
640 }
641}
642
643#[derive(Debug, Clone, PartialEq, Eq)]
645pub struct Entry {
646 pub target: Option<String>,
648 pub channel: Option<String>,
651 pub current: bool,
654}
655
656pub fn read_entry() -> Option<Entry> {
658 #[cfg(target_os = "windows")]
659 {
660 if packaged::is_packaged() {
662 return packaged::state().ok().filter(|s| s.is_on()).map(|_| Entry {
663 target: std::env::current_exe().ok().map(|e| e.display().to_string()),
664 channel: Some(current_channel()),
665 current: true,
666 });
667 }
668 let out = schtasks_command()
669 .args(["/Query", "/TN", AUTOSTART_ID, "/XML"])
670 .stderr(std::process::Stdio::null())
671 .output()
672 .ok()?;
673 if !out.status.success() {
674 return None;
675 }
676 Some(parse_task_xml(&decode_console_output(&out.stdout)))
677 }
678 #[cfg(not(target_os = "windows"))]
679 {
680 if login_item::registration().is_some_and(|r| r.is_registered()) {
682 return Some(Entry {
683 target: std::env::current_exe().ok().map(|p| p.display().to_string()),
684 channel: Some(current_channel()),
685 current: true,
686 });
687 }
688 let text = std::fs::read_to_string(artifact_path()?).ok()?;
689 let mut entry = if cfg!(target_os = "macos") {
690 parse_plist(&text)
691 } else {
692 parse_desktop_entry(&text)
693 };
694 if login_item::available() {
697 entry.current = false;
698 }
699 Some(entry)
700 }
701}
702
703#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
705fn decode_console_output(bytes: &[u8]) -> String {
706 let body = bytes.strip_prefix(&[0xFF, 0xFE]).unwrap_or(bytes);
707 if body.len() >= 2 && body.len() % 2 == 0 && body.iter().skip(1).step_by(2).take(64).all(|b| *b == 0) {
708 let units: Vec<u16> = body.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
709 return String::from_utf16_lossy(&units);
710 }
711 String::from_utf8_lossy(body).into_owned()
712}
713
714fn between<'a>(s: &'a str, start: &str, end: &str) -> Option<&'a str> {
715 let from = s.find(start)? + start.len();
716 let len = s[from..].find(end)?;
717 Some(&s[from..from + len])
718}
719
720fn xml_unescape(s: &str) -> String {
721 s.replace("<", "<")
722 .replace(">", ">")
723 .replace(""", "\"")
724 .replace("'", "'")
725 .replace("&", "&")
726}
727
728#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
729fn parse_task_xml(xml: &str) -> Entry {
730 let target = between(xml, "<Command>", "</Command>")
731 .map(|c| xml_unescape(c.trim()).trim_matches('"').to_string());
732 let channel = between(xml, "<Description>", "</Description>")
733 .and_then(|d| between(d, TASK_CHANNEL_MARKER, "]"))
734 .map(xml_unescape);
735 Entry { target, channel, current: true }
736}
737
738#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
739fn parse_plist(text: &str) -> Entry {
740 let target = between(text, "<key>ProgramArguments</key>", "</array>")
741 .and_then(|a| between(a, "<string>", "</string>"))
742 .map(xml_unescape);
743 let channel = between(text, &format!("<key>{PLIST_CHANNEL_KEY}</key>"), "</string>")
744 .and_then(|rest| rest.split_once("<string>").map(|(_, v)| xml_unescape(v)));
745 Entry { target, channel, current: true }
746}
747
748#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
749fn parse_desktop_entry(text: &str) -> Entry {
750 let value = |key: &str| {
751 text.lines()
752 .find_map(|l| l.strip_prefix(key).and_then(|r| r.strip_prefix('=')))
753 .map(desktop_string_unescape)
754 };
755 let target = value("TryExec");
758 let current = match (&target, value("Exec")) {
760 (Some(t), Some(exec)) if is_appimage(Path::new(t)) => exec.starts_with(APPIMAGELAUNCHER_OFF_PREFIX),
761 _ => true,
762 };
763 Entry { target, channel: value(XDG_CHANNEL_KEY), current }
764}
765
766#[derive(Debug, Clone, PartialEq, Eq)]
769pub enum Plan {
770 Nothing,
772 Write,
774 Remove,
776 Adopt,
780 Repoint,
784}
785
786static MOVED_FROM: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
789
790pub fn set_moved_from(from: Option<String>) {
792 let _ = MOVED_FROM.set(from);
793}
794
795pub(crate) fn moved_from() -> Option<String> {
796 MOVED_FROM.get().cloned().flatten()
797}
798
799pub fn startup() {
802 take_stable_exe_env();
803 note_appimage_start();
804 #[cfg(target_os = "windows")]
807 if packaged::is_packaged() {
808 crate::log(&format!("packaged start: activation {}", packaged::activation_name()));
809 }
810}
811
812pub fn note_appimage_start() {
815 let moved = std::env::current_exe().ok().and_then(|exe| {
816 let appimage = agentmux_common::runtime_mode::running_appimage(&exe)?;
817 let record = agentmux_common::appimage_record::record_path()?;
818 let done = agentmux_common::appimage_record::reconcile(&record, &appimage);
819 if let Some(from) = &done.moved_from {
820 crate::log(&format!("appimage: moved or renamed since it last started (from {from}); channel {:?} kept", done.channel));
821 }
822 done.moved_from
823 });
824 set_moved_from(moved);
825}
826
827pub fn missing_target(entry: &Entry) -> Option<&str> {
830 entry.target.as_deref().filter(|t| !t.is_empty() && !Path::new(t).exists())
831}
832
833#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
835#[serde(rename_all = "snake_case")]
836pub enum State {
837 Off,
839 On,
841 Broken,
843 NeedsApproval,
846}
847
848#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
850pub struct Status {
851 pub state: State,
852 pub target: Option<String>,
854 pub owner_channel: Option<String>,
856 pub this_channel: String,
857 pub movable: bool,
859 #[serde(skip_serializing_if = "Option::is_none")]
862 pub package: Option<String>,
863 #[serde(skip_serializing_if = "Option::is_none")]
865 pub activation: Option<String>,
866}
867
868pub fn status(entry: Option<&Entry>, registered: bool, this_channel: &str, can_write: bool) -> Status {
872 let state = match entry {
873 Some(e) if missing_target(e).is_some() => State::Broken,
874 Some(_) => State::On,
875 None if registered => State::On,
876 None => State::Off,
877 };
878 let owner_channel = entry.and_then(|e| e.channel.clone());
879 let movable = entry.is_some() && owner_channel.as_deref() != Some(this_channel) && can_write;
880 Status { state, target: entry.and_then(|e| e.target.clone()), owner_channel, this_channel: this_channel.to_string(), movable, package: None, activation: None }
881}
882
883pub fn plan(setting: Option<bool>, entry: Option<&Entry>, channel: &str, target: Option<&str>, moved_from: Option<&str>) -> Plan {
895 let owned = |e: &Entry| e.channel.as_deref() == Some(channel);
896 match (setting, entry) {
897 (Some(true), Some(e)) if owned(e) && e.current && target.is_some() && e.target.as_deref() == target => Plan::Nothing,
898 (Some(true), _) => Plan::Write,
899 (Some(false), Some(e)) if owned(e) => Plan::Remove,
900 (None, Some(e)) if e.channel.is_none() => Plan::Adopt,
901 (_, Some(e)) if target.is_some() && e.target.is_some() && e.target.as_deref() == moved_from && e.target.as_deref() != target => Plan::Repoint,
904 _ => Plan::Nothing,
905 }
906}
907
908pub fn current_status() -> Status {
911 let mut s = status(read_entry().as_ref(), is_enabled(), ¤t_channel(), stable_target().is_ok());
912 if login_item::registration() == Some(login_item::Registration::RequiresApproval) {
913 s.state = State::NeedsApproval;
914 }
915 #[cfg(target_os = "windows")]
919 if packaged::is_packaged() {
920 s.package = packaged::state().ok().map(|task| task.as_str().to_string());
921 s.activation = Some(packaged::activation_name());
922 s.movable = false;
923 }
924 s
925}
926
927pub fn entry_runs_from(entry: &Entry, dir: &Path) -> bool {
931 fn norm(p: &str) -> String {
932 let p = p.trim_end_matches(|c| c == '\\' || c == '/');
933 if cfg!(target_os = "windows") { p.replace('/', "\\").to_lowercase() } else { p.to_string() }
934 }
935 let Some(target) = entry.target.as_deref().filter(|t| !t.is_empty()) else { return false };
936 let dir = norm(&dir.to_string_lossy());
937 let target = norm(target);
938 let sep = if cfg!(target_os = "windows") { '\\' } else { '/' };
939 !dir.is_empty() && target.len() > dir.len() && target.starts_with(&dir) && target[dir.len()..].starts_with(sep)
940}
941
942pub fn handle_cli(args: &[String]) -> bool {
943 let has = |v: &str| args.iter().any(|a| a == v);
944
945 if has(login_item::LOGIN_START_FLAG) {
947 std::process::exit(login_item::login_start());
948 }
949 if has(login_item::OPEN_LOGIN_ITEMS_FLAG) {
950 match login_item::open_settings() {
951 Ok(()) => println!("opened Login Items"),
952 Err(e) => {
953 eprintln!("failed to open Login Items: {}", e);
954 std::process::exit(1);
955 }
956 }
957 return true;
958 }
959 if has("--autostart-status") {
960 if has("--json") {
961 let s = current_status();
962 println!("{}", serde_json::to_string(&s).unwrap_or_else(|_| "{}".to_string()));
963 } else {
964 println!("{}", if is_enabled() { "enabled" } else { "disabled" });
965 }
966 return true;
967 }
968 if has("--enable-autostart") {
969 match stable_target() {
970 Ok(exe) => match enable(&exe, ¤t_channel()) {
971 Ok(()) => println!("auto-start enabled ({})", exe.display()),
972 Err(e) => {
973 eprintln!("failed to enable auto-start: {}", e);
974 std::process::exit(1);
975 }
976 },
977 Err(e) => {
978 eprintln!("failed to resolve the auto-start target: {}", e);
979 std::process::exit(1);
980 }
981 }
982 return true;
983 }
984 if has("--disable-autostart") {
985 match disable() {
986 Ok(()) => println!("auto-start disabled"),
987 Err(e) => {
988 eprintln!("failed to disable auto-start: {}", e);
989 std::process::exit(1);
990 }
991 }
992 return true;
993 }
994 if has("--remove-autostart-for-this-install") {
995 let dir = std::env::current_exe().ok().and_then(|e| e.parent().map(Path::to_path_buf));
998 match (read_entry(), dir) {
999 (Some(entry), Some(dir)) if entry_runs_from(&entry, &dir) => match disable() {
1000 Ok(()) => println!("auto-start entry for this install removed"),
1001 Err(e) => {
1002 eprintln!("failed to remove the auto-start entry: {}", e);
1003 std::process::exit(1);
1004 }
1005 },
1006 _ => println!("no auto-start entry runs from this install; left alone"),
1007 }
1008 return true;
1009 }
1010 false
1011}
1012
1013#[cfg(test)]
1014mod autostart_tests {
1015 use super::*;
1016 use std::path::PathBuf;
1017
1018 fn exe() -> PathBuf {
1019 PathBuf::from(r"C:\Program Files\AgentMux\agentmux.exe")
1020 }
1021
1022 fn plan(setting: Option<bool>, entry: Option<&Entry>, channel: &str, target: Option<&str>) -> Plan {
1024 super::plan(setting, entry, channel, target, None)
1025 }
1026
1027 #[test]
1028 fn scheduled_task_uses_interactive_token_not_a_service_account() {
1029 let xml = scheduled_task_xml(&exe(), "test");
1034 assert!(xml.contains("<LogonType>InteractiveToken</LogonType>"));
1035 assert!(
1036 xml.contains("<RunLevel>LeastPrivilege</RunLevel>"),
1037 "auto-start must never require elevation"
1038 );
1039 }
1040
1041 #[test]
1044 fn scheduled_task_names_the_user_so_a_normal_token_can_create_it() {
1045 let xml = task_xml::scheduled_task_xml_for(&exe(), "test", Some(r"PC\Ann & Bo"));
1046 assert_eq!(xml.matches(r"<UserId>PC\Ann & Bo</UserId>").count(), 2, "{xml}");
1047 let trigger = xml.split("<LogonTrigger>").nth(1).unwrap().split("</LogonTrigger>").next().unwrap();
1048 assert!(trigger.contains("<UserId>"));
1049 let principal = xml.split("<Principal id=\"Author\">").nth(1).unwrap().split("</Principal>").next().unwrap();
1050 assert!(principal.contains("<UserId>"));
1051 assert!(!task_xml::scheduled_task_xml_for(&exe(), "test", None).contains("<UserId>"));
1053 }
1054
1055 #[test]
1056 fn scheduled_task_survives_battery_power() {
1057 let xml = scheduled_task_xml(&exe(), "test");
1062 assert!(xml.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));
1063 assert!(xml.contains("<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"));
1064 }
1065
1066 #[test]
1067 fn scheduled_task_has_no_execution_time_limit() {
1068 let xml = scheduled_task_xml(&exe(), "test");
1071 assert!(xml.contains("<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"));
1072 }
1073
1074 #[test]
1075 fn generated_xml_escapes_paths() {
1076 let xml = scheduled_task_xml(Path::new(r"C:\Tools & Apps\<agentmux>.exe"), "test");
1080 assert!(xml.contains("Tools & Apps"));
1081 assert!(xml.contains("<agentmux>"));
1082 assert!(
1083 !xml.contains("Tools & Apps"),
1084 "raw ampersand would make the document invalid"
1085 );
1086 }
1087
1088 #[test]
1089 fn launch_agent_does_not_let_launchd_resurrect_a_user_quit() {
1090 let plist = launch_agent_plist(Path::new("/Applications/AgentMux.app/Contents/MacOS/agentmux"), "test");
1094 assert!(plist.contains("<key>RunAtLoad</key>\n <true/>"));
1095 assert!(plist.contains("<key>KeepAlive</key>\n <false/>"));
1096 assert!(plist.contains(MACOS_LABEL));
1097 }
1098
1099 #[test]
1100 fn xdg_entry_is_a_valid_autostart_desktop_file() {
1101 let d = xdg_desktop_entry(Path::new("/opt/agentmux/agentmux"), "test");
1102 assert!(d.starts_with("[Desktop Entry]\n"));
1103 assert!(d.contains("Type=Application\n"));
1104 assert!(d.contains("X-GNOME-Autostart-enabled=true\n"));
1105 assert!(
1106 d.contains("Exec=\"/opt/agentmux/agentmux\" --background\n"),
1107 "Exec must quote the path so spaces don't split the command"
1108 );
1109 }
1110
1111 #[test]
1112 fn xdg_entry_cannot_be_injected_with_extra_keys_via_the_path() {
1113 let d = xdg_desktop_entry(Path::new("/opt/x\nHidden=true"), "test");
1116 assert!(!d.contains("\nHidden=true\n"), "newline must not survive into the file");
1117 }
1118
1119 #[test]
1136 #[ignore = "mutates real login configuration; run explicitly with --ignored"]
1137 fn autostart_round_trip_against_the_real_platform_registry() {
1138 assert!(
1141 !is_enabled(),
1142 "autostart already enabled on this machine — refusing to overwrite a real registration"
1143 );
1144
1145 let exe = std::env::current_exe().expect("current_exe");
1146 enable(&exe, "test").expect("enable should succeed");
1147 assert!(is_enabled(), "enable() must be observable through the platform");
1148
1149 enable(&exe, "test").expect("re-enable should replace, not fail");
1151 assert!(is_enabled());
1152
1153 disable().expect("disable should succeed");
1154 assert!(!is_enabled(), "disable() must actually remove the artifact");
1155
1156 disable().expect("disable must be idempotent");
1158 }
1159
1160 #[test]
1165 fn the_background_flag_maps_onto_the_env_the_host_actually_reads() {
1166 let args = vec!["agentmux.exe".to_string(), BACKGROUND_FLAG.to_string()];
1167 assert!(background_requested(&args));
1168 let env = background_env_for(&args);
1169 assert!(
1170 env.contains(&("AGENTMUX_BACKGROUND_SERVICE", "1")),
1171 "without this the auto-start entry is inert"
1172 );
1173 }
1174
1175 #[test]
1180 fn background_mode_also_forces_the_visible_indicator_on() {
1181 let args = vec![BACKGROUND_FLAG.to_string()];
1182 assert!(background_env_for(&args).contains(&("AGENTMUX_TRAY", "1")));
1183 }
1184
1185 #[test]
1186 fn a_normal_launch_sets_no_background_env() {
1187 let args = vec!["agentmux.exe".to_string(), "--url=http://x".to_string()];
1188 assert!(!background_requested(&args));
1189 assert!(
1190 background_env_for(&args).is_empty(),
1191 "an ordinary launch must be completely unaffected"
1192 );
1193 }
1194
1195 #[test]
1196 fn exec_escaping_covers_the_desktop_entry_grammar() {
1197 let d = xdg_desktop_entry(Path::new(r#"/opt/a"b\c`d$e%f/agentmux"#), "test");
1200 assert!(d.contains(r#"\"b"#), "quote must be escaped, not end the argument");
1201 assert!(d.contains(r"\\c"), "backslash must be escaped");
1202 assert!(d.contains(r"\`d"), "backtick must be escaped");
1203 assert!(d.contains(r"\$e"), "dollar must be escaped");
1204 assert!(d.contains("%%f"), "percent must be doubled or it reads as a field code");
1205 }
1206
1207 #[test]
1208 fn every_platform_artifact_launches_with_the_background_flag() {
1209 assert!(scheduled_task_xml(&exe(), "test").contains("--background"));
1213 assert!(launch_agent_plist(&exe(), "test").contains("<string>--background</string>"));
1214 assert!(xdg_desktop_entry(&exe(), "test").contains("--background"));
1215 }
1216
1217 #[test]
1220 fn a_login_start_that_finds_agentmux_running_opens_no_window() {
1221 let manual = vec!["agentmux".to_string()];
1222 let login = vec!["agentmux".to_string(), BACKGROUND_FLAG.to_string()];
1223 assert!(second_instance_opens_window(&manual));
1224 assert!(!second_instance_opens_window(&login));
1225 }
1226
1227 fn entry(target: &str, channel: Option<&str>) -> Entry {
1228 Entry { target: Some(target.to_string()), channel: channel.map(str::to_string), current: true }
1229 }
1230
1231 #[test]
1233 fn an_uninstall_removes_only_an_entry_that_runs_from_its_own_folder() {
1234 let (dir, ours, other) = if cfg!(target_os = "windows") {
1235 (
1236 r"C:\Users\a\AppData\Local\Programs\AgentMux",
1237 r"C:\Users\a\AppData\Local\Programs\AgentMux\agentmux.exe",
1238 r"C:\dev\agentmux\agentmux.exe",
1239 )
1240 } else {
1241 ("/opt/agentmux", "/opt/agentmux/agentmux", "/home/a/dev/agentmux/agentmux")
1242 };
1243 assert!(entry_runs_from(&entry(ours, Some("stable")), Path::new(dir)));
1244 assert!(!entry_runs_from(&entry(other, Some("stable")), Path::new(dir)));
1246 let sibling = format!("{}-dev{}agentmux.exe", dir, std::path::MAIN_SEPARATOR);
1248 assert!(!entry_runs_from(&entry(&sibling, None), Path::new(dir)));
1249 assert!(!entry_runs_from(&Entry { target: None, channel: None, current: true }, Path::new(dir)));
1251 assert!(!entry_runs_from(&entry(ours, None), Path::new("")));
1252 }
1253
1254 #[cfg(target_os = "windows")]
1255 #[test]
1256 fn windows_paths_compare_without_case_or_slash_direction() {
1257 let e = entry(r"c:\users\a\appdata\local\programs\agentmux\AGENTMUX.EXE", None);
1258 assert!(entry_runs_from(&e, Path::new("C:/Users/A/AppData/Local/Programs/AgentMux/")));
1259 }
1260
1261 #[test]
1262 fn plan_on_writes_unless_the_entry_is_already_ours_and_current() {
1263 let t = "/home/u/Desktop/AgentMux.AppImage";
1264 assert_eq!(plan(Some(true), None, "stable", Some(t)), Plan::Write);
1265 assert_eq!(plan(Some(true), Some(&entry(t, Some("stable"))), "stable", Some(t)), Plan::Nothing);
1266 assert_eq!(plan(Some(true), Some(&entry("/old/path", Some("stable"))), "stable", Some(t)), Plan::Write);
1268 assert_eq!(plan(Some(true), Some(&entry(t, Some("local-main-x"))), "stable", Some(t)), Plan::Write);
1270 }
1271
1272 #[test]
1273 fn plan_off_removes_only_this_channels_entry() {
1274 let t = "/opt/agentmux/agentmux";
1275 assert_eq!(plan(Some(false), Some(&entry(t, Some("stable"))), "stable", Some(t)), Plan::Remove);
1276 assert_eq!(plan(Some(false), Some(&entry(t, Some("local-main-x"))), "stable", Some(t)), Plan::Nothing);
1277 assert_eq!(plan(Some(false), Some(&entry(t, None)), "stable", Some(t)), Plan::Nothing);
1278 assert_eq!(plan(Some(false), None, "stable", Some(t)), Plan::Nothing);
1279 }
1280
1281 #[test]
1283 fn plan_needs_the_target_only_to_write() {
1284 let mine = entry("/x", Some("stable"));
1285 assert_eq!(plan(Some(false), Some(&mine), "stable", None), Plan::Remove);
1286 assert_eq!(plan(None, Some(&entry("/x", None)), "stable", None), Plan::Adopt);
1287 assert_eq!(plan(Some(true), Some(&mine), "stable", None), Plan::Write);
1289 }
1290
1291 #[test]
1293 fn plan_never_set_is_off_but_adopts_an_entry_from_before_the_setting() {
1294 let t = "/x";
1295 assert_eq!(plan(None, None, "stable", Some(t)), Plan::Nothing);
1296 assert_eq!(plan(None, Some(&entry(t, None)), "stable", Some(t)), Plan::Adopt);
1297 assert_eq!(plan(None, Some(&entry(t, Some("local-main-x"))), "stable", Some(t)), Plan::Nothing);
1298 }
1299
1300 #[test]
1301 fn every_artifact_reads_back_its_own_target_and_channel() {
1302 let exe = Path::new("/home/u/My Apps/Agent&Mux.AppImage");
1303 let want = Entry { target: Some(exe.display().to_string()), channel: Some("local-main-b28b7a".into()), current: true };
1304 assert_eq!(parse_desktop_entry(&xdg_desktop_entry(exe, "local-main-b28b7a")), want);
1305 assert_eq!(parse_plist(&launch_agent_plist(exe, "local-main-b28b7a")), want);
1306 let win = Path::new(r"C:\Users\u\AppData\Local\Programs\AgentMux & Co\agentmux.exe");
1307 assert_eq!(
1308 parse_task_xml(&scheduled_task_xml(win, "stable")),
1309 Entry { target: Some(win.display().to_string()), channel: Some("stable".into()), current: true }
1310 );
1311 }
1312
1313 #[test]
1315 fn a_pre_ownership_desktop_entry_reads_as_unowned_with_no_target() {
1316 let old = "[Desktop Entry]\nType=Application\nExec=\"/x/agentmux-launcher\" --background\n";
1317 assert_eq!(parse_desktop_entry(old), Entry { target: None, channel: None, current: true });
1318 }
1319
1320 #[test]
1321 fn the_desktop_entry_goes_inert_without_its_target_and_waits_for_the_session() {
1322 let d = xdg_desktop_entry(Path::new("/opt/agentmux/agentmux"), "stable");
1323 assert!(d.contains("\nTryExec=/opt/agentmux/agentmux\n"), "{d}");
1324 assert!(d.contains("\nX-GNOME-Autostart-Delay=10\n"), "{d}");
1325 assert!(d.contains("\nX-AgentMux-Channel=stable\n"), "{d}");
1326 }
1327
1328 #[test]
1329 fn a_login_entry_follows_its_file_when_the_file_is_moved_or_renamed_whichever_channel_wrote_it() {
1330 let old = "/home/user/Desktop/AgentMux_0.60.29_amd64.AppImage";
1331 let new = "/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage";
1332 let moved = |setting, entry: &Entry, channel| super::plan(setting, Some(entry), channel, Some(new), Some(old));
1333 assert_eq!(moved(Some(true), &entry(old, Some("local-x")), "local-x"), Plan::Write);
1335 for setting in [Some(true), Some(false), None] {
1338 assert_eq!(moved(setting, &entry(old, Some("local-x")), "stable"), if setting == Some(true) { Plan::Write } else { Plan::Repoint }, "{setting:?}");
1339 }
1340 assert_eq!(moved(Some(false), &entry("/opt/other/agentmux", Some("local-x")), "stable"), Plan::Nothing);
1342 assert_eq!(moved(Some(false), &entry(new, Some("local-x")), "stable"), Plan::Nothing);
1344 assert_eq!(super::plan(Some(false), Some(&entry(old, Some("local-x"))), "stable", Some(new), None), Plan::Nothing);
1345 assert_eq!(super::plan(Some(false), Some(&entry(old, Some("local-x"))), "stable", None, Some(old)), Plan::Nothing);
1347 }
1348
1349 #[test]
1350 fn status_says_off_on_or_broken_and_who_owns_the_entry() {
1351 let dir = tempfile::tempdir().unwrap();
1352 let there = dir.path().join("AgentMux.AppImage");
1353 std::fs::write(&there, b"x").unwrap();
1354 let there = there.display().to_string();
1355 let gone = dir.path().join("Gone.AppImage").display().to_string();
1356
1357 let none = status(None, false, "stable", true);
1358 assert_eq!((none.state, none.movable, none.owner_channel.as_deref(), none.target.as_deref()), (State::Off, false, None, None));
1359
1360 let ours = status(Some(&entry(&there, Some("stable"))), true, "stable", true);
1361 assert_eq!((ours.state, ours.movable, ours.owner_channel.as_deref()), (State::On, false, Some("stable")));
1362 assert_eq!(ours.target.as_deref(), Some(there.as_str()));
1363
1364 let broken = status(Some(&entry(&gone, Some("stable"))), true, "stable", true);
1365 assert_eq!((broken.state, broken.movable), (State::Broken, false), "ours but its file is gone: Repair, not a move");
1366
1367 let theirs = status(Some(&entry(&there, Some("local-x"))), true, "stable", true);
1368 assert_eq!((theirs.state, theirs.movable, theirs.owner_channel.as_deref()), (State::On, true, Some("local-x")));
1369 assert!(!status(Some(&entry(&there, Some("local-x"))), true, "stable", false).movable, "no target to point it at: not movable");
1370
1371 let unowned = status(Some(&entry(&there, None)), true, "stable", true);
1372 assert_eq!((unowned.state, unowned.movable, unowned.owner_channel), (State::On, true, None), "from before ownership was recorded");
1373
1374 let unreadable = status(None, true, "stable", true);
1375 assert_eq!((unreadable.state, unreadable.movable), (State::On, false), "registered but unparsed still starts something at login");
1376 }
1377
1378 #[test]
1379 fn status_json_has_the_keys_settings_reads() {
1380 let s = status(Some(&entry("/x/AgentMux.AppImage", Some("local-x"))), true, "stable", true);
1381 let v: serde_json::Value = serde_json::to_value(&s).unwrap();
1382 assert_eq!(
1383 v,
1384 serde_json::json!({ "state": "broken", "target": "/x/AgentMux.AppImage", "owner_channel": "local-x", "this_channel": "stable", "movable": true })
1385 );
1386 assert_eq!(serde_json::to_value(State::NeedsApproval).unwrap(), "needs_approval");
1387 }
1388
1389 #[test]
1390 fn a_login_entry_that_runs_a_file_that_is_gone_is_noticed() {
1391 let dir = tempfile::tempdir().unwrap();
1392 let there = dir.path().join("AgentMux.AppImage");
1393 std::fs::write(&there, b"x").unwrap();
1394 let gone = dir.path().join("Desktop").join("AgentMux.AppImage");
1395 assert_eq!(missing_target(&entry(&there.display().to_string(), Some("stable"))), None);
1396 let gone_text = gone.display().to_string();
1397 assert_eq!(missing_target(&entry(&gone_text, Some("local-x"))), Some(gone_text.as_str()));
1398 assert_eq!(missing_target(&Entry { target: None, channel: None, current: true }), None, "an entry with no target is rewritten, not reported");
1399 }
1400
1401 #[test]
1402 fn the_login_entry_runs_an_appimage_with_appimagelauncher_switched_off_and_nothing_else_that_way() {
1403 let image = xdg_desktop_entry(Path::new("/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage"), "stable");
1404 assert!(
1405 image.contains("\nExec=env APPIMAGELAUNCHER_DISABLE=1 \"/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage\" --background\n"),
1406 "{image}"
1407 );
1408 assert_eq!(parse_desktop_entry(&image).target.as_deref(), Some("/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage"));
1410 assert!(xdg_desktop_entry(Path::new("/home/user/a.appimage"), "stable").contains("Exec=env APPIMAGELAUNCHER_DISABLE=1 "));
1412 let wrapper = xdg_desktop_entry(Path::new("/usr/bin/agentmux"), "stable");
1413 assert!(wrapper.contains("\nExec=\"/usr/bin/agentmux\" --background\n"), "{wrapper}");
1414 }
1415
1416 #[test]
1417 fn an_appimage_login_entry_from_before_the_bypass_is_rewritten_even_when_it_runs_the_right_file() {
1418 let file = "/home/user/Applications/AgentMux_0.60.30_amd64.AppImage";
1419 let old = format!(
1420 "[Desktop Entry]\nType=Application\nTryExec={file}\nExec=\"{file}\" --background\nX-AgentMux-Channel=stable\n"
1421 );
1422 let read = parse_desktop_entry(&old);
1423 assert_eq!(read.target.as_deref(), Some(file));
1424 assert!(!read.current, "an AppImage entry that starts it with AppImageLauncher on");
1425 assert_eq!(plan(Some(true), Some(&read), "stable", Some(file)), Plan::Write);
1426 let new = parse_desktop_entry(&xdg_desktop_entry(Path::new(file), "stable"));
1428 assert!(new.current);
1429 assert_eq!(plan(Some(true), Some(&new), "stable", Some(file)), Plan::Nothing);
1430 assert!(parse_desktop_entry(&xdg_desktop_entry(Path::new("/usr/bin/agentmux"), "stable")).current);
1432 }
1433
1434 #[test]
1435 fn try_exec_cannot_be_used_to_inject_keys() {
1436 let d = xdg_desktop_entry(Path::new("/opt/x\nHidden=true"), "stable");
1437 assert!(!d.lines().any(|l| l == "Hidden=true"), "{d}");
1438 }
1439
1440 #[test]
1441 fn schtasks_utf16_output_is_decoded() {
1442 let mut bytes = vec![0xFF, 0xFE];
1443 for u in "<Command>\"C:\\a.exe\"</Command>".encode_utf16() {
1444 bytes.extend_from_slice(&u.to_le_bytes());
1445 }
1446 assert_eq!(decode_console_output(&bytes), "<Command>\"C:\\a.exe\"</Command>");
1447 assert_eq!(decode_console_output(b"plain"), "plain");
1448 }
1449
1450 #[test]
1451 fn the_stable_target_prefers_the_wrapper_path_then_this_exe() {
1452 let dir = std::env::temp_dir().join(format!("agentmux-stable-{}", std::process::id()));
1453 std::fs::create_dir_all(&dir).unwrap();
1454 let wrapper = dir.join("agentmux");
1455 std::fs::write(&wrapper, "").unwrap();
1456 let cur = || Ok(PathBuf::from("/cache/agentmux-launcher"));
1457
1458 assert_eq!(stable_target_from(Some(wrapper.clone().into()), cur()), Ok(wrapper.clone()));
1459 assert_eq!(stable_target_from(Some(dir.join("gone").into()), cur()), cur());
1461 assert_eq!(stable_target_from(None, cur()), cur());
1462 let _ = std::fs::remove_dir_all(&dir);
1463 }
1464}