Skip to main content

agentmux_srv/server/
deeplink_os.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A deep link another program hands to AgentMux (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md R18, G4e, G9;
5//! build 4): a link clicked in a web page, a mail or a chat reaches the running app as `POST /api/v1/host/deeplink_open`,
6//! sent by the host. Its caller is unknown and a web page can start it, so it navigates and nothing more:
7//!
8//! - Only the host calls the route, proven by its own token (`from_host`): every agent holds the instance key, so the
9//!   key does not open it. An agent opens with `Pane` open, recorded as itself.
10//! - A destination shown by path (the Editor, the Media view, Files) is refused: a page could have the browser
11//!   download a file and then send the person to it in our own preview.
12//! - A view whose sensitivity is not `public` (the Vault, Memory, the Audit) opens with no place in it: the pane only,
13//!   with no entry or row selected.
14//! - Five opens a minute, refused over it.
15//! - It lands in the window the person used last (or the one the host names), replaces nothing, takes no field's
16//!   focus, waits for the app to finish starting (`sagas::deeplink_open`), and its answer says which window it used,
17//!   for the host to raise.
18//! - Every open is recorded in the Audit with its source, refused ones too.
19
20use std::sync::OnceLock;
21use std::time::Instant;
22
23use agentmux_common::deeplinks::{self, ParsedLink, Sensitivity};
24use serde::Deserialize;
25
26use super::deeplink_guard::{label_of, refusal, Limiter, Refusal};
27use super::*;
28use crate::sagas::deeplink_open::{self, DeepLinkOutcome};
29
30/// Opens the operating system may ask for in a minute (G4e).
31pub(crate) const OS_RATE_LIMIT: usize = 5;
32
33/// The body of `POST /api/v1/host/deeplink_open`.
34#[derive(Debug, Clone, Default, Deserialize)]
35pub(crate) struct OsOpenRequest {
36    pub link: String,
37    /// The window to open it in. Absent, the one the person used last (`notify::router::Router::last_window`); with
38    /// no window open, the first window to start takes it.
39    #[serde(default)]
40    pub window_id: Option<String>,
41}
42
43fn limiter() -> &'static Limiter {
44    static LIMITER: OnceLock<Limiter> = OnceLock::new();
45    LIMITER.get_or_init(|| Limiter::new(OS_RATE_LIMIT))
46}
47
48/// What the operating system's open of `text` may show, by the rules above, or why it is refused. `allow` is the
49/// rate limit, so a test can give its own.
50pub(crate) fn os_guard(text: &str, allow: impl FnOnce() -> bool) -> Result<ParsedLink, Refusal> {
51    let mut link = deeplinks::parse_link(text.trim())?;
52    if link.view.sensitivity == Sensitivity::Path {
53        return Err(refusal("not_allowed", "a link from another program doesn't open a file or a folder", None));
54    }
55    if link.view.sensitivity != Sensitivity::Public {
56        link.place = None;
57        link.values.clear();
58        link.params.clear();
59        link.anchor = None;
60    }
61    if !allow() {
62        return Err(refusal("rate_limited", format!("links from other programs open at most {OS_RATE_LIMIT} places a minute"), None));
63    }
64    link.canonical = deeplinks::format_link(link.view, link.place, &link.values, &link.params, link.anchor.as_deref(), link.host.as_deref());
65    Ok(link)
66}
67
68/// G9: the open, recorded with its source.
69fn record(state: &AppState, request_id: &str, link: &str, outcome: &DeepLinkOutcome) {
70    let ok = matches!(outcome.outcome.as_str(), "opened" | "reused" | "queued");
71    let why = outcome.reason.as_deref().map(|r| format!(": {r}")).unwrap_or_default();
72    state.reactive_handler.log_fleet_action_audit(
73        None,
74        "",
75        outcome.block_id.as_deref().unwrap_or(""),
76        "pane.open_link",
77        ok,
78        (!ok).then_some(outcome.reason.as_deref().unwrap_or("refused")),
79        request_id,
80        Some(&format!("from another program: {} {link}{why}", outcome.outcome)),
81    );
82}
83
84/// `POST /api/v1/host/deeplink_open`: the host hands over a link another program opened. Answers the outcome of R3
85/// (200) for every open it decided, refused ones included, each recorded, with the `window_id` it opened in when it
86/// chose one; 403 for any caller but the host.
87pub(super) async fn handle_os_open_link(State(state): State<AppState>, headers: axum::http::HeaderMap, Json(req): Json<OsOpenRequest>) -> impl IntoResponse {
88    if !super::ui_handlers::from_host(&state, &headers).await {
89        return (StatusCode::FORBIDDEN, Json(json!({ "error": "only the AgentMux host hands over a link from another program; an agent opens one with Pane open" }))).into_response();
90    }
91    let request_id = uuid::Uuid::new_v4().to_string();
92    let link = match os_guard(&req.link, || limiter().allow("os", Instant::now()).is_ok()) {
93        Ok(l) => l,
94        Err(r) => {
95            let outcome = DeepLinkOutcome::refused(req.link.chars().take(120).collect::<String>().as_str(), r.code, &r.text, r.remedy);
96            record(&state, &request_id, &req.link.chars().take(200).collect::<String>(), &outcome);
97            return (StatusCode::OK, Json(json!(outcome))).into_response();
98        }
99    };
100    let window = req.window_id.filter(|w| !w.is_empty()).or_else(|| crate::backend::notify::router::get(&state.broker).and_then(|r| r.last_window()));
101    let event = crate::backend::mps_events::DeepLinkOpenEvent {
102        request_id: request_id.clone(),
103        link: link.canonical.clone(),
104        agent_id: String::new(),
105        source: Some("os".into()),
106        caller_block_id: None,
107        tab_id: None,
108        window_id: window.clone(),
109        target: "beside".into(),
110        expires_at_ms: agentmux_common::time::now_ms() + deeplink_open::KEEP_FOR.as_millis() as i64,
111    };
112    let late = {
113        let (state, rid, canonical) = (state.clone(), request_id.clone(), link.canonical.clone());
114        Box::new(move |o: &DeepLinkOutcome| record(&state, &rid, &canonical, o))
115    };
116    let label = label_of(&link);
117    let outcome = match deeplink_open::carry_out(&state, event, deeplink_open::WAIT_FOR, late).await {
118        Some(o) => o,
119        None => DeepLinkOutcome::queued(&label, "app_starting", "the window has not carried it out yet; it opens when it can"),
120    };
121    record(&state, &request_id, &link.canonical, &outcome);
122    let mut body = json!(outcome);
123    body["link"] = json!(link.canonical);
124    if let Some(w) = window {
125        body["window_id"] = json!(w);
126    }
127    (StatusCode::OK, Json(body)).into_response()
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn open(link: &str) -> Result<String, Refusal> {
135        os_guard(link, || true).map(|l| l.canonical)
136    }
137
138    #[test]
139    fn a_public_place_opens_whole() {
140        for link in ["agentmux://settings/recording#recording.engine", "agentmux://kanban/task/12", "agentmux://swarm/supervisor", "agentmux://help"] {
141            assert_eq!(open(link).unwrap(), link, "{link}");
142        }
143    }
144
145    #[test]
146    fn a_private_or_secret_view_opens_with_no_place_in_it() {
147        assert_eq!(open("agentmux://vault/entry/e_4f2a9c7b1d").unwrap(), "agentmux://vault");
148        assert_eq!(open("agentmux://vault/waiting/use-4f2a").unwrap(), "agentmux://vault");
149        assert_eq!(open("agentmux://memory/personal?agent=sorrel").unwrap(), "agentmux://memory");
150        assert_eq!(open("agentmux://audit/agent/sorrel").unwrap(), "agentmux://audit");
151    }
152
153    #[test]
154    fn a_destination_shown_by_path_is_refused() {
155        for link in ["agentmux://editor/%2Fhome%2Fme%2Fa.md", "agentmux://files/%2Fhome%2Fme", "agentmux://media/%2Fhome%2Fme%2Fclip.mp4"] {
156            assert_eq!(open(link).unwrap_err().code, "not_allowed", "{link}");
157        }
158    }
159
160    #[test]
161    fn a_link_the_parser_refuses_is_refused_with_its_reason() {
162        assert_eq!(open("agentmux://settings?pane=b1").unwrap_err().code, "invalid_link");
163        assert_eq!(open("agentmux://agent/a1").unwrap_err().code, "not_yet");
164    }
165
166    #[test]
167    fn five_opens_a_minute_and_the_sixth_is_refused() {
168        let l = Limiter::new(OS_RATE_LIMIT);
169        let t0 = Instant::now();
170        for i in 0..OS_RATE_LIMIT {
171            assert!(os_guard("agentmux://help", || l.allow("os", t0 + std::time::Duration::from_millis(i as u64)).is_ok()).is_ok());
172        }
173        let e = os_guard("agentmux://help", || l.allow("os", t0 + std::time::Duration::from_secs(1)).is_ok()).unwrap_err();
174        assert_eq!(e.code, "rate_limited");
175    }
176
177    #[test]
178    fn a_refused_link_does_not_count_against_the_limit() {
179        let l = Limiter::new(OS_RATE_LIMIT);
180        let t0 = Instant::now();
181        let mut asked = 0;
182        for _ in 0..OS_RATE_LIMIT + 2 {
183            let _ = os_guard("agentmux://files/%2Fhome", || {
184                asked += 1;
185                l.allow("os", t0).is_ok()
186            });
187        }
188        assert_eq!(asked, 0, "a path is refused before the limit is asked");
189    }
190}