Skip to main content

agentmux_srv/server/
http_viewer_terminal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /agentmux/viewer/terminals/:block_id/feed`: one terminal's output,
5//! live and read-only, for a paired device
6//! (`agentmux-mobile/docs/reports/REPORT_PANE_LIST_TERMINALS_AND_FROZEN_FEED_2026_10_12.md`
7//! §2.4, §2.5 phase B). Served beside the other viewer routes, on the viewer
8//! listener only, for the viewer token only.
9//!
10//! Off unless the user turns on "Share terminals with paired devices"
11//! (`viewer:shareterminals`): a terminal's scrollback routinely holds
12//! secrets, and terminals have no per-pane hide flag. The shell drawer of an
13//! agent hidden from paired devices is hidden with it. Nothing is ever sent
14//! to the terminal: no input, no resize. The device renders at the size the
15//! desktop gave the PTY (`size` events).
16//!
17//! Wire (SSE): `snapshot { offset, next_offset, data64, cols?, rows? }`, the
18//! last 256 KB of the terminal's output from a line start; `append { offset,
19//! data64 }` per write; `size { cols, rows }` when the PTY is resized;
20//! `reset { reason }` before a fresh snapshot, or before the stream ends
21//! (`behind`, `hidden`, `not_shared`); `: hb` every 15 s. Ids are the byte
22//! offset after the event; a reconnect whose `Last-Event-ID` is still within
23//! 256 KB of the end (a snapshot's worth) gets the bytes it missed as one
24//! `append`.
25
26use std::convert::Infallible;
27use std::time::Duration;
28
29use axum::body::Bytes;
30use axum::extract::Path;
31use base64::Engine as _;
32use futures_util::Stream;
33
34use super::http_viewer::{agent_hidden, ViewerCaller, FEED_HEARTBEAT, HEARTBEAT, RETRY_PREAMBLE, STATUS_POLL};
35use super::*;
36use crate::backend::viewer::feed::{self, HubEvent, TERM_FILE};
37use crate::backend::viewer::terminal::{self, TermStep};
38use crate::backend::viewer::FeedLease;
39
40/// Settings key: let paired devices watch this computer's terminals. Off
41/// unless set.
42pub(crate) const SETTING_SHARE_TERMINALS: &str = "viewer:shareterminals";
43
44/// Whether the user lets paired devices watch terminals.
45pub(crate) fn terminals_shared(state: &AppState) -> bool {
46    state
47        .config_watcher
48        .get_settings()
49        .extra
50        .get(SETTING_SHARE_TERMINALS)
51        .and_then(|v| v.as_bool())
52        .unwrap_or(false)
53}
54
55/// Why a block's terminal can't be watched.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub(crate) enum Unwatchable {
58    /// Gone, or not a terminal.
59    NotATerminal,
60    /// The shell drawer of an agent hidden from paired devices.
61    Hidden,
62}
63
64/// Whether `block_id` is a terminal a paired device may watch (sharing aside).
65pub(crate) fn terminal_watchable(state: &AppState, block_id: &str) -> Result<(), Unwatchable> {
66    use crate::backend::obj::{meta_get_string, Block};
67    let Ok(Some(block)) = state.mstore.get::<Block>(block_id) else {
68        return Err(Unwatchable::NotATerminal);
69    };
70    if meta_get_string(&block.meta, "view", "") != "term" {
71        return Err(Unwatchable::NotATerminal);
72    }
73    // An agent CLI can run in a terminal pane: that pane is the agent's, and
74    // hidden with it.
75    if agent_hidden(state, block_id) {
76        return Err(Unwatchable::Hidden);
77    }
78    let key = crate::backend::blockcontroller::META_KEY_SHELL_SUBBLOCK_ID;
79    let parent = state
80        .mstore
81        .get_all::<Block>()
82        .unwrap_or_default()
83        .into_iter()
84        .find(|b| meta_get_string(&b.meta, key, "") == block_id);
85    match parent {
86        Some(agent) if agent_hidden(state, &agent.oid) => Err(Unwatchable::Hidden),
87        _ => Ok(()),
88    }
89}
90
91fn refused(status: StatusCode, error: &str) -> Response {
92    (status, Json(json!({ "error": error }))).into_response()
93}
94
95pub(super) async fn handle_viewer_terminal_feed(
96    State(state): State<AppState>,
97    Extension(caller): Extension<ViewerCaller>,
98    Path(block_id): Path<String>,
99    headers: axum::http::HeaderMap,
100) -> Response {
101    if !terminals_shared(&state) {
102        return refused(StatusCode::FORBIDDEN, "this computer doesn't share its terminals");
103    }
104    let st = state.clone();
105    let id = block_id.clone();
106    let watchable = tokio::task::spawn_blocking(move || terminal_watchable(&st, &id)).await;
107    if !matches!(watchable, Ok(Ok(()))) {
108        return refused(StatusCode::NOT_FOUND, "no such terminal");
109    }
110    let lease = match state.viewer.open_feed(&caller.device_id, None) {
111        Ok(lease) => super::http_viewer::audited_feed(&state, &caller.device_id, &format!("terminal {block_id}"), lease),
112        Err(why) => return super::http_viewer::feed_refused(why),
113    };
114    let last_event_id = headers
115        .get("last-event-id")
116        .and_then(|v| v.to_str().ok())
117        .and_then(|v| v.trim().parse::<u64>().ok());
118    tracing::info!(device = %caller.device_id, block = %block_id, resume = last_event_id.is_some(), "viewer terminal feed: opened");
119    let stream = terminal_stream(
120        TermSource::of(&state, &block_id),
121        last_event_id,
122        lease,
123        TermTiming::default(),
124        TermProbe::of(&state, &block_id),
125    );
126    (
127        [(header::CONTENT_TYPE, "text/event-stream"), (header::CACHE_CONTROL, "no-cache")],
128        Body::from_stream(stream),
129    )
130        .into_response()
131}
132
133/// A terminal feed's clocks.
134#[derive(Debug, Clone, Copy)]
135pub(crate) struct TermTiming {
136    pub heartbeat: Duration,
137    pub size_poll: Duration,
138}
139
140impl Default for TermTiming {
141    fn default() -> Self {
142        Self { heartbeat: FEED_HEARTBEAT, size_poll: STATUS_POLL }
143    }
144}
145
146/// What a terminal feed asks while it runs: the PTY's size, and whether it
147/// may still be watched (`Some(reason)` ends the stream).
148pub(crate) struct TermProbe {
149    pub size: Box<dyn Fn() -> Option<(u16, u16)> + Send>,
150    pub closed: Box<dyn Fn() -> Option<&'static str> + Send>,
151}
152
153impl TermProbe {
154    pub(crate) fn of(state: &AppState, block_id: &str) -> Self {
155        let size_block = block_id.to_string();
156        let (st, block) = (state.clone(), block_id.to_string());
157        Self {
158            size: Box::new(move || crate::backend::blockcontroller::term_size::get(&size_block)),
159            closed: Box::new(move || {
160                if !terminals_shared(&st) {
161                    return Some("not_shared");
162                }
163                match terminal_watchable(&st, &block) {
164                    Ok(()) => None,
165                    Err(Unwatchable::Hidden) => Some("hidden"),
166                    Err(Unwatchable::NotATerminal) => Some("gone"),
167                }
168            }),
169        }
170    }
171}
172
173/// Where a terminal feed reads the terminal's output from: its `term` file.
174pub(crate) struct TermSource {
175    filestore: Arc<crate::backend::storage::filestore::FileStore>,
176    hub: Arc<feed::FeedHub>,
177    block_id: String,
178}
179
180/// A snapshot as read: its bytes start at `offset`; the file ends at `next`.
181struct TermSnapshot {
182    offset: u64,
183    next: u64,
184    data: Vec<u8>,
185}
186
187impl TermSource {
188    pub(crate) fn of(state: &AppState, block_id: &str) -> Self {
189        Self { filestore: state.filestore.clone(), hub: state.viewer.hub.clone(), block_id: block_id.to_string() }
190    }
191
192    /// The file's size and its bytes from `from` (`None`: from
193    /// [`terminal::SNAPSHOT_TAIL_BYTES`] before the end), on the blocking pool.
194    async fn read_from(&self, from: Option<u64>) -> Option<(u64, u64, Vec<u8>)> {
195        let (fs, block) = (self.filestore.clone(), self.block_id.clone());
196        tokio::task::spawn_blocking(move || {
197            let size = match fs.stat(&block, TERM_FILE) {
198                Ok(Some(file)) => file.size.max(0) as u64,
199                Ok(None) => return Some((0, 0, Vec::new())),
200                Err(_) => return None,
201            };
202            let start = from.unwrap_or_else(|| size.saturating_sub(terminal::SNAPSHOT_TAIL_BYTES));
203            // Nothing to read, or more than one event may carry (a resume far
204            // behind on a terminal whose file has no cap): not read at all.
205            if start >= size || size - start > terminal::SNAPSHOT_TAIL_BYTES {
206                return Some((start, size, Vec::new()));
207            }
208            let (at, data) = fs.read_at(&block, TERM_FILE, start as i64, (size - start) as i64).ok()?;
209            Some((at.max(0) as u64, size, data))
210        })
211        .await
212        .ok()
213        .flatten()
214    }
215
216    /// The tail, from a line start.
217    async fn snapshot(&self) -> Option<TermSnapshot> {
218        let (offset, next, mut data) = self.read_from(None).await?;
219        let start = terminal::tail_start(offset, &data);
220        data.drain(..start);
221        Some(TermSnapshot { offset: offset + start as u64, next, data })
222    }
223
224    /// The bytes from `from` on, for a reconnect: `None` when `from` is past
225    /// the end (the file was truncated) or more than a snapshot holds was
226    /// written since (a snapshot then). One event never carries more than a
227    /// snapshot would: a device's event-stream parser bounds a line's length.
228    async fn resume(&self, from: u64) -> Option<(u64, Vec<u8>)> {
229        let (at, size, data) = self.read_from(Some(from)).await?;
230        if from > size || at != from || size - from > terminal::SNAPSHOT_TAIL_BYTES {
231            return None;
232        }
233        Some((at, data))
234    }
235}
236
237fn b64(data: &[u8]) -> String {
238    base64::engine::general_purpose::STANDARD.encode(data)
239}
240
241fn snapshot_event(s: &TermSnapshot, size: Option<(u16, u16)>) -> Bytes {
242    let mut data = json!({ "offset": s.offset, "next_offset": s.next, "data64": b64(&s.data) });
243    if let Some((rows, cols)) = size {
244        data["rows"] = json!(rows);
245        data["cols"] = json!(cols);
246    }
247    feed::sse_event("snapshot", Some(&s.next.to_string()), &data)
248}
249
250fn append_event(offset: u64, data: &[u8]) -> Bytes {
251    let end = offset + data.len() as u64;
252    feed::sse_event("append", Some(&end.to_string()), &json!({ "offset": offset, "data64": b64(data) }))
253}
254
255fn size_event((rows, cols): (u16, u16)) -> Bytes {
256    feed::sse_event("size", None, &json!({ "rows": rows, "cols": cols }))
257}
258
259fn reset_event(reason: &str) -> Bytes {
260    feed::sse_event("reset", None, &json!({ "reason": reason }))
261}
262
263/// One terminal feed: `retry`, a `snapshot` (or, for a reconnect that still
264/// holds, the bytes it missed as one `append`), then an `append` per write,
265/// `size` on a resize, `reset` + `snapshot` when the file is truncated or the
266/// feed loses its place, and a heartbeat on a quiet stream. Ends with `reset`
267/// when the device falls more than 1 MB behind or the terminal may no longer
268/// be watched, and silently when the device is revoked or goes away.
269pub(crate) fn terminal_stream(
270    source: TermSource,
271    last_event_id: Option<u64>,
272    lease: FeedLease,
273    timing: TermTiming,
274    probe: TermProbe,
275) -> impl Stream<Item = Result<Bytes, Infallible>> + Send + 'static {
276    async_stream::stream! {
277        let lease = lease;
278        // Subscribed before anything is read, so nothing written between the
279        // read and the first event is missed.
280        let mut sub = source.hub.subscribe_file(&source.block_id, TERM_FILE);
281        yield Ok(Bytes::from_static(RETRY_PREAMBLE));
282        let mut shown_size = (probe.size)();
283
284        let resumed = match last_event_id {
285            Some(from) => source.resume(from).await,
286            None => None,
287        };
288        let mut next = match resumed {
289            Some((at, data)) => {
290                if !data.is_empty() {
291                    yield Ok(append_event(at, &data));
292                }
293                if let Some(size) = shown_size {
294                    yield Ok(size_event(size));
295                }
296                Some(at + data.len() as u64)
297            }
298            None => match source.snapshot().await {
299                Some(snapshot) => {
300                    yield Ok(snapshot_event(&snapshot, shown_size));
301                    Some(snapshot.next)
302                }
303                None => None,
304            },
305        };
306        if next.is_none() {
307            yield Ok(reset_event("unavailable"));
308        }
309
310        let mut tick = tokio::time::interval_at(tokio::time::Instant::now() + timing.heartbeat, timing.heartbeat);
311        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
312        let mut size_tick = tokio::time::interval_at(tokio::time::Instant::now() + timing.size_poll, timing.size_poll);
313        size_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
314        while let Some(cursor) = next.as_mut() {
315            let mut resync: Option<String> = None;
316            tokio::select! {
317                biased;
318                _ = lease.token.cancelled() => break,
319                event = sub.recv() => match event {
320                    None => break,
321                    Some(HubEvent::Behind) => {
322                        yield Ok(reset_event("behind"));
323                        break;
324                    }
325                    Some(HubEvent::Rewritten { fileop }) => resync = Some(fileop),
326                    Some(HubEvent::Append { offset, records, .. }) => match terminal::apply_term_append(cursor, offset, &records) {
327                        TermStep::Send { offset, data } => yield Ok(append_event(offset, &data)),
328                        TermStep::Skip => {}
329                        TermStep::Resync(reason) => resync = Some(reason.to_string()),
330                    },
331                },
332                _ = size_tick.tick() => {
333                    let size = (probe.size)();
334                    if size.is_some() && size != shown_size {
335                        shown_size = size;
336                        if let Some(size) = size {
337                            yield Ok(size_event(size));
338                        }
339                    }
340                }
341                _ = tick.tick() => {
342                    if let Some(reason) = (probe.closed)() {
343                        yield Ok(reset_event(reason));
344                        break;
345                    }
346                    yield Ok(Bytes::from_static(HEARTBEAT));
347                }
348            }
349            if let Some(reason) = resync {
350                tracing::info!(block = %source.block_id, %reason, "viewer terminal feed: reset; sending a fresh snapshot");
351                yield Ok(reset_event(&reason));
352                match source.snapshot().await {
353                    Some(snapshot) => {
354                        next = Some(snapshot.next);
355                        yield Ok(snapshot_event(&snapshot, shown_size));
356                    }
357                    None => {
358                        yield Ok(reset_event("unavailable"));
359                        break;
360                    }
361                }
362            }
363        }
364    }
365}
366
367#[cfg(test)]
368#[path = "tests/viewer/viewer_terminal_tests.rs"]
369mod tests;