Skip to main content

agentmux_srv/server/app_api/
viewer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The desktop's side of pairing a device with the viewer listener
5//! (`backend::viewer`, agentmux-mobile's
6//! SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07 ยง13.2): the QR, the
7//! paired-devices list with Revoke, and an agent's "hide from paired
8//! devices" flag. Reached over the full-key WebSocket only, like every RPC.
9
10use super::*;
11
12pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
13    register_pair_start(engine, state);
14    register_devices(engine, state);
15    register_revoke(engine, state);
16    register_agent_hidden(engine, state);
17    register_can_send(engine, state);
18    register_watching(engine, state);
19    register_stop_watching(engine, state);
20}
21
22/// Who watches which agent now, each device named as it paired (for the "being viewed" strip and the status bar's
23/// chip). A device no longer paired is left out: its feeds are closing.
24pub(crate) fn watching_impl(state: &AppState) -> Result<ViewerWatchingResult, String> {
25    let devices: std::collections::HashMap<String, _> = state
26        .mstore
27        .viewer_device_list()
28        .map_err(|e| format!("viewer.watching: {e}"))?
29        .into_iter()
30        .map(|d| (d.device_id.clone(), d))
31        .collect();
32    let watching = state
33        .viewer
34        .watching()
35        .into_iter()
36        .filter_map(|w| {
37            let device = devices.get(&w.device_id)?;
38            Some(ViewerWatchInfo {
39                device_name: device.device_name.clone(),
40                device_kind: device.kind.as_str().to_string(),
41                device_id: w.device_id,
42                block_id: state.reactive_handler.get_agent(&w.agent).map(|a| a.block_id),
43                agent: w.agent,
44                since_ms: w.since_ms,
45                last_sent_ms: w.last_sent_ms,
46            })
47        })
48        .collect();
49    Ok(ViewerWatchingResult { watching, now_ms: agentmux_common::time::now_ms() })
50}
51
52fn register_watching(engine: &Arc<WshRpcEngine>, state: &AppState) {
53    let state = state.clone();
54    engine.register_typed(COMMAND_VIEWER_WATCHING, move |_req: Option<NoArgsReq>, _ctx| {
55        let state = state.clone();
56        async move { watching_impl(&state) }
57    });
58}
59
60/// "Stop viewing": end the device's open feeds now, and refuse its next ones (`stopped_by_host`) until the person
61/// lets it watch again (`resume`). Its pairing and grants stay. Only a paired device can be stopped (the hold is
62/// cleared on revoke, so one for an unknown id would never be).
63pub(crate) fn stop_watching_impl(state: &AppState, device_id: &str, resume: bool) -> Result<ViewerStopWatchingResult, String> {
64    if !resume {
65        let devices = state.mstore.viewer_device_list().map_err(|e| format!("viewer.stop-watching: {e}"))?;
66        if !devices.iter().any(|d| d.device_id == device_id) {
67            return Err(format!("viewer.stop-watching: no paired device {device_id}"));
68        }
69    }
70    let feeds_closed = if resume {
71        state.viewer.allow_viewing(device_id);
72        0
73    } else {
74        state.viewer.stop_viewing(device_id)
75    };
76    tracing::info!(%device_id, resume, feeds_closed, "viewer: the person stopped or allowed a device's viewing");
77    state.broker.publish_event::<crate::backend::mps_events::ViewerDevicesChanged>(&(), vec![], 0);
78    Ok(ViewerStopWatchingResult { feeds_closed })
79}
80
81fn register_stop_watching(engine: &Arc<WshRpcEngine>, state: &AppState) {
82    let state = state.clone();
83    engine.register_typed(COMMAND_VIEWER_STOP_WATCHING, move |cmd: CommandViewerStopWatchingData, _ctx| {
84        let state = state.clone();
85        async move { stop_watching_impl(&state, &cmd.device_id, cmd.resume.unwrap_or(false)) }
86    });
87}
88
89/// Why there is no QR to show: the viewer listener is not up.
90pub(crate) const NOT_LISTENING: &str =
91    "The viewer isn't listening on this network. Turn on LAN discovery to pair a device.";
92
93/// The `agentmux://pair` URL for a fresh code (cancelling the last one).
94pub(crate) fn pair_start_impl(state: &AppState) -> Result<ViewerPairStartResult, String> {
95    let (Some(port), Some(host)) = (state.viewer.advertised_port(), state.viewer.pair_host()) else {
96        return Err(NOT_LISTENING.to_string());
97    };
98    let fingerprint = state.viewer.tls()?.fingerprint.clone();
99    let (code, ttl) = state.viewer.pairing.start();
100    let query = url::form_urlencoded::Serializer::new(String::new())
101        .append_pair("v", "1")
102        .append_pair("host", &host.to_string())
103        .append_pair("port", &port.to_string())
104        .append_pair("fp", &fingerprint)
105        .append_pair("code", &code)
106        .append_pair("hostname", &state.hostname)
107        .append_pair("channel", &crate::backend::reactive::registry::local_channel_id())
108        .finish();
109    Ok(ViewerPairStartResult {
110        url: format!("agentmux://pair?{query}"),
111        expires_ms: agentmux_common::time::now_ms() + ttl.as_millis() as i64,
112    })
113}
114
115fn register_pair_start(engine: &Arc<WshRpcEngine>, state: &AppState) {
116    let state = state.clone();
117    engine.register_typed(COMMAND_VIEWER_PAIR_START, move |_req: Option<NoArgsReq>, _ctx| {
118        let state = state.clone();
119        async move { pair_start_impl(&state) }
120    });
121}
122
123fn register_devices(engine: &Arc<WshRpcEngine>, state: &AppState) {
124    let (mstore, viewer) = (state.mstore.clone(), state.viewer.clone());
125    engine.register_typed(COMMAND_VIEWER_DEVICES, move |_req: Option<NoArgsReq>, _ctx| {
126        let (mstore, viewer) = (mstore.clone(), viewer.clone());
127        async move {
128            let devices = mstore
129                .viewer_device_list()
130                .map_err(|e| format!("viewer.devices: {e}"))?
131                .into_iter()
132                .map(|d| ViewerDeviceInfo {
133                    viewing_stopped: viewer.viewing_stopped(&d.device_id),
134                    device_id: d.device_id,
135                    device_name: d.device_name,
136                    created_ms: d.created_ms,
137                    last_seen_ms: d.last_seen_ms,
138                    can_send: d.can_send,
139                    has_key: !d.device_key.is_empty(),
140                    device_kind: d.kind.as_str().to_string(),
141                })
142                .collect();
143            Ok(ViewerDevicesResult { devices })
144        }
145    });
146}
147
148/// Revoke a device: its token stops working on the next request, and every
149/// feed it has open is closed now.
150pub(crate) fn revoke_impl(state: &AppState, device_id: &str) -> Result<ViewerRevokeResult, String> {
151    let revoked = state.mstore.viewer_device_delete(device_id).map_err(|e| format!("viewer.revoke: {e}"))?;
152    if revoked {
153        state.broker.publish_event::<crate::backend::mps_events::ViewerDevicesChanged>(&(), vec![], 0);
154    }
155    let feeds_closed = state.viewer.close_device_feeds(device_id);
156    state.viewer.forget_device(device_id);
157    if revoked {
158        tracing::info!(%device_id, feeds_closed, "viewer: device revoked");
159    }
160    Ok(ViewerRevokeResult { revoked, feeds_closed })
161}
162
163fn register_revoke(engine: &Arc<WshRpcEngine>, state: &AppState) {
164    let state = state.clone();
165    engine.register_typed(COMMAND_VIEWER_REVOKE, move |cmd: CommandViewerRevokeData, _ctx| {
166        let state = state.clone();
167        async move { revoke_impl(&state, &cmd.device_id) }
168    });
169}
170
171fn register_agent_hidden(engine: &Arc<WshRpcEngine>, state: &AppState) {
172    let state = state.clone();
173    engine.register_typed(COMMAND_VIEWER_AGENT_HIDDEN, move |cmd: CommandViewerAgentHiddenData, _ctx| {
174        let (mstore, broker) = (state.mstore.clone(), state.broker.clone());
175        async move {
176            if let Some(hidden) = cmd.hidden {
177                let found = mstore
178                    .agent_hide_from_devices_set(&cmd.agent_id, hidden)
179                    .map_err(|e| format!("viewer.agent-hidden: {e}"))?;
180                if !found {
181                    return Err(format!("viewer.agent-hidden: no agent {}", cmd.agent_id));
182                }
183                broker.publish_event::<crate::backend::mps_events::AgentHiddenChanged>(&(), vec![], 0);
184            }
185            let hidden = mstore
186                .agent_hide_from_devices_get(&cmd.agent_id)
187                .map_err(|e| format!("viewer.agent-hidden: {e}"))?;
188            Ok(ViewerAgentHiddenResult { hidden })
189        }
190    });
191}
192
193/// Turn a device's send grant on or off. On needs a key on file: a device
194/// that paired without one can't sign, so it must pair again first.
195pub(crate) fn can_send_impl(state: &AppState, device_id: &str, can_send: bool) -> Result<ViewerCanSendResult, String> {
196    let device = state
197        .mstore
198        .viewer_device_get(device_id)
199        .map_err(|e| format!("viewer.can-send: {e}"))?
200        .ok_or_else(|| format!("viewer.can-send: no paired device {device_id}"))?;
201    if can_send && device.device_key.is_empty() {
202        return Err(format!(
203            "{} paired before devices had keys. Pair it again to let it send.",
204            device.device_name
205        ));
206    }
207    state
208        .mstore
209        .viewer_device_set_can_send(device_id, can_send)
210        .map_err(|e| format!("viewer.can-send: {e}"))?;
211    state.broker.publish_event::<crate::backend::mps_events::ViewerDevicesChanged>(&(), vec![], 0);
212    tracing::info!(%device_id, can_send, "viewer: send grant changed");
213    Ok(ViewerCanSendResult { can_send })
214}
215
216fn register_can_send(engine: &Arc<WshRpcEngine>, state: &AppState) {
217    let state = state.clone();
218    engine.register_typed(COMMAND_VIEWER_CAN_SEND, move |cmd: CommandViewerCanSendData, _ctx| {
219        let state = state.clone();
220        async move { can_send_impl(&state, &cmd.device_id, cmd.can_send) }
221    });
222}