Skip to main content

agentmux_srv_core/backend/viewer/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The viewer: a read-only window onto this channel's agents for a paired
5//! device (agentmux-mobile's SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07
6//! §4, §5, §13.2, §13.3).
7//!
8//! What it adds next to the LAN routes, and why each part exists:
9//! - a credential that is not public: a per-device viewer token, handed out
10//!   once against a pairing code shown on this screen, stored hashed, and
11//!   revocable (`pairing`, `storage::viewer_devices`). Never the `lan_key`
12//!   (anyone on the network has it) and never the instance `auth_key`.
13//! - encryption on the wire: the viewer routes are served only on a TLS
14//!   listener whose self-signed certificate the device pins by the
15//!   fingerprint in the QR (`cert`). The listener follows LAN discovery like
16//!   the other LAN listeners (`lan::listeners`), on its own port of the LAN
17//!   port range.
18//! - the feed itself: an agent's transcript, a bounded snapshot then live
19//!   appends (`feed`, the route in `server::http_viewer`), with what a device
20//!   is never shown from it taken out on the host (`filter`).
21
22pub mod audit;
23pub mod cert;
24pub mod client;
25pub mod feed;
26pub mod filter;
27pub mod origin;
28pub mod pairing;
29pub mod panes;
30pub mod sends;
31pub mod signing;
32pub mod terminal;
33
34use std::collections::HashMap;
35use std::net::IpAddr;
36use std::path::PathBuf;
37use std::sync::atomic::{AtomicU16, Ordering};
38use std::sync::{Arc, OnceLock};
39
40use tokio_util::sync::CancellationToken;
41
42/// Open feeds one device may hold; the next gets 503.
43pub const MAX_FEEDS_PER_DEVICE: usize = 4;
44/// Open feeds this srv serves in all; the next gets 503.
45pub const MAX_FEEDS: usize = 16;
46/// A device's `last_seen_ms` is written at most this often.
47pub const LAST_SEEN_EVERY_MS: i64 = 60_000;
48
49/// Why a feed was refused.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum FeedRefused {
52    PerDevice,
53    Total,
54    /// The host's person stopped this device's viewing ([`ViewerService::stop_viewing`]).
55    Stopped,
56}
57
58/// One open feed: its lease's id, the token that ends it, and, for an agent's feed, the agent and when it opened.
59struct OpenFeed {
60    id: u64,
61    token: CancellationToken,
62    agent: Option<(String, i64)>,
63}
64
65/// Called when who watches which agent, or who sent one a message, changes (srv publishes `ViewerWatchingChanged`).
66pub type WatchingHook = Arc<dyn Fn() + Send + Sync>;
67
68#[derive(Default)]
69struct FeedRegistry {
70    by_device: HashMap<String, Vec<OpenFeed>>,
71    next_id: u64,
72    hook: Option<WatchingHook>,
73    /// Devices whose viewing the host's person stopped: no feed opens until it is allowed again.
74    stopped: std::collections::HashSet<String>,
75}
76
77impl FeedRegistry {
78    fn total(&self) -> usize {
79        self.by_device.values().map(Vec::len).sum()
80    }
81}
82
83/// A paired device watching an agent, since its earliest feed of that agent still open opened (unix ms).
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Watch {
86    pub device_id: String,
87    pub agent: String,
88    pub since_ms: i64,
89    /// When the device last sent the agent a message, if it did while this srv ran.
90    pub last_sent_ms: Option<i64>,
91}
92
93/// One open feed's place under the caps. Dropping it frees the place;
94/// `token` is cancelled when the device is revoked.
95pub struct FeedLease {
96    registry: Arc<parking_lot::Mutex<FeedRegistry>>,
97    device_id: String,
98    id: u64,
99    pub token: CancellationToken,
100    /// Run once when the feed closes (its Audit row, set by `audit::feed_opened`).
101    on_close: Option<Box<dyn FnOnce() + Send + Sync>>,
102}
103
104impl FeedLease {
105    /// Run `f` when this feed closes, however it ends (the device went away, it was revoked or stopped).
106    pub fn on_close(mut self, f: impl FnOnce() + Send + Sync + 'static) -> Self {
107        self.on_close = Some(Box::new(f));
108        self
109    }
110}
111
112impl Drop for FeedLease {
113    fn drop(&mut self) {
114        if let Some(f) = self.on_close.take() {
115            f();
116        }
117        let mut reg = self.registry.lock();
118        let mut watched = false;
119        if let Some(list) = reg.by_device.get_mut(&self.device_id) {
120            watched = list.iter().any(|f| f.id == self.id && f.agent.is_some());
121            list.retain(|f| f.id != self.id);
122            if list.is_empty() {
123                reg.by_device.remove(&self.device_id);
124            }
125        }
126        let hook = reg.hook.clone().filter(|_| watched);
127        drop(reg);
128        if let Some(hook) = hook {
129            hook();
130        }
131    }
132}
133
134/// The port the viewer listener is advertised on, process-wide, for the UDP
135/// identity replies (which have no `AppState` in hand). Installed once by
136/// `bootstrap`; absent in tests.
137static ADVERTISED_PORT: OnceLock<Arc<AtomicU16>> = OnceLock::new();
138
139/// The viewer listener's port while at least one viewer listener is bound.
140pub fn advertised_viewer_port() -> Option<u16> {
141    ADVERTISED_PORT.get().map(|p| p.load(Ordering::Relaxed)).filter(|p| *p != 0)
142}
143
144pub struct ViewerService {
145    /// Where the certificate is kept; `None` keeps it in memory only.
146    data_dir: Option<PathBuf>,
147    tls: parking_lot::Mutex<Option<Arc<cert::ViewerTls>>>,
148    pub pairing: pairing::Pairing,
149    pub hub: Arc<feed::FeedHub>,
150    feeds: Arc<parking_lot::Mutex<FeedRegistry>>,
151    max_per_device: usize,
152    max_total: usize,
153    /// 0 while no viewer listener is bound.
154    advertised_port: Arc<AtomicU16>,
155    /// The addresses viewer listeners are bound on, for the QR's `host`.
156    bound: parking_lot::Mutex<Vec<IpAddr>>,
157    /// The viewer port, held on loopback (bound, never listening) from the
158    /// first time the listener comes up until exit, so another instance on
159    /// this host never takes it from the range and the port a device saw
160    /// stays ours across LAN off/on.
161    reservation: parking_lot::Mutex<Option<(u16, socket2::Socket)>>,
162    /// When each device's `last_seen_ms` was last written.
163    last_seen_written: parking_lot::Mutex<HashMap<String, i64>>,
164    /// What each device sent lately: its rate limit and `message_id`s.
165    pub sends: parking_lot::Mutex<sends::SendLedger>,
166    /// The nonces of computers' signed feed opens seen lately (`signing::NonceLog`).
167    pub nonces: parking_lot::Mutex<signing::NonceLog>,
168    /// When each device last sent each agent a message: `(device, agent)` -> unix ms.
169    sent_to: parking_lot::Mutex<HashMap<(String, String), i64>>,
170}
171
172impl ViewerService {
173    /// A viewer whose feeds watch `broker`.
174    pub fn new(data_dir: Option<PathBuf>, broker: &crate::backend::mps::Broker) -> Arc<Self> {
175        Self::with_limits(data_dir, broker, Arc::new(feed::FeedHub::default()), MAX_FEEDS_PER_DEVICE, MAX_FEEDS)
176    }
177
178    pub fn with_limits(
179        data_dir: Option<PathBuf>,
180        broker: &crate::backend::mps::Broker,
181        hub: Arc<feed::FeedHub>,
182        max_per_device: usize,
183        max_total: usize,
184    ) -> Arc<Self> {
185        hub.install(broker);
186        Arc::new(Self {
187            data_dir,
188            tls: parking_lot::Mutex::new(None),
189            pairing: pairing::Pairing::new(),
190            hub,
191            feeds: Arc::new(parking_lot::Mutex::new(FeedRegistry::default())),
192            max_per_device,
193            max_total,
194            advertised_port: Arc::new(AtomicU16::new(0)),
195            bound: parking_lot::Mutex::new(Vec::new()),
196            reservation: parking_lot::Mutex::new(None),
197            last_seen_written: parking_lot::Mutex::new(HashMap::new()),
198            sends: parking_lot::Mutex::new(sends::SendLedger::default()),
199            nonces: parking_lot::Mutex::new(signing::NonceLog::default()),
200            sent_to: parking_lot::Mutex::new(HashMap::new()),
201        })
202    }
203
204    /// Make this the process's viewer: its port is the advertised one (`advertised_viewer_port`), and a change of
205    /// who watches which agent is published on `broker` (`ViewerWatchingChanged`), for the window's "being viewed"
206    /// strip and chip.
207    pub fn install_global(&self, broker: Arc<crate::backend::mps::Broker>) {
208        let _ = ADVERTISED_PORT.set(Arc::clone(&self.advertised_port));
209        self.set_watching_hook(Arc::new(move || {
210            broker.publish_event::<crate::backend::mps_events::ViewerWatchingChanged>(&(), vec![], 0);
211        }));
212    }
213
214    /// The handle the fleet feed reads `viewer_port` from.
215    pub fn advertised_port_handle(&self) -> Arc<AtomicU16> {
216        Arc::clone(&self.advertised_port)
217    }
218
219    pub fn advertised_port(&self) -> Option<u16> {
220        Some(self.advertised_port.load(Ordering::Relaxed)).filter(|p| *p != 0)
221    }
222
223    /// The certificate, made and kept on first need.
224    pub fn tls(&self) -> Result<Arc<cert::ViewerTls>, String> {
225        let mut slot = self.tls.lock();
226        if let Some(tls) = slot.as_ref() {
227            return Ok(Arc::clone(tls));
228        }
229        let tls = Arc::new(match &self.data_dir {
230            Some(dir) => cert::load_or_create(dir)?,
231            None => return Err("the viewer has no data directory for its certificate".to_string()),
232        });
233        *slot = Some(Arc::clone(&tls));
234        Ok(tls)
235    }
236
237    /// The viewer port: the one already held, else the first port of
238    /// `candidates` free on loopback, now held. `None` when none is free.
239    pub fn reserve_port(&self, candidates: impl IntoIterator<Item = u16>) -> Option<u16> {
240        let mut slot = self.reservation.lock();
241        if let Some((port, _)) = slot.as_ref() {
242            return Some(*port);
243        }
244        for port in candidates {
245            let Ok(socket) = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None) else {
246                continue;
247            };
248            let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
249            if socket.bind(&addr.into()).is_ok() {
250                *slot = Some((port, socket));
251                return Some(port);
252            }
253        }
254        None
255    }
256
257    /// Record which addresses viewer listeners are bound on, and advertise
258    /// the port while there is at least one.
259    pub fn set_bound(&self, addrs: Vec<IpAddr>, port: u16) {
260        let up = !addrs.is_empty();
261        *self.bound.lock() = addrs;
262        self.advertised_port.store(if up { port } else { 0 }, Ordering::Relaxed);
263    }
264
265    /// The IPv4 address the QR names: the primary outbound one when a viewer
266    /// listener is bound there, else the first bound IPv4 address.
267    pub fn pair_host(&self) -> Option<IpAddr> {
268        let bound = self.bound.lock().clone();
269        let primary = crate::backend::lan::listeners::primary_lan_ipv4();
270        primary
271            .filter(|p| bound.contains(p))
272            .or_else(|| bound.iter().copied().find(IpAddr::is_ipv4))
273    }
274
275    /// Take a place for one more feed of `device_id`, or say why not. `agent` names the agent an agent's feed
276    /// watches, so the host can show who watches it ([`Self::watching`]); a terminal's or the system figures' feed
277    /// has none.
278    pub fn open_feed(&self, device_id: &str, agent: Option<&str>) -> Result<FeedLease, FeedRefused> {
279        let mut reg = self.feeds.lock();
280        if reg.stopped.contains(device_id) {
281            return Err(FeedRefused::Stopped);
282        }
283        if reg.total() >= self.max_total {
284            return Err(FeedRefused::Total);
285        }
286        if reg.by_device.get(device_id).map_or(0, Vec::len) >= self.max_per_device {
287            return Err(FeedRefused::PerDevice);
288        }
289        reg.next_id += 1;
290        let id = reg.next_id;
291        let token = CancellationToken::new();
292        let agent = agent.map(|a| (a.to_string(), agentmux_common::time::now_ms()));
293        let hook = reg.hook.clone().filter(|_| agent.is_some());
294        reg.by_device.entry(device_id.to_string()).or_default().push(OpenFeed { id, token: token.clone(), agent });
295        drop(reg);
296        if let Some(hook) = hook {
297            hook();
298        }
299        Ok(FeedLease { registry: Arc::clone(&self.feeds), device_id: device_id.to_string(), id, token, on_close: None })
300    }
301
302    /// Close every open feed of `device_id` (it was revoked, or the host's person stopped its viewing). Returns
303    /// how many.
304    pub fn close_device_feeds(&self, device_id: &str) -> usize {
305        let reg = self.feeds.lock();
306        let Some(list) = reg.by_device.get(device_id) else { return 0 };
307        for feed in list {
308            feed.token.cancel();
309        }
310        list.len()
311    }
312
313    /// The host's person stops `device_id`'s viewing: its open feeds end now and it opens none until
314    /// [`Self::allow_viewing`] (or srv restarts). Its pairing and grants stay. Returns how many feeds closed.
315    pub fn stop_viewing(&self, device_id: &str) -> usize {
316        self.feeds.lock().stopped.insert(device_id.to_string());
317        self.close_device_feeds(device_id)
318    }
319
320    /// Let a device whose viewing was stopped open feeds again.
321    pub fn allow_viewing(&self, device_id: &str) {
322        self.feeds.lock().stopped.remove(device_id);
323    }
324
325    /// Whether the host's person stopped `device_id`'s viewing.
326    pub fn viewing_stopped(&self, device_id: &str) -> bool {
327        self.feeds.lock().stopped.contains(device_id)
328    }
329
330    /// Call `hook` whenever who watches which agent, or who sent one a message, changes.
331    pub fn set_watching_hook(&self, hook: WatchingHook) {
332        self.feeds.lock().hook = Some(hook);
333    }
334
335    /// Record that `device_id` sent `agent` a message at `now_ms`: it is driving the agent.
336    pub fn note_sent(&self, device_id: &str, agent: &str, now_ms: i64) {
337        self.sent_to.lock().insert((device_id.to_string(), agent.to_string()), now_ms);
338        let hook = self.feeds.lock().hook.clone();
339        if let Some(hook) = hook {
340            hook();
341        }
342    }
343
344    /// Who watches which agent now: one entry per device and agent, by device and then agent.
345    pub fn watching(&self) -> Vec<Watch> {
346        let mut by: std::collections::BTreeMap<(String, String), i64> = std::collections::BTreeMap::new();
347        for (device_id, list) in &self.feeds.lock().by_device {
348            for (agent, opened_ms) in list.iter().filter_map(|f| f.agent.as_ref()) {
349                let since = by.entry((device_id.clone(), agent.clone())).or_insert(*opened_ms);
350                *since = (*since).min(*opened_ms);
351            }
352        }
353        let sent_to = self.sent_to.lock();
354        by.into_iter()
355            .map(|((device_id, agent), since_ms)| {
356                let last_sent_ms = sent_to.get(&(device_id.clone(), agent.clone())).copied();
357                Watch { device_id, agent, since_ms, last_sent_ms }
358            })
359            .collect()
360    }
361
362    #[cfg(any(test, feature = "test-support"))]
363    pub fn open_feeds(&self) -> usize {
364        self.feeds.lock().total()
365    }
366
367    /// Whether `device_id`'s `last_seen_ms` is due to be written at `now_ms`;
368    /// records it when it is.
369    pub fn last_seen_due(&self, device_id: &str, now_ms: i64) -> bool {
370        let mut written = self.last_seen_written.lock();
371        match written.get(device_id) {
372            Some(at) if now_ms - at < LAST_SEEN_EVERY_MS => false,
373            _ => {
374                written.insert(device_id.to_string(), now_ms);
375                true
376            }
377        }
378    }
379
380    /// Forget a revoked device's throttle entry and what it sent.
381    pub fn forget_device(&self, device_id: &str) {
382        self.last_seen_written.lock().remove(device_id);
383        self.sends.lock().forget_device(device_id);
384        self.sent_to.lock().retain(|(device, _), _| device != device_id);
385        self.allow_viewing(device_id);
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    fn service(per_device: usize, total: usize) -> Arc<ViewerService> {
394        let broker = crate::backend::mps::Broker::new();
395        ViewerService::with_limits(None, &broker, Arc::new(feed::FeedHub::default()), per_device, total)
396    }
397
398    #[test]
399    fn feeds_are_capped_per_device_and_in_all() {
400        let v = service(2, 3);
401        let a1 = v.open_feed("a", None).unwrap();
402        let _a2 = v.open_feed("a", None).unwrap();
403        assert_eq!(v.open_feed("a", None).err(), Some(FeedRefused::PerDevice));
404        let _b1 = v.open_feed("b", None).unwrap();
405        assert_eq!(v.open_feed("c", None).err(), Some(FeedRefused::Total));
406        drop(a1);
407        assert_eq!(v.open_feeds(), 2);
408        assert!(v.open_feed("c", None).is_ok(), "a closed feed frees its place");
409    }
410
411    #[test]
412    fn closing_a_devices_feeds_cancels_only_its_own() {
413        let v = service(4, 16);
414        let a1 = v.open_feed("a", None).unwrap();
415        let a2 = v.open_feed("a", None).unwrap();
416        let b1 = v.open_feed("b", None).unwrap();
417        assert_eq!(v.close_device_feeds("a"), 2);
418        assert!(a1.token.is_cancelled() && a2.token.is_cancelled());
419        assert!(!b1.token.is_cancelled());
420        assert_eq!(v.close_device_feeds("nobody"), 0);
421    }
422
423    #[test]
424    fn who_watches_which_agent_is_listed_and_each_change_calls_the_hook() {
425        let v = service(4, 16);
426        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
427        let counted = Arc::clone(&calls);
428        v.set_watching_hook(Arc::new(move || {
429            counted.fetch_add(1, Ordering::SeqCst);
430        }));
431        let _terminal = v.open_feed("pixel", None).unwrap();
432        assert!(v.watching().is_empty(), "a terminal's feed watches no agent");
433        assert_eq!(calls.load(Ordering::SeqCst), 0);
434        let first = v.open_feed("studio", Some("Clamk")).unwrap();
435        let second = v.open_feed("studio", Some("Clamk")).unwrap();
436        let _other = v.open_feed("pixel", Some("Korp")).unwrap();
437        let listed = v.watching();
438        assert_eq!(listed.iter().map(|w| (w.device_id.as_str(), w.agent.as_str())).collect::<Vec<_>>(), [("pixel", "Korp"), ("studio", "Clamk")]);
439        assert_eq!(calls.load(Ordering::SeqCst), 3);
440        v.note_sent("studio", "Clamk", 42);
441        assert_eq!(v.watching()[1].last_sent_ms, Some(42));
442        drop(first);
443        assert_eq!(v.watching().len(), 2, "still open in its second feed");
444        drop(second);
445        assert_eq!(v.watching().len(), 1);
446        assert_eq!(calls.load(Ordering::SeqCst), 6, "three opens, a send and two closes");
447    }
448
449    #[test]
450    fn a_stopped_device_opens_no_feed_until_it_is_allowed_again_or_forgotten() {
451        let v = service(4, 16);
452        let open = v.open_feed("studio", Some("Clamk")).unwrap();
453        assert_eq!(v.stop_viewing("studio"), 1);
454        assert!(open.token.is_cancelled() && v.viewing_stopped("studio"));
455        assert_eq!(v.open_feed("studio", Some("Clamk")).err(), Some(FeedRefused::Stopped));
456        assert!(v.open_feed("pixel", Some("Clamk")).is_ok(), "only that device");
457        v.allow_viewing("studio");
458        assert!(v.open_feed("studio", Some("Clamk")).is_ok());
459        v.stop_viewing("studio");
460        v.forget_device("studio");
461        assert!(!v.viewing_stopped("studio"), "revoking clears it");
462    }
463
464    #[test]
465    fn last_seen_is_written_at_most_once_a_minute() {
466        let v = service(4, 16);
467        assert!(v.last_seen_due("a", 1_000));
468        assert!(!v.last_seen_due("a", 1_000 + LAST_SEEN_EVERY_MS - 1));
469        assert!(v.last_seen_due("b", 1_000), "per device");
470        assert!(v.last_seen_due("a", 1_000 + LAST_SEEN_EVERY_MS));
471    }
472
473    #[test]
474    fn the_port_is_reserved_once_and_skips_a_taken_one() {
475        let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
476        let taken_port = taken.local_addr().unwrap().port();
477        let free = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
478        let v = service(4, 16);
479        assert_eq!(v.reserve_port([taken_port, free]), Some(free));
480        assert!(
481            std::net::TcpListener::bind(("127.0.0.1", free)).is_err(),
482            "the reservation holds the port against other instances"
483        );
484        assert_eq!(v.reserve_port([taken_port]), Some(free), "kept, not chosen again");
485    }
486
487    #[test]
488    fn the_port_is_advertised_only_while_bound() {
489        let v = service(4, 16);
490        assert_eq!(v.advertised_port(), None);
491        v.set_bound(vec![IpAddr::from([198, 51, 100, 7])], 29702);
492        assert_eq!(v.advertised_port(), Some(29702));
493        assert_eq!(v.pair_host(), Some(IpAddr::from([198, 51, 100, 7])));
494        v.set_bound(Vec::new(), 29702);
495        assert_eq!(v.advertised_port(), None);
496        assert_eq!(v.pair_host(), None);
497    }
498
499    #[test]
500    fn without_a_data_directory_there_is_no_certificate() {
501        assert!(service(4, 16).tls().is_err());
502    }
503}