Skip to main content

agentmux_srv/server/
http_viewer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The viewer routes a paired device calls, served only on the viewer
5//! listener (TLS, `backend::lan::listeners`), never on the loopback or LAN
6//! routers (agentmux-mobile's SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07
7//! §13.2, §13.3):
8//!
9//! - `POST /agentmux/viewer/pair`: a pairing code for a viewer token. The
10//!   only route without a token.
11//! - `GET /agentmux/viewer/hello`, `GET /agentmux/viewer/agents`,
12//!   `GET /agentmux/viewer/agents/:name/feed`, `…/history`
13//!   (`server::http_viewer_history`), `…/attachments/:id`
14//!   (`server::http_viewer_attachments`), `GET /agentmux/viewer/panes`,
15//!   `GET /agentmux/viewer/terminals/:block_id/feed`
16//!   (`server::http_viewer_terminal`), `GET /agentmux/viewer/procs`, and
17//!   `GET /agentmux/viewer/sysinfo` and `…/sysinfo/feed`
18//!   (`server::http_viewer_sysinfo`):
19//!   `Authorization: Bearer amxv_…` only. Neither the `lan_key` nor the instance `auth_key` opens
20//!   them, and the token opens nothing else: no other router knows it.
21//!
22//! - `POST /agentmux/viewer/agents/:name/input` (`server::http_viewer_input`):
23//!   a message to an agent, as the user, from a device the owner allowed to
24//!   send, signed by the device's key.
25//!
26//! Read-only otherwise. An agent hidden from paired devices is left out of
27//! the list and its feed and input are 404; agents of other channels on this
28//! machine are 404 too for now (they are not in this channel's registry).
29
30use std::convert::Infallible;
31use std::net::SocketAddr;
32use std::time::Duration;
33
34use axum::body::Bytes;
35use axum::extract::{ConnectInfo, Path, Query};
36use futures_util::Stream;
37use serde::Deserialize;
38
39use super::*;
40use crate::backend::blockcontroller::PendingFacts;
41use crate::backend::rpc_types::CommandBlockfileReadRangeData;
42use crate::backend::storage::viewer_devices::DeviceKind;
43use crate::backend::viewer::feed::{self, AppendStep, Cursor, HubEvent};
44use crate::backend::viewer::audit::{self, Proof, ViewerActor};
45use crate::backend::viewer::{pairing, signing, FeedLease, FeedRefused};
46
47/// Heartbeat comment on a quiet feed.
48pub(crate) const FEED_HEARTBEAT: Duration = Duration::from_secs(15);
49/// How often a feed looks at its agent's state. One controller lookup and one
50/// block read, so a second is cheap and keeps the device's chip current.
51pub(crate) const STATUS_POLL: Duration = Duration::from_secs(1);
52/// How often a feed checks that its agent hasn't moved to another block, and
53/// reads lines of the agent's shared transcript that no event of this block
54/// brought (another block, or another srv instance, running the same agent).
55/// The desktop pane polls the shared transcript as often
56/// (`useAgentStream.ts`, `SHARED_ZONE_POLL_MS`).
57pub(crate) const FOLLOW_POLL: Duration = Duration::from_secs(5);
58/// The snapshot: the last 50 turns or 256 KB, whichever is smaller.
59const SNAPSHOT_TAIL_TURNS: u32 = 50;
60const SNAPSHOT_TAIL_BYTES: u64 = 256 * 1024;
61/// The most lines one bounded read returns (`blockfile:read_range`'s cap).
62const READ_LIMIT: u64 = 10_000;
63pub(crate) const RETRY_PREAMBLE: &[u8] = b"retry: 3000\n\n";
64pub(crate) const HEARTBEAT: &[u8] = b": hb\n\n";
65
66/// The paired device a request authenticated as.
67#[derive(Debug, Clone)]
68pub(crate) struct ViewerCaller {
69    pub device_id: String,
70}
71
72/// The viewer router: pairing, plus the token-gated read-only routes.
73pub fn build_viewer_router(state: AppState) -> Router {
74    let authed = Router::new()
75        .route("/agentmux/viewer/hello", get(handle_viewer_hello))
76        .route("/agentmux/viewer/agents", get(handle_viewer_agents))
77        .route("/agentmux/viewer/agents/:name/feed", get(handle_viewer_feed))
78        .route("/agentmux/viewer/agents/:name/history", get(super::http_viewer_history::handle_viewer_history))
79        .route(
80            "/agentmux/viewer/agents/:name/attachments/:id",
81            get(super::http_viewer_attachments::handle_viewer_attachment),
82        )
83        .route(
84            "/agentmux/viewer/agents/:name/input",
85            post(super::http_viewer_input::handle_viewer_input)
86                .layer(axum::extract::DefaultBodyLimit::max(super::http_viewer_input::MAX_INPUT_BODY)),
87        )
88        .route("/agentmux/viewer/procs", get(handle_viewer_procs))
89        .route("/agentmux/viewer/panes", get(handle_viewer_panes))
90        .route("/agentmux/viewer/sysinfo", get(super::http_viewer_sysinfo::handle_viewer_sysinfo))
91        .route("/agentmux/viewer/sysinfo/feed", get(super::http_viewer_sysinfo::handle_viewer_sysinfo_feed))
92        .route(
93            "/agentmux/viewer/terminals/:block_id/feed",
94            get(super::http_viewer_terminal::handle_viewer_terminal_feed),
95        )
96        .route_layer(middleware::from_fn_with_state(state.clone(), viewer_auth_middleware));
97    Router::new()
98        .route("/agentmux/viewer/pair", post(handle_viewer_pair))
99        .merge(authed)
100        .with_state(state)
101}
102
103/// Admit a request carrying a paired device's viewer token: its SHA-256 is
104/// compared, in constant time, with every paired device's. Stamps the
105/// device's `last_seen_ms` at most once a minute.
106async fn viewer_auth_middleware(State(state): State<AppState>, mut req: Request<Body>, next: Next) -> Response {
107    let token = req
108        .headers()
109        .get(header::AUTHORIZATION)
110        .and_then(|v| v.to_str().ok())
111        .and_then(|v| v.strip_prefix("Bearer "))
112        .map(str::trim)
113        .filter(|t| t.starts_with(pairing::TOKEN_PREFIX));
114    let Some(token) = token else {
115        return unauthorized();
116    };
117    let hash = pairing::token_hash(token);
118    let devices = match state.mstore.viewer_device_token_hashes() {
119        Ok(d) => d,
120        Err(e) => {
121            tracing::warn!(error = %e, "viewer: could not read paired devices");
122            return unauthorized();
123        }
124    };
125    let mut device_id = None;
126    for (id, stored) in devices {
127        if secret_eq(stored.as_bytes(), hash.as_bytes()) {
128            device_id = Some(id);
129        }
130    }
131    let Some(device_id) = device_id else {
132        return unauthorized();
133    };
134    if let Some(refused) = super::http_viewer_computers::admit(&state, &device_id, req.uri().path()) {
135        return refused;
136    }
137    // Stopped by the host's person (`viewer.stop-watching`): nothing but `hello` until allowed again, so a device
138    // can't read history, an attachment or the list, or send, with what it had before the stop.
139    if state.viewer.viewing_stopped(&device_id) && req.uri().path() != "/agentmux/viewer/hello" {
140        return feed_refused(FeedRefused::Stopped);
141    }
142    let now = agentmux_common::time::now_ms();
143    if state.viewer.last_seen_due(&device_id, now) {
144        if let Err(e) = state.mstore.viewer_device_touch(&device_id, now) {
145            tracing::debug!(error = %e, "viewer: could not stamp last_seen");
146        }
147    }
148    req.extensions_mut().insert(ViewerCaller { device_id });
149    next.run(req).await
150}
151
152#[derive(Deserialize)]
153pub(crate) struct PairBody {
154    code: String,
155    device_name: String,
156    #[serde(default)]
157    device_key: Option<String>,
158    /// `phone` (the default) or `computer`.
159    #[serde(default)]
160    device_kind: Option<String>,
161}
162
163fn bad_request(msg: &str) -> Response {
164    (StatusCode::BAD_REQUEST, Json(json!({ "error": msg }))).into_response()
165}
166
167/// `POST /agentmux/viewer/pair`: `{code, device_name, device_key?}` for
168/// `{token, device_id, hostname, channel, version, install_id?}`; 401 for an
169/// unknown or expired code, 429 after too many wrong ones.
170async fn handle_viewer_pair(
171    State(state): State<AppState>,
172    peer: Option<Extension<ConnectInfo<SocketAddr>>>,
173    body: Result<Json<PairBody>, axum::extract::rejection::JsonRejection>,
174) -> Response {
175    let Ok(Json(body)) = body else {
176        return bad_request("expected {code, device_name, device_key?}");
177    };
178    let device_name = body.device_name.trim().to_string();
179    let name_len = device_name.chars().count();
180    if !(1..=64).contains(&name_len) || device_name.chars().any(char::is_control) {
181        return bad_request("device_name must be 1 to 64 characters");
182    }
183    // The key the device signs send requests with (`viewer::signing`).
184    let device_key = match body.device_key.as_deref().map(str::trim).filter(|k| !k.is_empty()) {
185        None => String::new(),
186        Some(key) => match signing::DeviceKey::parse(key) {
187            Ok(_) => key.to_string(),
188            Err(msg) => return bad_request(msg),
189        },
190    };
191    let kind = match body.device_kind.as_deref().map(str::trim).filter(|k| !k.is_empty()) {
192        None => DeviceKind::Phone,
193        Some(k) => match DeviceKind::parse(k) {
194            Some(kind) => kind,
195            None => return bad_request("device_kind must be phone or computer"),
196        },
197    };
198    // Before the code is spent: a computer that isn't let in keeps the code for when its person allows it.
199    if !super::http_viewer_computers::kind_admitted(&state, kind) {
200        return super::http_viewer_computers::refused();
201    }
202    let from = peer.map(|Extension(ConnectInfo(addr))| addr.ip());
203    // A wrong code is recorded only while a code is shown: then someone answered the person's pairing wrongly. The
204    // shown code is cancelled after a few wrong ones, so a peer looping on this route can't fill the Audit.
205    let showing = state.viewer.pairing.showing();
206    let redeemed = state.viewer.pairing.redeem(&body.code, from);
207    if showing && redeemed == pairing::Redeem::Refused {
208        audit::wrong_pairing_code(&device_name, kind);
209    }
210    match redeemed {
211        pairing::Redeem::Accepted => {}
212        pairing::Redeem::Refused => return unauthorized(),
213        pairing::Redeem::RateLimited => {
214            return (StatusCode::TOO_MANY_REQUESTS, Json(json!({ "error": "too many wrong codes; wait a minute" })))
215                .into_response()
216        }
217    }
218    let token = pairing::new_token();
219    let device_id = uuid::Uuid::new_v4().to_string();
220    let now = agentmux_common::time::now_ms();
221    if let Err(e) =
222        state.mstore.viewer_device_insert_kind(&device_id, &pairing::token_hash(&token), &device_name, &device_key, now, kind)
223    {
224        tracing::warn!(error = %e, "viewer: could not record a paired device");
225        return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": "could not record the device" })))
226            .into_response();
227    }
228    tracing::info!(%device_id, %device_name, kind = kind.as_str(), "viewer: device paired");
229    let actor = ViewerActor { device_id: device_id.clone(), name: device_name.clone(), kind, user: None };
230    audit::record(&actor, "pair", "", Proof::Code, None, None);
231    // The desktop shows a toast and closes the QR (frontend `viewer:paired`).
232    let paired = crate::backend::mps_events::ViewerPairedEvent { device_id: device_id.to_string(), device_name: device_name.to_string() };
233    state.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::ViewerPaired>(&paired, String::new()));
234    let mut out = json!({
235        "token": token,
236        "device_id": device_id,
237        "hostname": state.hostname,
238        "channel": crate::backend::reactive::registry::local_channel_id(),
239        "version": state.version,
240    });
241    if let Some(id) = crate::backend::fleet_source::install_id() {
242        out["install_id"] = json!(id);
243    }
244    Json(out).into_response()
245}
246
247/// Whether a device may send to agents: `allowed` (the owner's grant and a
248/// key on file), `off` (no grant), or `pair_again` (a grant, but the device
249/// paired without a key, so it can't sign). agentmux-mobile's
250/// SPEC_SEND_FROM_THE_PHONE_2026_10_13 §4.
251pub(crate) fn send_state(device: &crate::backend::storage::viewer_devices::ViewerDevice) -> &'static str {
252    match (device.can_send, device.device_key.is_empty()) {
253        (false, _) => "off",
254        (true, true) => "pair_again",
255        (true, false) => "allowed",
256    }
257}
258
259/// `GET /agentmux/viewer/hello`: who this is, which device is asking, and
260/// whether it may send.
261async fn handle_viewer_hello(State(state): State<AppState>, Extension(caller): Extension<ViewerCaller>) -> Response {
262    let send = match state.mstore.viewer_device_get(&caller.device_id) {
263        Ok(Some(device)) => send_state(&device),
264        _ => "off",
265    };
266    let mut out = json!({
267        "hostname": state.hostname,
268        "channel": crate::backend::reactive::registry::local_channel_id(),
269        "version": state.version,
270        "device_id": caller.device_id,
271        "send": send,
272        "remote_panes": super::http_viewer_computers::REMOTE_PANES_VERSION,
273    });
274    if let Some(id) = crate::backend::fleet_source::install_id() {
275        out["install_id"] = json!(id);
276    }
277    Json(out).into_response()
278}
279
280/// Whether the agent in `block_id` is hidden from paired devices: its
281/// definition (the block's `agentId`) has `hide_from_devices` set. A store
282/// that can't answer hides it: a device never sees, or sends to, an agent
283/// because a read failed.
284pub(crate) fn agent_hidden(state: &AppState, block_id: &str) -> bool {
285    let block = match state.mstore.get::<crate::backend::obj::Block>(block_id) {
286        Ok(Some(block)) => block,
287        Ok(None) => return false,
288        Err(_) => return true,
289    };
290    let def_id = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
291    !def_id.is_empty() && state.mstore.agent_hide_from_devices_get(&def_id).unwrap_or(true)
292}
293
294/// Who the agent registered as `name` is, for the top of a device's pane
295/// (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md §2): `{name, color?, seat?}`, its name as registered, the colour its own pane is drawn in (`ui:color`), and its seat
296/// as the LAN shares it with peers (`agent_seat::summarize`). Nothing else of its definition.
297pub(crate) fn identity_of(state: &AppState, name: &str) -> serde_json::Value {
298    let registration = state.reactive_handler.get_agent(name);
299    let mut agent = json!({ "name": registration.as_ref().map_or(name, |a| a.agent_id.as_str()) });
300    // Its definition, as `agent_hidden` finds it: the block's `agentId`, else the registration's.
301    let of_block = |block_id: &str| {
302        let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
303        Some(crate::backend::obj::meta_get_string(&block.meta, "agentId", ""))
304    };
305    let uid = registration.and_then(|a| of_block(&a.block_id).filter(|id| !id.is_empty()).or(a.uid));
306    let Some(uid) = uid.filter(|u| !u.is_empty()) else {
307        return agent;
308    };
309    let color = state.mstore.agent_content_get(&uid, "ui:color").ok().flatten().map(|c| c.content.trim().to_string());
310    if let Some(color) = color.filter(|c| crate::backend::agent_color::is_valid_agent_color(c)) {
311        agent["color"] = json!(color);
312    }
313    if let Some(seat) = crate::backend::agent_seat::effective_seat_by_id(&state.mstore, &uid) {
314        let name_of = |id: &str| state.mstore.agent_def_get(id).ok().flatten().map(|d| d.name);
315        agent["seat"] = json!(crate::backend::agent_seat::summarize(&seat, name_of));
316    }
317    agent
318}
319
320/// The agent's provider id (`claude`, `codex`, …), '' when unknown.
321fn provider_of(state: &AppState, block_id: &str) -> String {
322    let Ok(Some(block)) = state.mstore.get::<crate::backend::obj::Block>(block_id) else {
323        return String::new();
324    };
325    let raw = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "");
326    match crate::backend::providers::resolve_provider_alias(&raw) {
327        "" => raw,
328        id => id.to_string(),
329    }
330}
331
332/// `GET /agentmux/viewer/agents`: this channel's agents, hidden ones left
333/// out, sorted case-insensitively.
334async fn handle_viewer_agents(State(state): State<AppState>) -> Response {
335    let mut agents: Vec<(String, String)> = state
336        .reactive_handler
337        .list_agents()
338        .into_iter()
339        .filter(|a| !agent_hidden(&state, &a.block_id))
340        .map(|a| (a.agent_id, a.block_id))
341        .collect();
342    agents.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()).then(a.0.cmp(&b.0)));
343    agents.dedup_by(|later, earlier| later.0.eq_ignore_ascii_case(&earlier.0));
344    let list: Vec<serde_json::Value> = agents
345        .into_iter()
346        .map(|(name, block_id)| {
347            let mut agent = json!({ "name": name });
348            if let Some(kind) = crate::backend::operator_config_seed::agent_kind_of_block(&state.mstore, &block_id) {
349                agent["kind"] = json!(kind);
350            }
351            // The state the LAN feed reports, from the same tracker, so both
352            // give the same `since_ms`. An agent with no known state has neither.
353            if let Some(status) = crate::backend::agent_state::agent_status_of_block(&state.mstore, &block_id) {
354                agent["state"] = json!(status.state);
355                agent["since_ms"] = json!(status.since_ms);
356            }
357            agent
358        })
359        .collect();
360    // Read after the states, so no `since_ms` is later than it.
361    Json(json!({ "now_ms": agentmux_common::time::now_ms_u64(), "agents": list })).into_response()
362}
363
364/// Settings key: let paired devices see this computer's processes in their
365/// Tower (`GET /agentmux/viewer/procs`). Off unless set.
366pub(crate) const SETTING_TOWER_SHARE: &str = "tower:sharewithpaired";
367
368#[derive(Deserialize)]
369pub(crate) struct ProcsQuery {
370    #[serde(default)]
371    filter: String,
372}
373
374/// `GET /agentmux/viewer/procs?filter=`: this computer's Tower snapshot for a
375/// paired device (SPEC_TOWER_TASK_MANAGER_PANE_2026_10_08.md §8.3): its
376/// tasks and the busiest and largest of its processes, names only, never a
377/// command line. 403 unless the user turned sharing on; an agent hidden from
378/// paired devices, and its processes, are left out.
379async fn handle_viewer_procs(State(state): State<AppState>, Query(q): Query<ProcsQuery>) -> Response {
380    let sharing = state
381        .config_watcher
382        .get_settings()
383        .extra
384        .get(SETTING_TOWER_SHARE)
385        .and_then(|v| v.as_bool())
386        .unwrap_or(false);
387    if !sharing {
388        return (StatusCode::FORBIDDEN, Json(json!({ "error": "this computer doesn't share its processes" })))
389            .into_response();
390    }
391    let st = state.clone();
392    let snap = tokio::task::spawn_blocking(move || {
393        let mut snap = crate::backend::tower::sampler::Tower::global().sample(
394            true,
395            &st.hostname,
396            || crate::server::app_api::tower_pane::inputs(&st.process_tracker),
397            |id| crate::backend::tower::sampler::block_label(&st.mstore, id),
398            // What each renderer serves names this computer's windows and
399            // pages; a paired viewer sees only that it is a renderer.
400            |_| None,
401        )?;
402        crate::backend::tower::sampler::share(&mut snap, crate::backend::tower::sampler::SHARED_TOP, &q.filter, &|id| {
403            agent_hidden(&st, id)
404        });
405        Ok::<_, std::io::Error>(snap)
406    })
407    .await;
408    match snap {
409        Ok(Ok(snap)) => Json(snap).into_response(),
410        Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
411        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
412    }
413}
414
415/// `GET /agentmux/viewer/panes`: every pane on this computer, window by window
416/// and tab by tab, with each agent's shell drawer (`backend::viewer::panes`):
417/// names, types, the agent name a feed opens by, and whether a terminal runs.
418/// No content, command line or working directory; agents hidden from paired
419/// devices, and their shells, are left out.
420async fn handle_viewer_panes(State(state): State<AppState>) -> Response {
421    let st = state.clone();
422    let panes = tokio::task::spawn_blocking(move || {
423        use crate::backend::obj::{Block, Tab, Window, Workspace};
424        // A table that can't be read fails the request: an empty or partial
425        // list would read as "nothing open".
426        let windows = st.mstore.get_all::<Window>().map_err(|e| e.to_string())?;
427        let workspaces = st.mstore.get_all::<Workspace>().map_err(|e| e.to_string())?;
428        let tabs = st.mstore.get_all::<Tab>().map_err(|e| e.to_string())?;
429        let blocks = st.mstore.get_all::<Block>().map_err(|e| e.to_string())?;
430        let label = |b: &Block| {
431            crate::backend::tower::sampler::block_label(&st.mstore, &b.oid)
432                .map(|l| (l.label, l.agent))
433                .unwrap_or_default()
434        };
435        let agent_name = |id: &str| st.reactive_handler.get_agent_by_block(id).map(|a| a.agent_id.clone());
436        let running = |id: &str| {
437            crate::backend::blockcontroller::get_block_controller_status(id)
438                .map(|s| s.shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING)
439        };
440        let hidden = |id: &str| agent_hidden(&st, id);
441        let facts = crate::backend::viewer::panes::PaneFacts {
442            label: &label,
443            agent_name: &agent_name,
444            running: &running,
445            hidden: &hidden,
446        };
447        Ok::<_, String>(crate::backend::viewer::panes::list(&windows, &workspaces, &tabs, &blocks, &facts))
448    })
449    .await
450    .map_err(|e| e.to_string())
451    .and_then(|r| r);
452    match panes {
453        Ok(panes) => Json(json!({
454            "now_ms": agentmux_common::time::now_ms_u64(),
455            "terminals_shared": super::http_viewer_terminal::terminals_shared(&state),
456            "panes": panes,
457        }))
458        .into_response(),
459        Err(error) => {
460            tracing::warn!(%error, "viewer: could not list panes");
461            (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": "could not list panes" }))).into_response()
462        }
463    }
464}
465
466/// `GET /agentmux/viewer/agents/:name/feed`: the agent's transcript as
467/// Server-Sent Events (see [`feed_stream`]). 404 for an agent that isn't
468/// this channel's or is hidden; 503 past the feed caps.
469async fn handle_viewer_feed(
470    State(state): State<AppState>,
471    Extension(caller): Extension<ViewerCaller>,
472    Path(name): Path<String>,
473    uri: axum::http::Uri,
474    headers: axum::http::HeaderMap,
475) -> Response {
476    let Some(agent) = state.reactive_handler.get_agent(&name) else {
477        return not_found();
478    };
479    if agent_hidden(&state, &agent.block_id) {
480        return not_found();
481    }
482    if let Some(refused) = super::http_viewer_computers::refuse_unsigned_open(&state, &caller.device_id, uri.path(), &headers) {
483        return refused;
484    }
485    let lease = match state.viewer.open_feed(&caller.device_id, Some(&agent.agent_id)) {
486        Ok(lease) => audited_feed(&state, &caller.device_id, &agent.agent_id, lease),
487        Err(refused) => return feed_refused(refused),
488    };
489    let last_event_id = headers.get("last-event-id").and_then(|v| v.to_str().ok()).map(str::to_string);
490    let provider = provider_of(&state, &agent.block_id);
491    tracing::info!(
492        device = %caller.device_id,
493        agent = %name,
494        block = %agent.block_id,
495        resume = last_event_id.is_some(),
496        "viewer feed: opened"
497    );
498    let stream = feed_stream(
499        FeedSource::of(&state, &agent.block_id),
500        provider,
501        last_event_id,
502        lease,
503        FeedTiming::default(),
504        AgentProbe::of(&state, &name).for_device(&state, &caller.device_id),
505    );
506    (
507        [(header::CONTENT_TYPE, "text/event-stream"), (header::CACHE_CONTROL, "no-cache")],
508        Body::from_stream(stream),
509    )
510        .into_response()
511}
512
513/// The answer to a feed open that got no lease: 503 past the caps, 403 `stopped_by_host` when the host's person
514/// stopped this device's viewing.
515pub(crate) fn feed_refused(refused: FeedRefused) -> Response {
516    let (status, body) = match refused {
517        FeedRefused::PerDevice => (StatusCode::SERVICE_UNAVAILABLE, json!({ "error": "too many open feeds for this device" })),
518        FeedRefused::Total => (StatusCode::SERVICE_UNAVAILABLE, json!({ "error": "too many open feeds" })),
519        FeedRefused::Stopped => (
520            StatusCode::FORBIDDEN,
521            json!({ "error": "this computer's person stopped your viewing", "reason": "stopped_by_host" }),
522        ),
523    };
524    (status, Json(body)).into_response()
525}
526
527/// `lease`, with the feed's Audit rows: opened now, closed when the lease drops. `what` names what it shows (the
528/// agent, or a terminal). A computer's feed open is signed (`http_viewer_computers::refuse_unsigned_open`); a
529/// phone's carries its token.
530pub(crate) fn audited_feed(state: &AppState, device_id: &str, what: &str, lease: FeedLease) -> FeedLease {
531    match state.mstore.viewer_device_get(device_id) {
532        Ok(Some(device)) => {
533            let proof = if device.kind == DeviceKind::Computer { Proof::Signed } else { Proof::Token };
534            audit::feed_opened(ViewerActor::of(&device, None), what, proof, lease)
535        }
536        _ => lease,
537    }
538}
539
540pub(super) fn not_found() -> Response {
541    (StatusCode::NOT_FOUND, Json(json!({ "error": "no such agent" }))).into_response()
542}
543
544/// A feed's clocks.
545#[derive(Debug, Clone, Copy)]
546pub(crate) struct FeedTiming {
547    pub heartbeat: Duration,
548    pub status_poll: Duration,
549    pub follow_poll: Duration,
550}
551
552impl Default for FeedTiming {
553    fn default() -> Self {
554        Self { heartbeat: FEED_HEARTBEAT, status_poll: STATUS_POLL, follow_poll: FOLLOW_POLL }
555    }
556}
557
558/// The state of the agent in a block, if it has one.
559type StatusProbe = Box<dyn Fn(&str) -> Option<crate::backend::agent_state::AgentStatus> + Send>;
560
561/// What a feed asks about its agent while it runs: the block it runs in now,
562/// whether it has been hidden from paired devices, its state, and the
563/// provider of a block it moves to, who it is for each snapshot, and what
564/// waits in it (its controller's `pending_for_devices`).
565pub(crate) struct AgentProbe {
566    pub block: Box<dyn Fn() -> Option<String> + Send>,
567    pub hidden: Box<dyn Fn(&str) -> bool + Send>,
568    pub status: StatusProbe,
569    pub provider: Box<dyn Fn(&str) -> String + Send>,
570    pub identity: Box<dyn Fn() -> serde_json::Value + Send>,
571    pub pending: Box<dyn Fn(&str) -> PendingFacts + Send>,
572}
573
574impl AgentProbe {
575    /// The agent registered as `name`: its block from the registry (it moves
576    /// on a respawn), hidden per its definition, its state from the tracker
577    /// the LAN feed uses (`agent_state::agent_status_of_block`), the
578    /// provider per the block's meta, and who it is per [`identity_of`].
579    pub(crate) fn of(state: &AppState, name: &str) -> Self {
580        let (registry, name) = (state.reactive_handler, name.to_string());
581        let hidden_state = state.clone();
582        let provider_state = state.clone();
583        let (identity_state, identity_name) = (state.clone(), name.clone());
584        let mstore = state.mstore.clone();
585        Self {
586            block: Box::new(move || registry.get_agent(&name).map(|a| a.block_id.clone())),
587            hidden: Box::new(move |block_id| agent_hidden(&hidden_state, block_id)),
588            status: Box::new(move |block_id| crate::backend::agent_state::agent_status_of_block(&mstore, block_id)),
589            provider: Box::new(move |block_id| provider_of(&provider_state, block_id)),
590            identity: Box::new(move || identity_of(&identity_state, &identity_name)),
591            pending: Box::new(|block_id| {
592                crate::backend::blockcontroller::get_controller(block_id).map(|c| c.pending_for_devices()).unwrap_or_default()
593            }),
594        }
595    }
596
597    /// The same probe for `device_id`'s feed: the agent also counts as hidden once the device is no longer let in
598    /// (a computer, after its host's person stopped allowing computers), so the feed ends at its next event or
599    /// heartbeat, as it does when the agent is hidden.
600    pub(crate) fn for_device(mut self, state: &AppState, device_id: &str) -> Self {
601        let (state, device_id, hidden) = (state.clone(), device_id.to_string(), self.hidden);
602        self.hidden = Box::new(move |block_id| {
603            hidden(block_id) || !super::http_viewer_computers::device_admitted(&state, &device_id)
604        });
605        self
606    }
607}
608
609/// Where a feed reads its agent's transcript from.
610pub(crate) struct FeedSource {
611    broker: Arc<Broker>,
612    filestore: Arc<FileStore>,
613    global_store: Option<Arc<FileStore>>,
614    mstore: Arc<Store>,
615    hub: Arc<crate::backend::viewer::feed::FeedHub>,
616    block_id: String,
617}
618
619/// A snapshot as read: where the feed stands after it, and its lines from
620/// `from_line`.
621struct Snapshot {
622    cursor: Cursor,
623    from_line: u64,
624    lines: Vec<String>,
625}
626
627impl FeedSource {
628    pub(crate) fn of(state: &AppState, block_id: &str) -> Self {
629        Self {
630            broker: state.broker.clone(),
631            filestore: state.filestore.clone(),
632            global_store: state.global_transcript_store.clone(),
633            mstore: state.mstore.clone(),
634            hub: state.viewer.hub.clone(),
635            block_id: block_id.to_string(),
636        }
637    }
638
639    /// Up to `limit` lines from `offset` (the newest of them as a snapshot, with `tail`), as a device may be shown
640    /// them; `None` when the transcript is another generation than `expect_gen` now, or can't be read.
641    pub(super) async fn read(
642        &self,
643        offset: u64,
644        limit: u64,
645        expect_gen: &str,
646        tail: bool,
647    ) -> Option<crate::backend::rpc_types::BlockfileReadRangeResult> {
648        let cmd = CommandBlockfileReadRangeData {
649            block_id: self.block_id.clone(),
650            filename: crate::backend::agent_session::OUTPUT_FILE.to_string(),
651            offset,
652            limit,
653            expect_gen: Some(expect_gen.to_string()),
654            tail_turns: tail.then_some(SNAPSHOT_TAIL_TURNS),
655            tail_bytes: tail.then_some(SNAPSHOT_TAIL_BYTES),
656            archive_zone: None,
657        };
658        let mut result = super::app_api::blockfile::read_range(
659            self.broker.clone(),
660            self.filestore.clone(),
661            self.global_store.clone(),
662            self.mstore.clone(),
663            cmd,
664        )
665        .await
666        .ok()?;
667        // What srv holds secret is not shown to a device, in a line written before it was withheld too.
668        crate::backend::transcript::withhold::in_place(&mut result.lines);
669        crate::backend::viewer::filter::for_viewer(&mut result.lines);
670        (result.gen_mismatch != Some(true)).then_some(result)
671    }
672
673    /// `lines` of this feed's transcript as a device may be shown them: an
674    /// `amx` only as srv signed it (`origin_sig`), nothing srv holds secret
675    /// (`transcript::withhold`), and none of what `viewer::filter` keeps from a
676    /// device (a memory re-delivery, a host path, inline bytes, a token).
677    fn vet(&self, lines: &mut [String]) {
678        let owner = crate::backend::transcript::origin_sig::owner_for_block(&self.mstore, &self.block_id);
679        crate::backend::transcript::attribution::vet_for_viewer(&self.mstore, &self.filestore, &owner, lines);
680        crate::backend::transcript::withhold::in_place(lines);
681        crate::backend::viewer::filter::for_viewer(lines);
682    }
683
684    pub(super) async fn position(&self) -> Option<(String, String, u64)> {
685        super::app_api::blockfile::transcript_position(&self.filestore, &self.global_store, &self.mstore, &self.block_id)
686            .await
687    }
688
689    /// The tail, through the bounded range read. Retried when the transcript
690    /// is replaced between the count and the read; `None` if it keeps moving
691    /// or can't be read.
692    async fn snapshot(&self) -> Option<Snapshot> {
693        for _ in 0..3 {
694            let Some((stream, gen, total)) = self.position().await else {
695                // No transcript yet: an empty snapshot; its first append
696                // starts the stream at line 0.
697                let cursor = Cursor { stream: format!("b:{}", self.block_id), gen: String::new(), next_line: 0 };
698                return Some(Snapshot { cursor, from_line: 0, lines: Vec::new() });
699            };
700            let offset = total.saturating_sub(READ_LIMIT);
701            let Some(result) = self.read(offset, READ_LIMIT, &gen, true).await else { continue };
702            let from_line = result.offset.unwrap_or(offset);
703            let next_line = from_line + result.lines.len() as u64;
704            let cursor = Cursor { stream: result.stream.unwrap_or(stream), gen, next_line };
705            return Some(Snapshot { cursor, from_line, lines: result.lines });
706        }
707        None
708    }
709
710    /// The lines from `line` on, for a reconnect that sent `gen:line`: `None`
711    /// when the transcript has another generation now, or more has been
712    /// written since than a stream may fall behind by (a snapshot then).
713    async fn resume(&self, gen: &str, line: u64) -> Option<(Cursor, Vec<String>)> {
714        let (stream, current, total) = self.position().await?;
715        if current != gen || line > total || total - line > READ_LIMIT {
716            return None;
717        }
718        let result = self.read(line, READ_LIMIT, gen, false).await?;
719        let bytes: usize = result.lines.iter().map(|l| feed::wire_size(l.as_bytes())).sum();
720        if bytes > feed::MAX_BEHIND_BYTES {
721            return None;
722        }
723        let cursor = Cursor { stream: result.stream.unwrap_or(stream), gen: gen.to_string(), next_line: line + result.lines.len() as u64 };
724        Some((cursor, result.lines))
725    }
726
727    /// Lines of the agent's shared transcript past `cursor` that no event of
728    /// this block brought: another block, or another srv instance, running
729    /// the same agent wrote them, or this block's append didn't say where it
730    /// landed in the shared stream. Moves the cursor past what it returns.
731    /// Lines an event brings later are then skipped by line number
732    /// ([`feed::apply_append`]), so nothing is sent twice.
733    ///
734    /// A cursor on the block's own transcript is left to its events, unless
735    /// the transcript is now read from another stream: the agent's shared
736    /// transcript started after the snapshot (another srv instance may have
737    /// begun it, and its appends reach no event here).
738    async fn catch_up(&self, cursor: &mut Cursor) -> CatchUp {
739        let shared = cursor.stream.starts_with("g:");
740        let Some((stream, gen, total)) = self.position().await else {
741            return CatchUp::Nothing;
742        };
743        if stream != cursor.stream {
744            return CatchUp::Resync("stream");
745        }
746        if !shared {
747            return CatchUp::Nothing;
748        }
749        if gen != cursor.gen {
750            return CatchUp::Resync("gen");
751        }
752        if total <= cursor.next_line {
753            return CatchUp::Nothing;
754        }
755        if total - cursor.next_line > READ_LIMIT {
756            return CatchUp::Resync("behind");
757        }
758        // Replaced since the count: the next poll, or the event that
759        // announces it, resyncs.
760        let Some(result) = self.read(cursor.next_line, READ_LIMIT, &gen, false).await else {
761            return CatchUp::Nothing;
762        };
763        let bytes: usize = result.lines.iter().map(|l| feed::wire_size(l.as_bytes())).sum();
764        if bytes > feed::MAX_BEHIND_BYTES {
765            return CatchUp::Resync("behind");
766        }
767        if result.lines.is_empty() {
768            return CatchUp::Nothing;
769        }
770        let line = cursor.next_line;
771        cursor.next_line += result.lines.len() as u64;
772        CatchUp::Lines { line, lines: result.lines }
773    }
774}
775
776/// What [`FeedSource::catch_up`] found.
777enum CatchUp {
778    Nothing,
779    /// Lines that follow on from the cursor, starting at `line`.
780    Lines { line: u64, lines: Vec<String> },
781    /// The cursor can't continue (another stream or generation, or too far
782    /// behind): reset and send a fresh snapshot.
783    Resync(&'static str),
784}
785
786/// The snapshot event; `agent` is who the agent is ([`identity_of`]), so the first event a device gets says it.
787fn snapshot_event(snapshot: Snapshot, provider: &str, agent: serde_json::Value) -> Bytes {
788    let id = snapshot.cursor.event_id();
789    feed::sse_event(
790        "snapshot",
791        Some(&id),
792        &json!({
793            "provider": provider,
794            "agent": agent,
795            "gen": snapshot.cursor.gen,
796            "from_line": snapshot.from_line,
797            "next_line": snapshot.cursor.next_line,
798            "lines": feed::device_frames(snapshot.lines),
799        }),
800    )
801}
802
803fn append_event(cursor: &Cursor, line: u64, lines: Vec<String>) -> Bytes {
804    feed::sse_event(
805        "append",
806        Some(&cursor.event_id()),
807        &json!({ "gen": cursor.gen, "line": line, "lines": feed::device_frames(lines) }),
808    )
809}
810
811fn reset_event(reason: &str) -> Bytes {
812    feed::sse_event("reset", None, &json!({ "reason": reason }))
813}
814
815/// `status` `{state, since_ms, now_ms}`; `state` and `since_ms` are null when
816/// a state the device was shown has gone (it drops its chip).
817/// What a feed last told its device about the agent.
818#[derive(Default)]
819struct Shown {
820    status: Option<crate::backend::agent_state::AgentStatus>,
821    /// `None` until the first look.
822    pending: Option<PendingFacts>,
823}
824
825/// Whether to send what waits in the agent now: when it changed since it was last sent, and after a snapshot (which
826/// starts the device over) when anything waits. Nothing while nothing has waited yet.
827fn pending_step(shown: &mut Option<PendingFacts>, now: PendingFacts, after_snapshot: bool) -> Option<PendingFacts> {
828    let waits = now != PendingFacts::default();
829    let send = match shown.as_ref() {
830        Some(last) => *last != now || (after_snapshot && waits),
831        None => waits,
832    };
833    *shown = Some(now.clone());
834    send.then_some(now)
835}
836
837/// What waits in the agent, for a feed resumed from its `Last-Event-ID` (no snapshot): sent once even when nothing
838/// does, since the device may still show a request answered or a message sent while it was away; then
839/// [`pending_step`] sends it only when it changes.
840fn pending_on_resume(shown: &mut Option<PendingFacts>, now: PendingFacts) -> Bytes {
841    *shown = Some(now.clone());
842    feed::sse_event("pending", None, &now)
843}
844
845/// The events that tell the device what changed about the agent in `block_id`: its state (`status`,
846/// [`feed::status_step`]) and what waits in it (`pending`, [`pending_step`]): the request waiting for the user's
847/// answer by id and kind, and how many messages wait to be sent, never their text (§2).
848fn facts_events(shown: &mut Shown, probe: &AgentProbe, block_id: &str, after_snapshot: bool) -> Vec<Bytes> {
849    let mut out = Vec::new();
850    if let Some(status) = feed::status_step(&mut shown.status, (probe.status)(block_id), after_snapshot) {
851        out.push(status_event(status));
852    }
853    if let Some(pending) = pending_step(&mut shown.pending, (probe.pending)(block_id), after_snapshot) {
854        out.push(feed::sse_event("pending", None, &pending));
855    }
856    out
857}
858
859fn status_event(status: Option<crate::backend::agent_state::AgentStatus>) -> Bytes {
860    feed::sse_event(
861        "status",
862        None,
863        &json!({
864            "state": status.map(|s| s.state),
865            "since_ms": status.map(|s| s.since_ms),
866            "now_ms": agentmux_common::time::now_ms_u64(),
867        }),
868    )
869}
870
871/// One feed: `retry`, then a `snapshot` (or, for a reconnect whose
872/// `Last-Event-ID` still holds, the lines it missed as one `append`), then an
873/// `append` per published transcript append, `reset` + `snapshot` when the
874/// transcript is rewritten or the feed loses its place, and a heartbeat on a
875/// quiet stream. A `status` follows each `snapshot` and every change of the
876/// agent's state, and a `pending` every change of what waits in it ([`facts_events`]). Ends with `reset` when the device falls more than 1 MB
877/// behind, or the agent is hidden or, for a computer, its host's person stops allowing computers
878/// (`hidden` both: [`AgentProbe::for_device`]), and silently when the device is revoked
879/// (its lease's token) or goes away. The lease is held until the stream is
880/// dropped.
881///
882/// The feed follows the agent, not the block it opened on: every
883/// [`FOLLOW_POLL`] it asks the registry where the agent runs now and moves
884/// its subscription there, and reads lines of the agent's shared transcript
885/// that no event brought ([`FeedSource::catch_up`]).
886pub(crate) fn feed_stream(
887    source: FeedSource,
888    provider: String,
889    last_event_id: Option<String>,
890    lease: FeedLease,
891    timing: FeedTiming,
892    probe: AgentProbe,
893) -> impl Stream<Item = Result<Bytes, Infallible>> + Send + 'static {
894    async_stream::stream! {
895        let lease = lease;
896        let mut source = source;
897        let mut provider = provider;
898        // The state and what waits, as last sent to the device.
899        let mut shown = Shown::default();
900        // Subscribed before anything is read, so nothing published between
901        // the read and the first event is missed.
902        let mut sub = source.hub.subscribe(&source.block_id);
903        yield Ok(Bytes::from_static(RETRY_PREAMBLE));
904
905        let resumed = match last_event_id.as_deref().and_then(feed::parse_event_id) {
906            Some((gen, line)) => source.resume(&gen, line).await,
907            None => None,
908        };
909        let mut cursor = match resumed {
910            Some((cursor, lines)) => {
911                if !lines.is_empty() {
912                    let line = cursor.next_line - lines.len() as u64;
913                    yield Ok(append_event(&cursor, line, lines));
914                }
915                yield Ok(pending_on_resume(&mut shown.pending, (probe.pending)(&source.block_id)));
916                Some(cursor)
917            }
918            None => match source.snapshot().await {
919                Some(snapshot) => {
920                    let cursor = snapshot.cursor.clone();
921                    yield Ok(snapshot_event(snapshot, &provider, (probe.identity)()));
922                    for event in facts_events(&mut shown, &probe, &source.block_id, true) {
923                        yield Ok(event);
924                    }
925                    Some(cursor)
926                }
927                None => None,
928            },
929        };
930        if cursor.is_none() {
931            yield Ok(reset_event("unavailable"));
932        }
933
934        let mut tick = tokio::time::interval_at(tokio::time::Instant::now() + timing.heartbeat, timing.heartbeat);
935        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
936        let mut status_tick = tokio::time::interval_at(tokio::time::Instant::now() + timing.status_poll, timing.status_poll);
937        status_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
938        let mut follow_tick = tokio::time::interval_at(tokio::time::Instant::now() + timing.follow_poll, timing.follow_poll);
939        follow_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
940        while let Some(current) = cursor.as_mut() {
941            // What to do after this event: keep going, resync from a fresh
942            // snapshot after a `reset`, or stop.
943            let mut resync: Option<String> = None;
944            tokio::select! {
945                biased;
946                _ = lease.token.cancelled() => break,
947                event = sub.recv() => match event {
948                    None => break,
949                    Some(HubEvent::Behind) => {
950                        yield Ok(reset_event("behind"));
951                        break;
952                    }
953                    Some(HubEvent::Rewritten { fileop }) => resync = Some(fileop),
954                    Some(HubEvent::Append { pos, records, .. }) => match feed::apply_append(current, &pos, &records) {
955                        AppendStep::Send { line, mut lines } => {
956                            // Checked before anything new leaves: the agent may have been hidden, or the device
957                            // shut out, since the last tick.
958                            if (probe.hidden)(&source.block_id) {
959                                yield Ok(reset_event("hidden"));
960                                break;
961                            }
962                            source.vet(&mut lines);
963                            yield Ok(append_event(current, line, lines))
964                        }
965                        AppendStep::Skip => {
966                            if !pos.iter().any(|p| p.stream == current.stream) {
967                                // Not placed in the feed's stream; the follow
968                                // poll brings these lines if they reached it.
969                                tracing::debug!(block = %source.block_id, stream = %current.stream, "viewer feed: an append without a position in the feed's stream");
970                            }
971                        }
972                        AppendStep::Resync(reason) => resync = Some(reason.to_string()),
973                    },
974                },
975                _ = status_tick.tick() => {
976                    for event in facts_events(&mut shown, &probe, &source.block_id, false) {
977                        yield Ok(event);
978                    }
979                }
980                _ = follow_tick.tick() => {
981                    let moved = (probe.block)().filter(|b| *b != source.block_id);
982                    // Checked before anything is subscribed to or read: the
983                    // block followed to, or the shared transcript read below,
984                    // may belong to an agent hidden from paired devices.
985                    if (probe.hidden)(moved.as_deref().unwrap_or(&source.block_id)) {
986                        yield Ok(reset_event("hidden"));
987                        break;
988                    }
989                    if let Some(block) = moved {
990                        tracing::info!(from = %source.block_id, to = %block, "viewer feed: the agent moved to another block; following it");
991                        // Subscribed before the catch-up read below, as at
992                        // the start, so nothing published in between is missed.
993                        sub = source.hub.subscribe(&block);
994                        // Its snapshots are labelled with its own provider.
995                        provider = (probe.provider)(&block);
996                        source.block_id = block;
997                        if current.stream.starts_with("b:") {
998                            // The old block's own transcript: the new one is
999                            // another stream.
1000                            resync = Some("moved".to_string());
1001                        }
1002                    }
1003                    if resync.is_none() {
1004                        match source.catch_up(current).await {
1005                            CatchUp::Nothing => {}
1006                            CatchUp::Lines { line, lines } => yield Ok(append_event(current, line, lines)),
1007                            CatchUp::Resync(reason) => resync = Some(reason.to_string()),
1008                        }
1009                    }
1010                }
1011                _ = tick.tick() => {
1012                    if (probe.hidden)(&source.block_id) {
1013                        yield Ok(reset_event("hidden"));
1014                        break;
1015                    }
1016                    yield Ok(Bytes::from_static(HEARTBEAT));
1017                }
1018            }
1019            if let Some(reason) = resync {
1020                // A fresh snapshot is new content too: checked as an append is.
1021                if (probe.hidden)(&source.block_id) {
1022                    yield Ok(reset_event("hidden"));
1023                    break;
1024                }
1025                tracing::info!(block = %source.block_id, %reason, "viewer feed: reset; sending a fresh snapshot");
1026                yield Ok(reset_event(&reason));
1027                match source.snapshot().await {
1028                    Some(snapshot) => {
1029                        cursor = Some(snapshot.cursor.clone());
1030                        yield Ok(snapshot_event(snapshot, &provider, (probe.identity)()));
1031                        for event in facts_events(&mut shown, &probe, &source.block_id, true) {
1032                            yield Ok(event);
1033                        }
1034                    }
1035                    None => {
1036                        yield Ok(reset_event("unavailable"));
1037                        break;
1038                    }
1039                }
1040            }
1041        }
1042    }
1043}
1044
1045#[cfg(test)]
1046#[path = "tests/viewer/viewer_tests.rs"]
1047pub(crate) mod tests;