Skip to main content

agentmux_srv/sagas/
capture_mask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The private and secret rectangles of each AgentMux window, read at the instant of a `UI` window capture
5//! (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md ยง7, G5).
6//!
7//! The capturing agent's MCP asks twice through `POST /api/v1/ui/capture_mask`: `begin` just before it takes the
8//! frame, `end` just after. Each ask publishes `capture:mask` to every window, and each window answers
9//! `capture.mask.report` with its rectangles, its size and scale, and (for `end`) whether anything changed since
10//! `begin`. The answer is accepted only from the AgentMux window (`operator_only`), so an agent can't report a mask.
11
12use std::collections::HashMap;
13use std::sync::{Arc, LazyLock, Mutex};
14use std::time::Duration;
15
16use serde::{Deserialize, Serialize};
17
18use crate::backend::mps_events::CaptureMaskEvent;
19use crate::backend::rpc::engine::WshRpcEngine;
20use crate::server::AppState;
21use agentmux_common::time::now_ms;
22
23pub const COMMAND_CAPTURE_MASK_REPORT: &str = "capture.mask.report";
24/// How long an ask waits for the windows' answers.
25pub const WAIT_FOR: Duration = Duration::from_millis(1500);
26/// The most rectangles one window may report.
27const MAX_RECTS: usize = 64;
28
29/// A rectangle in the window's viewport, in CSS pixels.
30#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, ts_rs::TS)]
31#[ts(export, export_to = "../../../frontend/types/rpc/")]
32pub struct CaptureRect {
33    pub x: f64,
34    pub y: f64,
35    pub w: f64,
36    pub h: f64,
37}
38
39/// One window's answer.
40#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, ts_rs::TS)]
41#[ts(export, export_to = "../../../frontend/types/rpc/")]
42pub struct WindowCaptureMask {
43    pub window_id: String,
44    /// The window's title, as the operating system shows it.
45    pub title: String,
46    /// The viewport in CSS pixels, and the device pixels per CSS pixel.
47    pub width: f64,
48    pub height: f64,
49    pub scale: f64,
50    /// Each pane or panel showing private or secret content.
51    pub rects: Vec<CaptureRect>,
52    /// The layout is moving (a resize, a drag, a pane animating, a tab switching).
53    pub moving: bool,
54    /// `end` only: the layout changed at some frame since `begin`.
55    pub changed: bool,
56    /// Set when the window can't give its rectangles: why.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    #[ts(optional)]
59    pub refuse: Option<String>,
60}
61
62impl WindowCaptureMask {
63    fn well_formed(&self) -> bool {
64        let finite = |v: f64| v.is_finite() && (0.0..=100_000.0).contains(&v);
65        self.window_id.len() <= 128
66            && self.title.len() <= 1024
67            && finite(self.width)
68            && finite(self.height)
69            && self.scale.is_finite()
70            && self.scale > 0.0
71            && self.scale <= 16.0
72            && self.rects.len() <= MAX_RECTS
73            && self.rects.iter().all(|r| r.x.is_finite() && r.y.is_finite() && finite(r.w) && finite(r.h))
74            && self.refuse.as_ref().is_none_or(|t| t.len() <= 500)
75    }
76}
77
78/// Data for `capture.mask.report`.
79#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
80#[ts(export, export_to = "../../../frontend/types/rpc/")]
81pub struct CommandCaptureMaskReportData {
82    pub capture_id: String,
83    #[ts(type = r#""begin" | "end""#)]
84    pub phase: String,
85    pub mask: WindowCaptureMask,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
89#[ts(export, export_to = "../../../frontend/types/rpc/")]
90pub struct CaptureMaskReportResult {
91    #[ts(type = r#""recorded" | "too_late""#)]
92    pub status: String,
93}
94
95struct Entry {
96    masks: Vec<WindowCaptureMask>,
97    expected: usize,
98    wake: Arc<tokio::sync::Notify>,
99    expires_at_ms: i64,
100}
101
102static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
103
104fn entries() -> std::sync::MutexGuard<'static, HashMap<String, Entry>> {
105    ENTRIES.lock().unwrap_or_else(|e| e.into_inner())
106}
107
108fn key(capture_id: &str, phase: &str) -> String {
109    format!("{phase}:{capture_id}")
110}
111
112/// How many windows srv knows, so an ask stops waiting once each has answered.
113fn window_count(state: &AppState) -> usize {
114    state.mstore.get_all::<crate::backend::obj::Window>().map(|w| w.len()).unwrap_or(0)
115}
116
117/// Ask every window for its mask and gather the answers that come within `wait`.
118pub async fn ask(state: &AppState, capture_id: &str, phase: &str, wait: Duration) -> Vec<WindowCaptureMask> {
119    gather(capture_id, phase, window_count(state), wait, || {
120        let event = CaptureMaskEvent { capture_id: capture_id.to_string(), phase: phase.to_string(), expires_at_ms: now_ms() + wait.as_millis() as i64 };
121        state.broker.publish_event::<crate::backend::mps_events::CaptureMask>(&event, vec![], 0);
122    })
123    .await
124}
125
126async fn gather(capture_id: &str, phase: &str, expected: usize, wait: Duration, publish: impl FnOnce()) -> Vec<WindowCaptureMask> {
127    let k = key(capture_id, phase);
128    let wake = Arc::new(tokio::sync::Notify::new());
129    {
130        let mut map = entries();
131        let now = now_ms();
132        map.retain(|_, e| e.expires_at_ms > now);
133        map.insert(k.clone(), Entry { masks: Vec::new(), expected: expected.max(1), wake: wake.clone(), expires_at_ms: now + wait.as_millis() as i64 });
134    }
135    publish();
136    let _ = tokio::time::timeout(wait, async {
137        loop {
138            let notified = wake.notified();
139            if entries().get(&k).is_none_or(|e| e.masks.len() >= e.expected) {
140                return;
141            }
142            notified.await;
143        }
144    })
145    .await;
146    entries().remove(&k).map(|e| e.masks).unwrap_or_default()
147}
148
149/// A window's answer to the ask `capture_id`, `phase`.
150pub fn report(capture_id: &str, phase: &str, mask: WindowCaptureMask) -> &'static str {
151    if !mask.well_formed() {
152        return "too_late";
153    }
154    let mut map = entries();
155    let Some(entry) = map.get_mut(&key(capture_id, phase)).filter(|e| e.expires_at_ms > now_ms()) else {
156        return "too_late";
157    };
158    if entry.masks.iter().any(|m| m.window_id == mask.window_id) {
159        return "too_late";
160    }
161    entry.masks.push(mask);
162    entry.wake.notify_one();
163    "recorded"
164}
165
166/// `capture.mask.report`, accepted only from the proven AgentMux window (`operator_only`), never from an agent.
167pub fn register(engine: &Arc<WshRpcEngine>) {
168    engine.register_typed(COMMAND_CAPTURE_MASK_REPORT, move |cmd: CommandCaptureMaskReportData, ctx| async move {
169        ctx.operator_only("only the AgentMux window reports what it shows")?;
170        Ok(CaptureMaskReportResult { status: report(&cmd.capture_id, &cmd.phase, cmd.mask).to_string() })
171    });
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    fn mask(window: &str) -> WindowCaptureMask {
179        WindowCaptureMask {
180            window_id: window.into(),
181            title: "AgentMux".into(),
182            width: 800.0,
183            height: 600.0,
184            scale: 1.5,
185            rects: vec![CaptureRect { x: 10.0, y: 20.0, w: 300.0, h: 200.0 }],
186            ..Default::default()
187        }
188    }
189
190    fn id() -> String {
191        uuid::Uuid::new_v4().to_string()
192    }
193
194    #[tokio::test]
195    async fn an_ask_gathers_each_windows_answer_and_stops_once_all_have_answered() {
196        let cid = id();
197        let started = std::time::Instant::now();
198        let task = {
199            let cid = cid.clone();
200            tokio::spawn(async move { gather(&cid, "begin", 2, Duration::from_secs(5), || {}).await })
201        };
202        for w in ["w1", "w2"] {
203            for _ in 0..200 {
204                if report(&cid, "begin", mask(w)) == "recorded" {
205                    break;
206                }
207                tokio::time::sleep(Duration::from_millis(5)).await;
208            }
209        }
210        let got = task.await.unwrap();
211        assert_eq!(got.len(), 2);
212        assert!(started.elapsed() < Duration::from_secs(4), "it did not wait out the whole time");
213        assert_eq!(report(&cid, "begin", mask("w3")), "too_late", "an ask that ended takes no answer");
214    }
215
216    #[tokio::test]
217    async fn a_window_answers_once_and_the_two_phases_are_kept_apart() {
218        let cid = id();
219        let task = {
220            let cid = cid.clone();
221            tokio::spawn(async move { gather(&cid, "end", 3, Duration::from_millis(300), || {}).await })
222        };
223        for _ in 0..200 {
224            if report(&cid, "end", mask("w1")) == "recorded" {
225                break;
226            }
227            tokio::time::sleep(Duration::from_millis(5)).await;
228        }
229        assert_eq!(report(&cid, "end", mask("w1")), "too_late");
230        assert_eq!(report(&cid, "begin", mask("w2")), "too_late", "no begin ask is open");
231        assert_eq!(task.await.unwrap(), vec![mask("w1")]);
232    }
233
234    #[test]
235    fn a_malformed_mask_is_not_taken() {
236        let mut bad = mask("w1");
237        bad.scale = 0.0;
238        assert!(!bad.well_formed());
239        let mut many = mask("w1");
240        many.rects = vec![CaptureRect::default(); MAX_RECTS + 1];
241        assert!(!many.well_formed());
242        let mut nan = mask("w1");
243        nan.rects[0].x = f64::NAN;
244        assert!(!nan.well_formed());
245        assert_eq!(report("nothing-asked", "begin", mask("w1")), "too_late");
246    }
247}