Skip to main content

agentmux_srv/sagas/
deeplink_open.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's deep-link open, carried to the window and its outcome carried back
5//! (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md §4.2, R3, G9).
6//!
7//! srv's guard (`server::deeplink_guard`) has already let the open through when it reaches here. srv publishes
8//! `deeplink:open`; the window that holds the tab carries it out with the app's executor, which applies the rules only
9//! the window can (R5, the caps and the typing queue of G3, G6), and answers `deeplink.open.done`. The answer is
10//! accepted only from the proven AgentMux window (`operator_only`), so an agent can't report an outcome for itself.
11//!
12//! An open the window has not answered within [`WAIT_FOR`] is `queued` for the caller (the person is typing, the
13//! app is starting); its outcome is recorded when it comes, until [`KEEP_FOR`].
14
15use std::collections::HashMap;
16use std::sync::{Arc, LazyLock, Mutex};
17use std::time::Duration;
18
19use serde::{Deserialize, Serialize};
20
21use crate::backend::mps_events::DeepLinkOpenEvent;
22use crate::backend::rpc::engine::WshRpcEngine;
23use crate::server::AppState;
24use agentmux_common::time::now_ms;
25
26pub const COMMAND_DEEPLINK_OPEN_DONE: &str = "deeplink.open.done";
27/// How long the caller waits for the window's answer before it is told `queued`. Longer than the typing queue's
28/// own wait (two seconds after the last keystroke, ten at most), so an open that waited for the person still answers.
29pub const WAIT_FOR: Duration = Duration::from_secs(13);
30/// How long a window may still carry an open out, and srv still records its outcome.
31pub const KEEP_FOR: Duration = Duration::from_secs(60);
32/// How many opens a window that connects late is given (§8: the app is still starting; a queue of ten).
33const REPLAY_EVENTS: usize = 10;
34
35/// What the window answers: the outcome of R3, as the executor gave it.
36#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, ts_rs::TS)]
37#[ts(export, export_to = "../../../frontend/types/rpc/")]
38pub struct DeepLinkOutcome {
39    #[ts(type = r#""opened" | "reused" | "queued" | "refused""#)]
40    pub outcome: String,
41    pub label: String,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    #[ts(optional)]
44    pub block_id: Option<String>,
45    /// `missing` when the view opened but the place inside it is gone (§8).
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    #[ts(optional)]
48    pub place: Option<String>,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    #[ts(optional)]
51    pub reason_code: Option<String>,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    #[ts(optional)]
54    pub reason: Option<String>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    #[ts(optional)]
57    pub remedy: Option<String>,
58}
59
60impl DeepLinkOutcome {
61    pub fn refused(label: &str, code: &str, reason: &str, remedy: Option<String>) -> Self {
62        Self {
63            outcome: "refused".into(),
64            label: label.into(),
65            reason_code: Some(code.into()),
66            reason: Some(reason.into()),
67            remedy,
68            ..Default::default()
69        }
70    }
71
72    pub fn queued(label: &str, code: &str, reason: &str) -> Self {
73        Self { outcome: "queued".into(), label: label.into(), reason_code: Some(code.into()), reason: Some(reason.into()), ..Default::default() }
74    }
75
76    /// Whether a window's answer is one srv can record: a known outcome, and text of a sane length.
77    fn well_formed(&self) -> bool {
78        let short = |s: &Option<String>| s.as_ref().is_none_or(|t| t.len() <= 500);
79        matches!(self.outcome.as_str(), "opened" | "reused" | "queued" | "refused")
80            && self.label.len() <= 200
81            && short(&self.block_id)
82            && short(&self.place)
83            && short(&self.reason_code)
84            && short(&self.reason)
85            && short(&self.remedy)
86    }
87}
88
89/// Data for `deeplink.open.done`.
90#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
91#[ts(export, export_to = "../../../frontend/types/rpc/")]
92pub struct CommandDeepLinkOpenDoneData {
93    pub request_id: String,
94    pub outcome: DeepLinkOutcome,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
98#[ts(export, export_to = "../../../frontend/types/rpc/")]
99pub struct DeepLinkOpenDoneResult {
100    #[ts(type = r#""recorded" | "too_late""#)]
101    pub status: String,
102}
103
104/// What to do with an outcome that comes after the caller stopped waiting: record it.
105pub type Late = Box<dyn FnOnce(&DeepLinkOutcome) + Send>;
106
107struct Entry {
108    answer: Option<DeepLinkOutcome>,
109    wake: Arc<tokio::sync::Notify>,
110    expires_at_ms: i64,
111    /// Set once the caller has stopped waiting.
112    late: Option<Late>,
113}
114
115static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
116
117fn entries() -> std::sync::MutexGuard<'static, HashMap<String, Entry>> {
118    ENTRIES.lock().unwrap_or_else(|e| e.into_inner())
119}
120
121/// Publish `event` and wait up to `window` for the window's outcome. `None` when none came in time: the caller says
122/// `queued`, and `late` records the outcome if it comes before the event expires.
123pub async fn carry_out(state: &AppState, event: DeepLinkOpenEvent, window: Duration, late: Late) -> Option<DeepLinkOutcome> {
124    let id = event.request_id.clone();
125    let wake = Arc::new(tokio::sync::Notify::new());
126    {
127        let mut map = entries();
128        let now = now_ms();
129        map.retain(|_, e| e.expires_at_ms > now);
130        map.insert(id.clone(), Entry { answer: None, wake: wake.clone(), expires_at_ms: event.expires_at_ms, late: None });
131    }
132    state.broker.publish_event::<crate::backend::mps_events::DeepLinkOpen>(&event, vec![], REPLAY_EVENTS);
133    let _ = tokio::time::timeout(window, wake.notified()).await;
134    let mut map = entries();
135    let Some(entry) = map.get_mut(&id) else { return None };
136    match entry.answer.take() {
137        Some(answer) => {
138            map.remove(&id);
139            Some(answer)
140        }
141        None => {
142            entry.late = Some(late);
143            None
144        }
145    }
146}
147
148/// The window's outcome for open `id`.
149pub fn done(id: &str, outcome: DeepLinkOutcome) -> &'static str {
150    if !outcome.well_formed() {
151        return "too_late";
152    }
153    let mut map = entries();
154    let Some(entry) = map.get_mut(id).filter(|e| e.expires_at_ms > now_ms() && e.answer.is_none()) else {
155        return "too_late";
156    };
157    if let Some(late) = entry.late.take() {
158        late(&outcome);
159        map.remove(id);
160        return "recorded";
161    }
162    entry.answer = Some(outcome);
163    entry.wake.notify_one();
164    "recorded"
165}
166
167/// `deeplink.open.done`, accepted only from the proven AgentMux window (`operator_only`), never from an agent.
168pub fn register(engine: &Arc<WshRpcEngine>) {
169    engine.register_typed(COMMAND_DEEPLINK_OPEN_DONE, move |cmd: CommandDeepLinkOpenDoneData, ctx| async move {
170        ctx.operator_only("only the AgentMux window reports what an open did")?;
171        Ok(DeepLinkOpenDoneResult { status: done(&cmd.request_id, cmd.outcome).to_string() })
172    });
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use crate::server::tests::test_state;
179
180    fn event(id: &str) -> DeepLinkOpenEvent {
181        DeepLinkOpenEvent {
182            request_id: id.into(),
183            link: "agentmux://settings/recording".into(),
184            agent_id: "a1".into(),
185            source: None,
186            caller_block_id: None,
187            tab_id: Some("t1".into()),
188            window_id: None,
189            target: "beside".into(),
190            expires_at_ms: now_ms() + KEEP_FOR.as_millis() as i64,
191        }
192    }
193
194    fn opened() -> DeepLinkOutcome {
195        DeepLinkOutcome { outcome: "opened".into(), label: "Settings › Recording".into(), block_id: Some("b9".into()), ..Default::default() }
196    }
197
198    fn id() -> String {
199        uuid::Uuid::new_v4().to_string()
200    }
201
202    #[tokio::test]
203    async fn the_windows_outcome_is_the_callers_answer() {
204        let state = test_state();
205        let rid = id();
206        let task = {
207            let (state, rid) = (state.clone(), rid.clone());
208            tokio::spawn(async move { carry_out(&state, event(&rid), Duration::from_secs(5), Box::new(|_| {})).await })
209        };
210        for _ in 0..200 {
211            if done(&rid, opened()) == "recorded" {
212                break;
213            }
214            tokio::time::sleep(Duration::from_millis(5)).await;
215        }
216        assert_eq!(task.await.unwrap(), Some(opened()));
217        assert_eq!(done(&rid, opened()), "too_late", "an open is answered once");
218    }
219
220    #[tokio::test]
221    async fn no_answer_in_time_is_queued_and_a_late_answer_is_still_recorded() {
222        let state = test_state();
223        let rid = id();
224        let seen = Arc::new(Mutex::new(None));
225        let rec = seen.clone();
226        let got = carry_out(&state, event(&rid), Duration::from_millis(30), Box::new(move |o| *rec.lock().unwrap() = Some(o.clone()))).await;
227        assert_eq!(got, None);
228        assert_eq!(done(&rid, opened()), "recorded");
229        assert_eq!(seen.lock().unwrap().clone(), Some(opened()));
230    }
231
232    #[test]
233    fn an_answer_for_no_open_or_a_malformed_one_is_too_late() {
234        assert_eq!(done("nothing-asked", opened()), "too_late");
235        let mut odd = opened();
236        odd.outcome = "approved".into();
237        assert_eq!(done("nothing-asked", odd), "too_late");
238        let mut long = opened();
239        long.label = "x".repeat(201);
240        assert!(!long.well_formed());
241    }
242
243    #[tokio::test]
244    async fn an_expired_open_takes_no_answer() {
245        let state = test_state();
246        let rid = id();
247        let mut ev = event(&rid);
248        ev.expires_at_ms = now_ms() - 1;
249        let _ = carry_out(&state, ev, Duration::from_millis(10), Box::new(|_| panic!("an expired open records nothing late"))).await;
250        assert_eq!(done(&rid, opened()), "too_late");
251    }
252}