Skip to main content

agentmux_launcher/
launch_link.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A deep link the operating system started the launcher with: a person clicked `agentmux://…` in a web page, a mail
5//! or a chat (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md R18, G4e; build 4). It is taken out of the
6//! arguments the host gets, and handed over once:
7//! - AgentMux is running: the launcher that lost the single-instance race sends it to the running host (`open_link`,
8//!   `second_instance::forward_launch`) instead of asking for a new window.
9//! - The link started AgentMux: the first host gets it in its environment (`AGENTMUX_OPEN_LINK`), and a host the
10//!   launcher restarts later does not open it again.
11//!
12//! The host passes it to srv, whose guard decides what a link from another program may show.
13//!
14//! The operating system's registrations put the link after `--` (`agentmux.exe -- "%1"` on Windows, `-- %u` in the
15//! Linux desktop entry): nothing after it is ever read as the launcher's own flag or passed on, so a link that carries
16//! a quote (Windows quotes `%1` but doesn't escape one inside it) can't add a flag such as `--verify-update`.
17//!
18//! macOS hands a link to the running launcher by an Apple Event instead (`splash_mac`, `application:openURLs:`), the
19//! one that started it too: [`from_os`] keeps it for the first host when none has started yet, like an argument.
20
21use std::sync::{Mutex, MutexGuard};
22
23/// The host reads it (`crates/cef/src/commands/deeplink_open.rs`).
24pub(crate) const OPEN_LINK_ENV: &str = "AGENTMUX_OPEN_LINK";
25
26/// Longer than any link the registry makes; srv's parser refuses what isn't a link.
27const MAX_LINK: usize = 4096;
28
29/// This launch's link, and whether a host was started yet: one lock, so a link that arrives while the first host
30/// starts is either in its environment or handed back to forward, never neither.
31#[derive(Debug, Default, PartialEq)]
32struct Launch {
33    link: Option<String>,
34    host_started: bool,
35}
36
37impl Launch {
38    /// The link the launcher was started with; one the operating system handed over first stays.
39    fn started_with(&mut self, link: Option<String>) {
40        self.link = self.link.take().or(link);
41    }
42
43    /// The link for the first host's environment; nothing for a later one.
44    fn for_host(&mut self) -> Option<String> {
45        let first = !std::mem::replace(&mut self.host_started, true);
46        self.link.clone().filter(|_| first)
47    }
48
49    /// A link the operating system handed over: kept for the first host when none has started (and none is kept), else
50    /// given back to forward to the running host.
51    fn handed_over(&mut self, link: String) -> Option<String> {
52        if self.host_started || self.link.is_some() {
53            return Some(link);
54        }
55        self.link = Some(link);
56        None
57    }
58}
59
60static LAUNCH: Mutex<Launch> = Mutex::new(Launch { link: None, host_started: false });
61
62fn launch() -> MutexGuard<'static, Launch> {
63    LAUNCH.lock().unwrap_or_else(|e| e.into_inner())
64}
65
66/// Whether `arg` is a deep link: `agentmux://`, at most [`MAX_LINK`] bytes, no control characters.
67pub(crate) fn is_link(arg: &str) -> bool {
68    arg.get(..11).is_some_and(|s| s.eq_ignore_ascii_case("agentmux://")) && arg.len() <= MAX_LINK && !arg.chars().any(char::is_control)
69}
70
71/// Ends the launcher's own arguments; what follows is a link the operating system passes, and only that.
72const SEPARATOR: &str = "--";
73
74/// This process's arguments up to `--` (the program's name first): the only ones its own flags are read from.
75pub(crate) fn own_args() -> Vec<String> {
76    before_separator(std::env::args().collect())
77}
78
79fn before_separator(args: Vec<String>) -> Vec<String> {
80    args.into_iter().take_while(|a| a != SEPARATOR).collect()
81}
82
83/// `args` without the deep link and without anything after `--`, and the link (the first one, before or after `--`;
84/// the operating system passes one).
85pub(crate) fn split(args: Vec<String>) -> (Vec<String>, Option<String>) {
86    let link = args.iter().find(|a| is_link(a)).cloned();
87    (before_separator(args).into_iter().filter(|a| !is_link(a)).collect(), link)
88}
89
90/// `args` without the deep link, which is kept for [`link`]: it is handed over on its own, never passed on as an
91/// argument. Called once, by `main`.
92pub(crate) fn take(args: Vec<String>) -> Vec<String> {
93    let (rest, link) = split(args);
94    launch().started_with(link);
95    rest
96}
97
98/// This launch's link.
99pub(crate) fn link() -> Option<String> {
100    launch().link.clone()
101}
102
103/// The link for a host's environment: for the first host only.
104pub(crate) fn for_host() -> Option<String> {
105    launch().for_host()
106}
107
108/// A link the operating system handed this running launcher (macOS): None when it is kept for the first host, else
109/// the link, to forward to the running host (`open_link`). Not a link: None.
110#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
111pub(crate) fn from_os(link: &str) -> Option<String> {
112    let link = link.trim();
113    if !is_link(link) {
114        return None;
115    }
116    launch().handed_over(link.to_string())
117}
118
119/// Puts this launch's link in a host's environment, or makes sure an inherited one isn't there.
120pub(crate) fn set_host_env(cmd: &mut tokio::process::Command) {
121    match for_host() {
122        Some(link) => cmd.env(OPEN_LINK_ENV, link),
123        None => cmd.env_remove(OPEN_LINK_ENV),
124    };
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    fn args(list: &[&str]) -> Vec<String> {
132        list.iter().map(|s| s.to_string()).collect()
133    }
134
135    #[test]
136    fn the_link_is_taken_out_of_the_hosts_arguments() {
137        let (rest, link) = split(args(&["--background", "agentmux://settings/recording", "--x"]));
138        assert_eq!(rest, args(&["--background", "--x"]));
139        assert_eq!(link.as_deref(), Some("agentmux://settings/recording"));
140        let (rest, link) = split(args(&["--x"]));
141        assert_eq!((rest, link), (args(&["--x"]), None));
142    }
143
144    #[test]
145    fn nothing_after_the_separator_is_an_argument_but_the_link() {
146        // `agentmux.exe -- "%1"` with a link that closes the quote: Windows splits the rest into arguments.
147        let (rest, link) = split(args(&["--background", "--", "agentmux://help", "--verify-update", "1.0.0", "C:/x", "f"]));
148        assert_eq!(rest, args(&["--background"]));
149        assert_eq!(link.as_deref(), Some("agentmux://help"));
150        let (rest, link) = split(args(&["--", "--verify-update", "1.0.0"]));
151        assert_eq!((rest, link), (vec![], None));
152        assert_eq!(before_separator(args(&["agentmux", "--", "agentmux://x", "--background"])), args(&["agentmux"]));
153    }
154
155    #[test]
156    fn a_link_the_os_hands_over_goes_to_the_first_host_or_is_forwarded() {
157        // Before any host: kept for the first host, which gets it once.
158        let mut l = Launch::default();
159        assert_eq!(l.handed_over("agentmux://help".into()), None);
160        l.started_with(None);
161        assert_eq!(l.for_host().as_deref(), Some("agentmux://help"));
162        assert_eq!(l.for_host(), None, "a host the launcher restarts doesn't open it again");
163        // A host is running: forwarded.
164        assert_eq!(l.handed_over("agentmux://kanban".into()).as_deref(), Some("agentmux://kanban"));
165        // A second link before any host: forwarded, the first stays.
166        let mut l = Launch::default();
167        l.started_with(Some("agentmux://help".into()));
168        assert_eq!(l.handed_over("agentmux://kanban".into()).as_deref(), Some("agentmux://kanban"));
169        assert_eq!(l.for_host().as_deref(), Some("agentmux://help"));
170        // The OS's link came first: an argument doesn't replace it.
171        let mut l = Launch::default();
172        l.handed_over("agentmux://help".into());
173        l.started_with(Some("agentmux://kanban".into()));
174        assert_eq!(l.link.as_deref(), Some("agentmux://help"));
175    }
176
177    #[test]
178    fn only_an_agentmux_link_is_one() {
179        assert!(is_link("agentmux://help"));
180        assert!(is_link("AGENTMUX://help"));
181        for a in ["https://example.com", "agentmux:/help", "agentmux", "", "agentmux://a\nb"] {
182            assert!(!is_link(a), "{a:?}");
183        }
184        assert!(!is_link(&format!("agentmux://help#{}", "a".repeat(MAX_LINK))));
185    }
186}