Skip to main content

agentmux_srv_core/backend/viewer/
feed.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The server-side half of the live feed: a [`FeedHub`] that watches every
5//! published `blockfile` event in-process (a broker observer, so no
6//! WebSocket route is involved) and hands each open feed the changes of the
7//! one file it follows: an agent's transcript (`output`), or a terminal's
8//! output (`term`, for the terminal feed in [`super::terminal`]); plus the
9//! pure pieces of the feed's wire (cursor, frame truncation, SSE framing)
10//! the route assembles.
11//!
12//! Nothing is buffered without bound for a slow device: a subscription counts
13//! the bytes queued for it, and once more than [`MAX_BEHIND_BYTES`] wait it
14//! stops queueing and receives one [`HubEvent::Behind`], on which the feed
15//! sends `reset` and closes (the device reconnects and gets a snapshot).
16
17use std::collections::HashMap;
18use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
19use std::sync::Arc;
20
21use axum::body::Bytes;
22use base64::Engine as _;
23use serde::Serialize;
24use tokio::sync::mpsc;
25
26use crate::backend::agent_state::AgentStatus;
27use crate::backend::mps::{self, MuxEvent, StreamPos};
28
29/// A stream more than this far behind is reset and closed.
30pub const MAX_BEHIND_BYTES: usize = 1024 * 1024;
31/// A terminal block's output file: raw PTY bytes.
32pub const TERM_FILE: &str = "term";
33/// A frame longer than this is replaced by an `amx_truncated` frame.
34pub const MAX_FRAME_BYTES: usize = 64 * 1024;
35/// How much of a truncated frame is kept, in characters.
36pub const TRUNCATED_HEAD_CHARS: usize = 2048;
37
38/// About how many bytes `records` cost on the wire: each line as the device
39/// gets it, so at most [`MAX_FRAME_BYTES`] however large it is written (one
40/// 5 MB tool result is 64 KB behind, not 5 MB), and as a JSON string inside
41/// the event, so with its escapes: a line of quotes is twice its size there.
42/// Counting raw bytes let a 1 MB resume become a 2 MB event, past what the
43/// phone's reader took in one line.
44pub fn wire_size(records: &[u8]) -> usize {
45    records
46        .split(|b| *b == b'\n')
47        .map(|line| {
48            let kept = &line[..line.len().min(MAX_FRAME_BYTES)];
49            let escapes: usize = kept
50                .iter()
51                .map(|b| match b {
52                    b'"' | b'\\' | b'\t' | b'\r' | 0x08 | 0x0c => 1,
53                    0..=0x1f => 5,
54                    _ => 0,
55                })
56                .sum();
57            kept.len() + escapes + 1
58        })
59        .sum()
60}
61
62/// What `records` of `filename` cost a subscriber: a transcript's lines as
63/// the device gets them ([`wire_size`]); a terminal's bytes as they are.
64fn queued_size(filename: &str, records: &[u8]) -> usize {
65    if filename == TERM_FILE {
66        records.len()
67    } else {
68        wire_size(records)
69    }
70}
71
72/// What a subscription receives.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum HubEvent {
75    /// Bytes appended to the file, as published: where they landed per
76    /// stream (transcripts), the byte offset they were written at when the
77    /// writer said (terminals), and the bytes themselves.
78    Append { pos: Vec<StreamPos>, offset: Option<u64>, records: Vec<u8> },
79    /// The transcript was replaced, deleted or otherwise rewritten as a
80    /// whole (`fileop`).
81    Rewritten { fileop: String },
82    /// Too much was waiting; nothing more will be queued.
83    Behind,
84}
85
86struct Subscriber {
87    id: u64,
88    tx: mpsc::UnboundedSender<HubEvent>,
89    /// Bytes queued and not yet received. With `behind`, what bounds `tx`.
90    pending: Arc<AtomicUsize>,
91    behind: Arc<AtomicBool>,
92}
93
94/// Every open feed's subscription, by the block and file it follows.
95pub struct FeedHub {
96    subs: parking_lot::RwLock<HashMap<(String, String), Vec<Subscriber>>>,
97    next_id: AtomicU64,
98    max_behind: usize,
99}
100
101impl Default for FeedHub {
102    fn default() -> Self {
103        Self::with_max_behind(MAX_BEHIND_BYTES)
104    }
105}
106
107impl FeedHub {
108    pub fn with_max_behind(max_behind: usize) -> Self {
109        Self {
110            subs: parking_lot::RwLock::new(HashMap::new()),
111            next_id: AtomicU64::new(1),
112            max_behind,
113        }
114    }
115
116    /// Watch `broker` for transcript events. Called once per broker.
117    pub fn install(self: &Arc<Self>, broker: &mps::Broker) {
118        let hub = Arc::clone(self);
119        broker.add_observer(Arc::new(move |event: &MuxEvent| hub.observe(event)));
120    }
121
122    /// Start receiving `block_id`'s transcript changes. Subscribe before
123    /// reading the snapshot, so nothing published in between is missed; the
124    /// feed drops what the snapshot already holds by line number.
125    pub fn subscribe(self: &Arc<Self>, block_id: &str) -> FeedSubscription {
126        self.subscribe_file(block_id, crate::backend::agent_session::OUTPUT_FILE)
127    }
128
129    /// Start receiving the changes of `block_id`'s `filename` (the
130    /// transcript, or [`TERM_FILE`]).
131    pub fn subscribe_file(self: &Arc<Self>, block_id: &str, filename: &str) -> FeedSubscription {
132        let (tx, rx) = mpsc::unbounded_channel();
133        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
134        let pending = Arc::new(AtomicUsize::new(0));
135        let behind = Arc::new(AtomicBool::new(false));
136        let key = (block_id.to_string(), filename.to_string());
137        self.subs.write().entry(key.clone()).or_default().push(Subscriber {
138            id,
139            tx,
140            pending: Arc::clone(&pending),
141            behind,
142        });
143        FeedSubscription { hub: Arc::clone(self), key, id, rx, pending }
144    }
145
146    #[cfg(test)]
147    pub fn subscribers(&self, block_id: &str) -> usize {
148        let key = (block_id.to_string(), crate::backend::agent_session::OUTPUT_FILE.to_string());
149        self.subs.read().get(&key).map_or(0, Vec::len)
150    }
151
152    fn unsubscribe(&self, key: &(String, String), id: u64) {
153        let mut subs = self.subs.write();
154        if let Some(list) = subs.get_mut(key) {
155            list.retain(|s| s.id != id);
156            if list.is_empty() {
157                subs.remove(key);
158            }
159        }
160    }
161
162    /// The broker observer. Runs on every publish, so it returns at once for
163    /// anything but an event of a followed block's followed file, and never
164    /// blocks.
165    pub fn observe(&self, event: &MuxEvent) {
166        if event.event != mps::EVENT_BLOCK_FILE {
167            return;
168        }
169        let Some(data) = event.data.as_ref() else { return };
170        let Some(filename) = data.get("filename").and_then(|v| v.as_str()) else { return };
171        if filename != crate::backend::agent_session::OUTPUT_FILE && filename != TERM_FILE {
172            return;
173        }
174        let Some(block_id) = data.get("zoneid").and_then(|v| v.as_str()) else { return };
175        let subs = self.subs.read();
176        let Some(list) = subs.get(&(block_id.to_string(), filename.to_string())) else { return };
177        let Ok(file) = serde_json::from_value::<mps::WSFileEventData>(data.clone()) else { return };
178        let event = if file.fileop == mps::FILE_OP_APPEND {
179            let Ok(records) = base64::engine::general_purpose::STANDARD.decode(file.data64.as_bytes()) else {
180                return;
181            };
182            HubEvent::Append { pos: file.pos, offset: file.offset, records }
183        } else {
184            HubEvent::Rewritten { fileop: file.fileop }
185        };
186        let size = match &event {
187            HubEvent::Append { records, .. } => queued_size(filename, records),
188            _ => 0,
189        };
190        for sub in list {
191            if sub.behind.load(Ordering::Relaxed) {
192                continue;
193            }
194            if sub.pending.load(Ordering::Relaxed) + size > self.max_behind {
195                sub.behind.store(true, Ordering::Relaxed);
196                let _ = sub.tx.send(HubEvent::Behind);
197                continue;
198            }
199            sub.pending.fetch_add(size, Ordering::Relaxed);
200            let _ = sub.tx.send(event.clone());
201        }
202    }
203}
204
205/// One feed's subscription; unsubscribes when dropped.
206pub struct FeedSubscription {
207    hub: Arc<FeedHub>,
208    /// The block and file it follows.
209    key: (String, String),
210    id: u64,
211    rx: mpsc::UnboundedReceiver<HubEvent>,
212    pending: Arc<AtomicUsize>,
213}
214
215impl FeedSubscription {
216    pub async fn recv(&mut self) -> Option<HubEvent> {
217        let event = self.rx.recv().await?;
218        if let HubEvent::Append { records, .. } = &event {
219            self.pending.fetch_sub(queued_size(&self.key.1, records), Ordering::Relaxed);
220        }
221        Some(event)
222    }
223}
224
225impl Drop for FeedSubscription {
226    fn drop(&mut self) {
227        self.hub.unsubscribe(&self.key, self.id);
228    }
229}
230
231/// Where a feed stands in its stream: the generation it is reading and the
232/// next line it has not sent.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct Cursor {
235    /// `b:<blockId>`, or `g:<zone>` when the transcript is read from the
236    /// agent's global zone.
237    pub stream: String,
238    /// '' while the transcript does not exist yet.
239    pub gen: String,
240    pub next_line: u64,
241}
242
243impl Cursor {
244    /// `<gen>:<next line>`, the SSE `id` a reconnect sends back.
245    pub fn event_id(&self) -> String {
246        format!("{}:{}", self.gen, self.next_line)
247    }
248}
249
250/// `Last-Event-ID` read back: `(gen, next line)`.
251pub fn parse_event_id(id: &str) -> Option<(String, u64)> {
252    let (gen, line) = id.trim().rsplit_once(':')?;
253    if gen.is_empty() {
254        return None;
255    }
256    Some((gen.to_string(), line.parse().ok()?))
257}
258
259/// What to do with one published append.
260#[derive(Debug, Clone, PartialEq, Eq)]
261pub enum AppendStep {
262    /// Send these lines, starting at `line`; the cursor has moved past them.
263    Send { line: u64, lines: Vec<String> },
264    /// Nothing new for this feed (another stream's event, or lines already sent).
265    Skip,
266    /// The feed can't continue from here (another generation, a gap, a count
267    /// that doesn't match): reset and send a fresh snapshot.
268    Resync(&'static str),
269}
270
271/// The lines in published `records`, split the way `blockfile:read_range`
272/// splits the file, so the counts agree.
273pub fn split_records(records: &[u8]) -> Vec<String> {
274    String::from_utf8_lossy(records)
275        .lines()
276        .filter(|l| !l.trim().is_empty())
277        .map(str::to_string)
278        .collect()
279}
280
281/// Apply one published append to `cursor`.
282pub fn apply_append(cursor: &mut Cursor, pos: &[StreamPos], records: &[u8]) -> AppendStep {
283    let Some(pos) = pos.iter().find(|p| p.stream == cursor.stream) else {
284        return AppendStep::Skip;
285    };
286    if pos.gen != cursor.gen {
287        // A transcript that didn't exist at the snapshot: its first
288        // generation simply continues from line 0.
289        if cursor.gen.is_empty() && cursor.next_line == 0 {
290            cursor.gen = pos.gen.clone();
291        } else {
292            return AppendStep::Resync("gen");
293        }
294    }
295    if pos.lines <= cursor.next_line {
296        return AppendStep::Skip;
297    }
298    if pos.line > cursor.next_line {
299        return AppendStep::Resync("gap");
300    }
301    let mut lines = split_records(records);
302    if lines.len() as u64 != pos.lines - pos.line {
303        return AppendStep::Resync("count");
304    }
305    let skip = (cursor.next_line - pos.line) as usize;
306    lines.drain(..skip);
307    let line = cursor.next_line;
308    cursor.next_line = pos.lines;
309    AppendStep::Send { line, lines }
310}
311
312/// Whether a feed sends a `status` event now, given the state it last sent
313/// (`shown`, updated here) and the state now: `Some(Some(_))` sends a state,
314/// `Some(None)` sends `state: null` so the device drops a chip it shows, `None`
315/// sends nothing. Right after a snapshot (`after_snapshot`) a known state is
316/// always sent; otherwise only a change of state or `since_ms` is. An agent
317/// that has never had a state gets no event at all.
318pub fn status_step(
319    shown: &mut Option<AgentStatus>,
320    now: Option<AgentStatus>,
321    after_snapshot: bool,
322) -> Option<Option<AgentStatus>> {
323    let send = match (&*shown, &now) {
324        (_, Some(now)) => after_snapshot || shown.as_ref() != Some(now),
325        (Some(_), None) => true,
326        (None, None) => false,
327    };
328    *shown = now;
329    send.then_some(now)
330}
331
332/// A frame as the device gets it: as written, or, over
333/// [`MAX_FRAME_BYTES`], an `amx_truncated` frame with its size and head.
334pub fn device_frame(line: String) -> String {
335    if line.len() <= MAX_FRAME_BYTES {
336        return line;
337    }
338    let head: String = line.chars().take(TRUNCATED_HEAD_CHARS).collect();
339    serde_json::json!({ "type": "amx_truncated", "bytes": line.len(), "head": head }).to_string()
340}
341
342/// [`device_frame`] over a batch.
343pub fn device_frames(lines: Vec<String>) -> Vec<String> {
344    lines.into_iter().map(device_frame).collect()
345}
346
347/// One SSE event. `data` is serde output on one line, so no raw newline can
348/// end the `data:` field early.
349pub fn sse_event(name: &str, id: Option<&str>, data: &impl Serialize) -> Bytes {
350    let json = serde_json::to_string(data).unwrap_or_else(|_| "{}".to_string());
351    match id {
352        Some(id) => Bytes::from(format!("event: {name}\nid: {id}\ndata: {json}\n\n")),
353        None => Bytes::from(format!("event: {name}\ndata: {json}\n\n")),
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    fn pos(stream: &str, gen: &str, line: u64, lines: u64) -> Vec<StreamPos> {
362        vec![StreamPos { stream: stream.into(), gen: gen.into(), line, lines }]
363    }
364
365    fn cursor(gen: &str, next: u64) -> Cursor {
366        Cursor { stream: "b:blk".into(), gen: gen.into(), next_line: next }
367    }
368
369    #[test]
370    fn appends_continue_the_cursor_and_drop_what_was_sent() {
371        let mut c = cursor("g1", 3);
372        let step = apply_append(&mut c, &pos("b:blk", "g1", 3, 5), b"{\"a\":1}\n{\"a\":2}\n");
373        assert_eq!(step, AppendStep::Send { line: 3, lines: vec!["{\"a\":1}".into(), "{\"a\":2}".into()] });
374        assert_eq!(c.next_line, 5);
375
376        // Already sent (the snapshot held it).
377        assert_eq!(apply_append(&mut c, &pos("b:blk", "g1", 4, 5), b"x\n"), AppendStep::Skip);
378        // Half sent: only the new part goes out.
379        let step = apply_append(&mut c, &pos("b:blk", "g1", 4, 7), b"x\ny\nz\n");
380        assert_eq!(step, AppendStep::Send { line: 5, lines: vec!["y".into(), "z".into()] });
381        assert_eq!(c.event_id(), "g1:7");
382    }
383
384    #[test]
385    fn another_generation_a_gap_or_a_bad_count_resyncs() {
386        let mut c = cursor("g1", 3);
387        assert_eq!(apply_append(&mut c, &pos("b:blk", "g2", 0, 1), b"x\n"), AppendStep::Resync("gen"));
388        assert_eq!(apply_append(&mut c, &pos("b:blk", "g1", 4, 5), b"x\n"), AppendStep::Resync("gap"));
389        assert_eq!(apply_append(&mut c, &pos("b:blk", "g1", 3, 5), b"x\n"), AppendStep::Resync("count"));
390        assert_eq!(c.next_line, 3, "nothing moved");
391    }
392
393    #[test]
394    fn other_streams_are_ignored_and_a_new_transcript_is_adopted() {
395        let mut c = cursor("g1", 3);
396        assert_eq!(apply_append(&mut c, &pos("g:agent:x:current", "zz", 0, 9), b"x\n"), AppendStep::Skip);
397        let mut fresh = cursor("", 0);
398        let step = apply_append(&mut fresh, &pos("b:blk", "g9", 0, 1), b"first\n");
399        assert_eq!(step, AppendStep::Send { line: 0, lines: vec!["first".into()] });
400        assert_eq!(fresh.gen, "g9");
401    }
402
403    #[test]
404    fn event_ids_round_trip() {
405        assert_eq!(parse_event_id("ab12:40"), Some(("ab12".into(), 40)));
406        assert_eq!(parse_event_id(" ab12:0 "), Some(("ab12".into(), 0)));
407        for bad in ["", ":4", "ab12", "ab12:x", "ab12:-1"] {
408            assert_eq!(parse_event_id(bad), None, "{bad}");
409        }
410    }
411
412    #[test]
413    fn a_frame_over_64_kb_is_replaced_by_its_head() {
414        let small = "x".repeat(MAX_FRAME_BYTES);
415        assert_eq!(device_frame(small.clone()), small);
416        let big = format!("{{\"type\":\"user\",\"text\":\"{}\"}}", "é".repeat(5 * 1024 * 1024 / 2));
417        let frame = device_frame(big.clone());
418        assert!(frame.len() < MAX_FRAME_BYTES);
419        let v: serde_json::Value = serde_json::from_str(&frame).unwrap();
420        assert_eq!(v["type"], "amx_truncated");
421        assert_eq!(v["bytes"], big.len());
422        let head = v["head"].as_str().unwrap();
423        assert_eq!(head.chars().count(), TRUNCATED_HEAD_CHARS);
424        assert!(big.starts_with(head));
425    }
426
427    #[test]
428    fn a_huge_line_counts_as_the_frame_the_device_gets() {
429        let huge = format!("{}\n", "x".repeat(5 * 1024 * 1024));
430        assert!(wire_size(huge.as_bytes()) <= MAX_FRAME_BYTES + 2);
431        assert_eq!(wire_size(b"ab\ncd\n"), 3 + 3 + 1);
432    }
433
434    #[test]
435    fn a_line_counts_with_the_escapes_it_gets_as_a_json_string() {
436        // Each record goes out as a JSON string: quotes and backslashes
437        // double, a control character becomes \u00XX.
438        let line = r#"{"a":"b\"c"}"#;
439        let on_wire = serde_json::to_string(line).unwrap();
440        assert_eq!(wire_size(line.as_bytes()), on_wire.len() - 2 + 1, "the escaped string without its quotes, plus the newline");
441        assert_eq!(wire_size(b"\x01"), 6 + 1);
442        assert_eq!(wire_size(b"\t"), 2 + 1);
443    }
444
445    #[test]
446    fn status_is_sent_after_a_snapshot_on_change_and_once_when_it_goes() {
447        use crate::backend::agent_state::AgentState;
448        let working = AgentStatus { state: AgentState::Working, since_ms: 100 };
449        let idle = AgentStatus { state: AgentState::Idle, since_ms: 200 };
450        let mut shown = None;
451        assert_eq!(status_step(&mut shown, None, true), None, "no state yet: no event, even after a snapshot");
452        assert_eq!(status_step(&mut shown, None, false), None);
453        assert_eq!(status_step(&mut shown, Some(working), true), Some(Some(working)));
454        assert_eq!(status_step(&mut shown, Some(working), false), None, "unchanged");
455        assert_eq!(status_step(&mut shown, Some(working), true), Some(Some(working)), "every snapshot gets one");
456        assert_eq!(status_step(&mut shown, Some(idle), false), Some(Some(idle)));
457        let restarted = AgentStatus { state: AgentState::Idle, since_ms: 900 };
458        assert_eq!(status_step(&mut shown, Some(restarted), false), Some(Some(restarted)), "since_ms alone counts");
459        assert_eq!(status_step(&mut shown, None, false), Some(None), "gone: null, once");
460        assert_eq!(status_step(&mut shown, None, false), None);
461        assert_eq!(status_step(&mut shown, None, true), None);
462    }
463
464    #[test]
465    fn sse_events_are_one_data_line() {
466        let ev = sse_event("append", Some("g:3"), &serde_json::json!({"lines": ["a\nb"]}));
467        let text = String::from_utf8(ev.to_vec()).unwrap();
468        assert_eq!(text, "event: append\nid: g:3\ndata: {\"lines\":[\"a\\nb\"]}\n\n");
469        let reset = sse_event("reset", None, &serde_json::json!({"reason": "gen"}));
470        assert_eq!(String::from_utf8(reset.to_vec()).unwrap(), "event: reset\ndata: {\"reason\":\"gen\"}\n\n");
471    }
472
473    fn blockfile(block: &str, fileop: &str, records: &[u8], pos: Vec<StreamPos>) -> MuxEvent {
474        let data = mps::WSFileEventData {
475            zoneid: block.into(),
476            filename: "output".into(),
477            fileop: fileop.into(),
478            data64: base64::engine::general_purpose::STANDARD.encode(records),
479            offset: None,
480            pos,
481            echo: None,
482        };
483        MuxEvent {
484            event: mps::EVENT_BLOCK_FILE.into(),
485            scopes: vec![format!("block:{block}")],
486            sender: String::new(),
487            persist: 0,
488            data: serde_json::to_value(&data).ok(),
489        }
490    }
491
492    #[tokio::test]
493    async fn the_hub_delivers_only_the_followed_blocks_transcript() {
494        let broker = mps::Broker::new();
495        let hub = Arc::new(FeedHub::default());
496        hub.install(&broker);
497        let mut sub = hub.subscribe("b1");
498        broker.publish(blockfile("b2", "append", b"other\n", pos("b:b2", "g", 0, 1)));
499        let mut term = blockfile("b1", "append", b"tty", vec![]);
500        if let Some(d) = term.data.as_mut() {
501            d["filename"] = "term".into();
502        }
503        broker.publish(term);
504        broker.publish(blockfile("b1", "append", b"mine\n", pos("b:b1", "g", 0, 1)));
505        broker.publish(blockfile("b1", "replace", b"", vec![]));
506        assert_eq!(
507            sub.recv().await,
508            Some(HubEvent::Append { pos: pos("b:b1", "g", 0, 1), offset: None, records: b"mine\n".to_vec() })
509        );
510        assert_eq!(sub.recv().await, Some(HubEvent::Rewritten { fileop: "replace".into() }));
511        assert_eq!(hub.subscribers("b1"), 1);
512        drop(sub);
513        assert_eq!(hub.subscribers("b1"), 0, "dropping the subscription unsubscribes");
514    }
515
516    #[tokio::test]
517    async fn a_subscription_that_falls_behind_gets_behind_once_and_nothing_more() {
518        let broker = mps::Broker::new();
519        let hub = Arc::new(FeedHub::with_max_behind(10));
520        hub.install(&broker);
521        let mut sub = hub.subscribe("b1");
522        for i in 0..5u64 {
523            broker.publish(blockfile("b1", "append", b"12345\n", pos("b:b1", "g", i, i + 1)));
524        }
525        assert!(matches!(sub.recv().await, Some(HubEvent::Append { .. })));
526        assert_eq!(sub.recv().await, Some(HubEvent::Behind), "the second append would pass 10 bytes");
527        broker.publish(blockfile("b1", "append", b"x\n", pos("b:b1", "g", 5, 6)));
528        assert!(
529            tokio::time::timeout(std::time::Duration::from_millis(100), sub.recv()).await.is_err(),
530            "nothing is queued after Behind"
531        );
532    }
533}