Skip to main content

agentmux_srv/server/app_api/
open_tail.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agent:open_tail`: an agent pane's first screen from one small read.
5//! The open-first-screen design (#5156), under #5141.
6//!
7//! The pane used to open with three or four calls (the snapshot, the line
8//! count, a range of up to 10,000 lines) before it showed anything, and those
9//! could write under the store's single write lock: extending `output.idx`,
10//! catching the line counter up, a `stat` on a cache miss. This returns the
11//! newest ~64 KB of the transcript, the line positions the live feed resumes
12//! from, and the snapshot overlay, from **one reader snapshot**: it takes the
13//! WAL reader pool only, never the writer mutex, and never writes or extends
14//! an index.
15//!
16//! Line positions come from the line counter, caught up in memory when the
17//! file has grown past it (`SnapshotReader::tail_state`). A transcript with no
18//! usable counter epoch is counted first (`transcript::counting`, one scan at a
19//! time per file, off this read's snapshot): a small one is counted within the
20//! call, a large one answers `counting` and the pane asks again. Without that
21//! the pane's usual open could not read it either: `output.idx` is never
22//! fresh for a file with no generation. A transcript whose newest line fits no
23//! window comes back without line positions and the pane opens the usual way.
24
25use super::blockfile::{is_claude_turn_start, trim_to_last_turns, trim_to_tail_bytes};
26use super::*;
27
28use crate::backend::storage::filestore::{is_blank_line, FileStore, SnapshotReader};
29use crate::backend::storage::StoreError;
30
31/// A first screen: about what fits one pane, plus a margin.
32const DEFAULT_TAIL_BYTES: u64 = 64 * 1024;
33/// The most a counter that is only behind is caught up by in memory.
34const MAX_CATCH_UP_BYTES: i64 = 4 << 20;
35/// The most a tail read grows to when the newest line is larger than the window.
36const MAX_WINDOW_BYTES: i64 = 16 << 20;
37/// The most a slice is extended back to reach a turn start, and the most
38/// `tail_bytes` asks for: the pane's restore size today.
39const RESTORE_BUDGET_BYTES: i64 = 1 << 20;
40/// How long a call waits for a transcript with no epoch to be counted before it answers "counting"
41/// (the pane's call times out at 5 s). A small file is counted well inside it.
42const COUNT_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
43
44pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
45    let mstore = state.mstore.clone();
46    let filestore = state.filestore.clone();
47    let global_store = state.global_transcript_store.clone();
48    engine.register_typed(COMMAND_AGENT_OPEN_TAIL, move |cmd: CommandAgentOpenTailData, _ctx| {
49        let mstore = mstore.clone();
50        let filestore = filestore.clone();
51        let global_store = global_store.clone();
52        async move {
53            let started = std::time::Instant::now();
54            let block_id = cmd.block_id.clone();
55            let result = tokio::task::spawn_blocking(move || open_tail(&filestore, global_store.as_ref(), &mstore, cmd))
56                .await
57                .map_err(|e| format!("agent:open_tail: {e}"))??;
58            tracing::info!(
59                block_id = %block_id,
60                lines = result.lines.len(),
61                size = result.size.unwrap_or(0),
62                counted = result.gen.is_some(),
63                ms = started.elapsed().as_millis() as u64,
64                "agent:open_tail"
65            );
66            Ok(result)
67        }
68    });
69}
70
71/// Which store and zone a block's transcript is read from: the same rule
72/// `blockfile:read_range` and `blockfile:line_count` use (`global_output_source`:
73/// the agent's global zone when the block has a valid `agentId`, is not archived
74/// and the zone has content, the block's own otherwise), so the first screen and
75/// the older pages the pane reads next come from one file. Decided here from a
76/// reader snapshot rather than `stat`, which takes the writer mutex on a cache miss.
77fn pick_source(
78    filestore: &Arc<FileStore>,
79    global: Option<&Arc<FileStore>>,
80    mstore: &Arc<Store>,
81    block_id: &str,
82) -> (Arc<FileStore>, String, String) {
83    let local = || (filestore.clone(), block_id.to_string(), format!("b:{block_id}"));
84    let Some(gfs) = global else { return local() };
85    let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return local() };
86    let archived = block
87        .meta
88        .get(crate::backend::session_archive::META_SESSION_ARCHIVED_AT)
89        .and_then(|v| v.as_i64())
90        .map(|v| v > 0)
91        .unwrap_or(false);
92    if archived {
93        return local();
94    }
95    let Some(zone) = crate::backend::agent_session::agent_zone_for_block_meta(&block.meta) else { return local() };
96    // A zone found corrupt is not read again in this process: the block's own copy answers (`damage`).
97    if crate::backend::transcript::damage::is_damaged(&zone) {
98        return local();
99    }
100    let size = match gfs.read_snapshot(|r| Ok(r.file(&zone, "output")?.map(|f| f.size))) {
101        Ok(size) => size.unwrap_or(0),
102        Err(e) => {
103            crate::backend::transcript::damage::note_corrupt(&zone, "tail read", &e);
104            0
105        }
106    };
107    if size > 0 {
108        let stream = format!("g:{zone}");
109        (gfs.clone(), zone, stream)
110    } else {
111        local()
112    }
113}
114
115/// What one pass over the reader snapshot found.
116enum Read {
117    /// A slice, with where it sits.
118    Slice(Slice),
119    /// `expect_gen` is not the transcript's generation (named here).
120    Mismatch(String),
121    /// The slice could not be read (the newest line is larger than any window): no line positions.
122    Uncounted { size: i64 },
123    /// No usable counter epoch: the file has to be counted first (`transcript::counting`).
124    NoEpoch { size: i64 },
125}
126
127struct Slice {
128    gen: String,
129    size: i64,
130    /// `(byte offset, line)` of every returned line, oldest first.
131    lines: Vec<(i64, String)>,
132    stamps: Option<Vec<i64>>,
133    /// Byte offset just past the last complete line.
134    end_byte: i64,
135    /// Complete non-blank lines in the stream at the snapshot.
136    total_lines: u64,
137}
138
139/// The newest `want` bytes (the newest line always) of the complete lines in
140/// `[0, complete_end)`, with the non-blank lines in them and each one's byte
141/// offset. `None` when the bytes aren't all stored or the newest line is
142/// larger than [`MAX_WINDOW_BYTES`].
143fn read_window(r: &SnapshotReader<'_>, zone: &str, complete_end: i64, want: i64) -> Result<Option<Vec<(i64, String)>>, StoreError> {
144    let mut window = want.max(1);
145    loop {
146        let start = (complete_end - window).max(0);
147        // One byte before the window says whether it starts on a line start.
148        let pre = i64::from(start > 0);
149        let Some(buf) = r.bytes(zone, "output", start - pre, complete_end - start + pre)? else { return Ok(None) };
150        // Offset in `buf` of the first byte that starts a whole line.
151        let first = if start == 0 {
152            Some(0usize)
153        } else if buf.first() == Some(&b'\n') {
154            Some(1usize)
155        } else {
156            buf.iter().position(|b| *b == b'\n').map(|i| i + 1)
157        };
158        let mut lines = Vec::new();
159        if let Some(first) = first {
160            let base = start - pre + first as i64;
161            let mut at = first;
162            while at < buf.len() {
163                let end = buf[at..].iter().position(|b| *b == b'\n').map(|i| at + i).unwrap_or(buf.len());
164                let line = &buf[at..end];
165                if !is_blank_line(line) {
166                    lines.push((base + (at - first) as i64, String::from_utf8_lossy(line).into_owned()));
167                }
168                at = end + 1;
169            }
170        }
171        if !lines.is_empty() || start == 0 {
172            return Ok(Some(lines));
173        }
174        // No whole line fits: the newest line is larger than the window.
175        if window >= MAX_WINDOW_BYTES.min(complete_end) {
176            return Ok(None);
177        }
178        window = (window * 2).min(MAX_WINDOW_BYTES);
179    }
180}
181
182/// Receive-time stamps for lines starting at `offsets` (ascending byte offsets),
183/// from `output.tsidx` in this snapshot: the same lookup `blockfile:read_range`
184/// uses (`stamps_for`), which finds the records around the range wherever they
185/// are in the sidecar. `None` without a sidecar or records near the range.
186fn read_stamps(r: &SnapshotReader<'_>, zone: &str, offsets: &[i64]) -> Result<Option<Vec<i64>>, StoreError> {
187    use crate::backend::agent_session::TSIDX_FILE;
188    let Some(file) = r.file(zone, TSIDX_FILE)? else { return Ok(None) };
189    let offsets: Vec<u64> = offsets.iter().map(|o| (*o).max(0) as u64).collect();
190    crate::backend::blockcontroller::shell::stamps::stamps_for(&|off, len| r.bytes(zone, TSIDX_FILE, off, len), file.size, &offsets)
191}
192
193fn read_slice(r: &SnapshotReader<'_>, zone: &str, cmd: &CommandAgentOpenTailData) -> Result<Read, StoreError> {
194    let Some(state) = r.tail_state(zone, "output", MAX_CATCH_UP_BYTES)? else {
195        let size = r.file(zone, "output")?.map(|f| f.size).unwrap_or(0);
196        // Nothing to count in a file that is missing or empty (a new agent's block): the usual open answers it.
197        return Ok(if size > 0 { Read::NoEpoch { size } } else { Read::Uncounted { size } });
198    };
199    if let Some(expected) = &cmd.expect_gen {
200        if *expected != state.gen {
201            return Ok(Read::Mismatch(state.gen));
202        }
203    }
204    let want = cmd.tail_bytes.filter(|b| *b > 0).unwrap_or(DEFAULT_TAIL_BYTES).min(RESTORE_BUDGET_BYTES as u64) as i64;
205    // Read twice the budget, so the trimming sees lines it must drop and moves
206    // the start up to a turn start the way `read_range`'s tail_bytes does (it
207    // only does that when the byte budget cut something).
208    let Some(window) = read_window(r, zone, state.complete_end, want * 2)? else {
209        return Ok(Read::Uncounted { size: state.size });
210    };
211    // A counter that disagrees with the bytes (more lines read than it counts) can't position anything.
212    if window.len() as u64 > state.lines {
213        return Ok(Read::Uncounted { size: state.size });
214    }
215    let mut kept = trim_window(r, zone, window, cmd.tail_turns, want)?;
216
217    // A first screen must not start mid-turn, or the pane would show one turn
218    // as two rows once the rest fills in. When the slice has no turn start
219    // (one long running turn, which is when opening is slowest), reach back to
220    // the nearest one, up to the restore budget; a turn longer than that may
221    // start mid-turn.
222    let starts_a_turn = kept.0.first().map(|(_, l)| is_claude_turn_start(l)).unwrap_or(true);
223    if !starts_a_turn && (kept.0.len() as u64) < state.lines && want < RESTORE_BUDGET_BYTES {
224        if let Some(big) = read_window(r, zone, state.complete_end, RESTORE_BUDGET_BYTES)? {
225            let first_offset = kept.0[0].0;
226            let at = big.iter().position(|(o, _)| *o == first_offset);
227            if let Some(at) = at {
228                if let Some(j) = big[..=at].iter().rposition(|(_, l)| is_claude_turn_start(l)) {
229                    let reach: Vec<(i64, String)> = big[j..].to_vec();
230                    let offsets: Vec<i64> = reach.iter().map(|(o, _)| *o).collect();
231                    let stamps = read_stamps(r, zone, &offsets)?.filter(|s| s.len() == reach.len());
232                    kept = (reach, stamps);
233                }
234            }
235        }
236    }
237    let (lines, stamps) = kept;
238    Ok(Read::Slice(Slice {
239        gen: state.gen,
240        size: state.size,
241        lines,
242        stamps,
243        end_byte: state.complete_end,
244        total_lines: state.lines,
245    }))
246}
247
248/// `window` trimmed by the rules `blockfile:read_range` uses (`tail_turns`,
249/// then `tail_bytes`), with its receive-time stamps.
250fn trim_window(
251    r: &SnapshotReader<'_>,
252    zone: &str,
253    window: Vec<(i64, String)>,
254    tail_turns: Option<u32>,
255    want: i64,
256) -> Result<(Vec<(i64, String)>, Option<Vec<i64>>), StoreError> {
257    let offsets: Vec<i64> = window.iter().map(|(o, _)| *o).collect();
258    let stamps = read_stamps(r, zone, &offsets)?.filter(|s| s.len() == window.len());
259    let mut trimmed = BlockfileReadRangeResult { lines: window.iter().map(|(_, l)| l.clone()).collect(), stamps, ..Default::default() };
260    if let Some(turns) = tail_turns.filter(|t| *t > 0) {
261        trim_to_last_turns(&mut trimmed, 0, turns as usize);
262    }
263    trim_to_tail_bytes(&mut trimmed, 0, want as usize);
264    let cut = window.len() - trimmed.lines.len();
265    Ok((window.into_iter().skip(cut).collect(), trimmed.stamps))
266}
267
268/// The agent's session snapshot, from reader snapshots: the global store first
269/// (it always holds the agent-anchored copy), the block's store as a fallback,
270/// as `agent:session:read` does.
271fn read_overlay(filestore: &Arc<FileStore>, global: Option<&Arc<FileStore>>, definition_id: &str) -> Option<(String, i64)> {
272    use crate::backend::agent_session::{agent_current_zone, is_valid_definition_id, SNAPSHOT_FILE};
273    if !is_valid_definition_id(definition_id) {
274        return None;
275    }
276    let zone = agent_current_zone(definition_id);
277    let from = |fs: &Arc<FileStore>| -> Option<(String, i64)> {
278        fs.read_snapshot(|r| {
279            let Some(file) = r.file(&zone, SNAPSHOT_FILE)? else { return Ok(None) };
280            let bytes = r.bytes(&zone, SNAPSHOT_FILE, 0, file.size)?.unwrap_or_default();
281            Ok(Some((String::from_utf8_lossy(&bytes).into_owned(), file.modts)))
282        })
283        .ok()
284        .flatten()
285    };
286    global.and_then(from).or_else(|| from(filestore))
287}
288
289fn open_tail(
290    filestore: &Arc<FileStore>,
291    global: Option<&Arc<FileStore>>,
292    mstore: &Arc<Store>,
293    cmd: CommandAgentOpenTailData,
294) -> Result<AgentOpenTailResult, String> {
295    open_tail_waiting(filestore, global, mstore, cmd, COUNT_WAIT)
296}
297
298/// [`open_tail`], waiting up to `count_wait` for a transcript with no epoch to be counted.
299fn open_tail_waiting(
300    filestore: &Arc<FileStore>,
301    global: Option<&Arc<FileStore>>,
302    mstore: &Arc<Store>,
303    cmd: CommandAgentOpenTailData,
304    count_wait: std::time::Duration,
305) -> Result<AgentOpenTailResult, String> {
306    if cmd.filename != crate::backend::agent_session::OUTPUT_FILE {
307        return Err(format!("agent:open_tail: only `{}` has a tail", crate::backend::agent_session::OUTPUT_FILE));
308    }
309    let (mut fs, mut zone, mut stream) = pick_source(filestore, global, mstore, &cmd.block_id);
310    let mut read = fs.read_snapshot(|r| read_slice(r, &zone, &cmd));
311    // The shared zone answered with a corrupt database: it is marked now, so the block's own copy answers instead.
312    if let Err(e) = &read {
313        if stream.starts_with("g:") && crate::backend::transcript::damage::note_corrupt(&zone, "tail read", e) {
314            (fs, zone, stream) = pick_source(filestore, global, mstore, &cmd.block_id);
315            read = fs.read_snapshot(|r| read_slice(r, &zone, &cmd));
316        }
317    }
318    let mut read = read.map_err(|e| format!("agent:open_tail: {e}"))?;
319    // No epoch: count the file (once, whoever asks), and wait for it a moment. A small file is counted
320    // by then and opens in this call; a large one answers "counting" and the pane asks again.
321    if matches!(read, Read::NoEpoch { .. }) && crate::backend::transcript::counting::ensure_counted(&fs, &zone, count_wait) {
322        read = fs.read_snapshot(|r| read_slice(r, &zone, &cmd)).map_err(|e| format!("agent:open_tail: {e}"))?;
323    }
324    let mut out = match read {
325        Read::Mismatch(gen) => AgentOpenTailResult {
326            stream: Some(stream),
327            gen: Some(gen),
328            gen_mismatch: Some(true),
329            ..Default::default()
330        },
331        Read::Uncounted { size } => AgentOpenTailResult { size: Some(size.max(0) as u64), ..Default::default() },
332        Read::NoEpoch { size } => AgentOpenTailResult { size: Some(size.max(0) as u64), counting: Some(true), ..Default::default() },
333        Read::Slice(slice) => {
334            let end_line = slice.total_lines;
335            let start_line = end_line - slice.lines.len() as u64;
336            let start_byte = slice.lines.first().map(|(o, _)| *o).unwrap_or(slice.end_byte);
337            AgentOpenTailResult {
338                stamps: slice.stamps,
339                stream: Some(stream),
340                gen: Some(slice.gen),
341                start_line: Some(start_line),
342                end_line: Some(end_line),
343                total_lines: Some(end_line),
344                start_byte: Some(start_byte.max(0) as u64),
345                end_byte: Some(slice.end_byte.max(0) as u64),
346                size: Some(slice.size.max(0) as u64),
347                has_more_before: Some(start_line > 0),
348                lines: slice.lines.into_iter().map(|(_, l)| l).collect(),
349                ..Default::default()
350            }
351        }
352    };
353    let owner = crate::backend::transcript::origin_sig::owner_for_read(mstore, &cmd.block_id, &zone);
354    crate::backend::transcript::attribution::vet_for_viewer(mstore, filestore, &owner, &mut out.lines);
355    if super::history_damaged(mstore, &cmd.block_id) {
356        out.history_damaged = Some(true);
357    }
358    if let Some(def_id) = cmd.definition_id.as_deref().filter(|d| !d.is_empty()) {
359        if let Some((content, modts)) = read_overlay(filestore, global, def_id) {
360            out.snapshot = Some(content);
361            out.snapshot_modts = Some(modts);
362        }
363    }
364    Ok(out)
365}
366
367#[cfg(test)]
368#[path = "open_tail_tests.rs"]
369mod open_tail_tests;