Skip to main content

agentmux_srv/server/
http_viewer_history.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /agentmux/viewer/agents/:name/history?before=<gen:line>&limit=`: older lines of an agent's transcript than a
5//! paired device has, for a remote pane scrolled up past the feed's snapshot
6//! (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md §2, §7 "Large history").
7//!
8//! `before` is a line of the feed's own numbering: the snapshot's `from_line` (or an earlier page's) with the
9//! snapshot's `gen`. A page is the `limit` lines (at most 2,000) just before it, read and vetted the same way as the
10//! feed's (`FeedSource::read`: origin-vetted, withheld values out, `viewer::filter` applied), framed the same way, and
11//! at most [`PAGE_BYTES`] on the wire: when the lines are larger the oldest are left for the next page. A transcript
12//! that is another generation now answers `409 gen_changed`, and the device starts again from a snapshot.
13
14use axum::extract::{Path, Query, State};
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::{Extension, Json};
18use serde::Deserialize;
19use serde_json::json;
20
21use super::http_viewer::{agent_hidden, not_found, FeedSource, ViewerCaller};
22use crate::backend::viewer::feed;
23use crate::server::AppState;
24
25/// The most lines one page holds.
26pub(crate) const MAX_PAGE_LINES: u64 = 2_000;
27/// The most a page's lines take on the wire. A remote pane keeps at most 20 MiB of history (§2), so a page is a
28/// tenth of that; a page always holds at least one line (a frame is at most 64 KiB, `feed::device_frame`).
29pub(crate) const PAGE_BYTES: usize = 2 * 1024 * 1024;
30
31#[derive(Deserialize)]
32pub(crate) struct HistoryQuery {
33    before: String,
34    #[serde(default)]
35    limit: Option<u64>,
36}
37
38/// The lines a page asks for: `limit`, 1 to [`MAX_PAGE_LINES`], all of them when not given.
39fn page_lines(limit: Option<u64>) -> u64 {
40    limit.unwrap_or(MAX_PAGE_LINES).clamp(1, MAX_PAGE_LINES)
41}
42
43/// How many of `frames`, oldest first, to leave for the next page so the rest fit in `budget` bytes on the wire. The
44/// newest frame always stays.
45fn oldest_left_out(frames: &[String], budget: usize) -> usize {
46    let mut kept = 0;
47    let mut bytes = 0;
48    for frame in frames.iter().rev() {
49        let size = feed::wire_size(frame.as_bytes());
50        if kept > 0 && bytes + size > budget {
51            break;
52        }
53        bytes += size;
54        kept += 1;
55    }
56    frames.len() - kept
57}
58
59fn refuse(status: StatusCode, reason: &str, error: &str) -> Response {
60    (status, Json(json!({ "error": error, "reason": reason }))).into_response()
61}
62
63fn gen_changed() -> Response {
64    refuse(StatusCode::CONFLICT, "gen_changed", "the conversation was replaced since: open the feed again")
65}
66
67/// `GET /agentmux/viewer/agents/:name/history?before=<gen:line>&limit=`: `{gen, from_line, before, lines, more}`, the
68/// lines `from_line..before`; `more` when there are older ones. 404 for an agent that isn't this channel's or is
69/// hidden, 400 for a malformed `before` or one past the end, 409 `gen_changed`. A computer's read is signed as its
70/// feed open is (`http_viewer_computers::refuse_unsigned_open`), over the path and the query, so a page asked for is
71/// the page signed for; its token alone reads nothing.
72pub(crate) async fn handle_viewer_history(
73    State(state): State<AppState>,
74    Extension(caller): Extension<ViewerCaller>,
75    Path(name): Path<String>,
76    Query(q): Query<HistoryQuery>,
77    uri: axum::http::Uri,
78    headers: axum::http::HeaderMap,
79) -> Response {
80    let Some(agent) = state.reactive_handler.get_agent(&name) else {
81        return not_found();
82    };
83    if agent_hidden(&state, &agent.block_id) {
84        return not_found();
85    }
86    let signed_path = uri.path_and_query().map_or(uri.path(), |p| p.as_str());
87    if let Some(refused) = super::http_viewer_computers::refuse_unsigned_open(&state, &caller.device_id, signed_path, &headers) {
88        return refused;
89    }
90    let Some((gen, before)) = feed::parse_event_id(&q.before) else {
91        return refuse(StatusCode::BAD_REQUEST, "bad_cursor", "before is <gen>:<line>");
92    };
93    let source = FeedSource::of(&state, &agent.block_id);
94    let Some((_, current, total)) = source.position().await else {
95        return gen_changed();
96    };
97    if current != gen {
98        return gen_changed();
99    }
100    if before > total {
101        return refuse(StatusCode::BAD_REQUEST, "bad_cursor", "before is past the end of the conversation");
102    }
103    let from = before.saturating_sub(page_lines(q.limit));
104    let lines = if from == before {
105        Vec::new()
106    } else {
107        match source.read(from, before - from, &gen, false).await {
108            // A shorter read than asked: the transcript moved under the read.
109            Some(result) if result.lines.len() as u64 == before - from => result.lines,
110            _ => return gen_changed(),
111        }
112    };
113    let mut frames = feed::device_frames(lines);
114    let left_out = oldest_left_out(&frames, PAGE_BYTES);
115    frames.drain(..left_out);
116    let from_line = from + left_out as u64;
117    tracing::debug!(device = %caller.device_id, agent = %name, from_line, before, "viewer history: a page");
118    Json(json!({ "gen": gen, "from_line": from_line, "before": before, "lines": frames, "more": from_line > 0 }))
119        .into_response()
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn a_page_asks_for_one_to_two_thousand_lines() {
128        assert_eq!(page_lines(None), 2_000);
129        assert_eq!(page_lines(Some(0)), 1);
130        assert_eq!(page_lines(Some(50)), 50);
131        assert_eq!(page_lines(Some(1_000_000)), 2_000);
132    }
133
134    #[test]
135    fn the_oldest_lines_are_left_for_the_next_page_and_the_newest_always_stays() {
136        let frames: Vec<String> = (0..10).map(|i| format!("{i}{}", "x".repeat(99))).collect();
137        let size = feed::wire_size(frames[0].as_bytes());
138        assert_eq!(oldest_left_out(&frames, size * 10), 0);
139        assert_eq!(oldest_left_out(&frames, size * 3), 7);
140        assert_eq!(oldest_left_out(&frames, size * 3 + size / 2), 7);
141        assert_eq!(oldest_left_out(&frames, 1), 9, "one line however large");
142        assert_eq!(oldest_left_out(&[], 1), 0);
143    }
144}