1use 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";
27pub const WAIT_FOR: Duration = Duration::from_secs(13);
30pub const KEEP_FOR: Duration = Duration::from_secs(60);
32const REPLAY_EVENTS: usize = 10;
34
35#[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 #[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 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#[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
104pub 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 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
121pub 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
148pub 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
167pub 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}