Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
term_cap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The size cap on what a terminal pane keeps of its output (the `term` file in
5//! the pane's zone). A command that prints without end (`yes`) was stored whole:
6//! 2.5 GB and a 4.3 GB write-ahead log in 100 s. The file is now circular: it
7//! holds the last `term:storedoutputmb` megabytes (50 by default, 0 for no
8//! limit), offsets stay absolute so readers that remember where they were keep
9//! working, and the parts below the window are deleted as the file grows
10//! (`FileStore::trim_circular_head`). Agent transcripts are a different file and
11//! are not touched.
12
13use std::sync::atomic::{AtomicI64, Ordering};
14
15use crate::backend::storage::filestore::{FileOpts, FileStore};
16
17/// The settings.json key, whole megabytes.
18pub const SETTING: &str = "term:storedoutputmb";
19const DEFAULT_MB: i64 = 50;
20/// A typo like 5000000 is a limit nobody meant.
21const MAX_MB: i64 = 100_000;
22const MIB: i64 = 1 << 20;
23/// Log written between two checkpoints made by the writer itself. Counted as the
24/// log takes it in (`append_log_cost`), not as output: the PTY's batches run
25/// from one 4 KB read to 256 KB, and the smaller they are the more log each
26/// byte of output costs.
27const WAL_RELIEF_EVERY: i64 = 8 * MIB;
28/// Log written before the writer tries again, after a pass that could not copy
29/// all of the log back (`FileStore::checkpoint_between_writes`).
30const WAL_RELIEF_RETRY: i64 = MIB;
31/// The block file the cap applies to.
32pub const TERM_FILE: &str = "term";
33
34/// Written into the stream once, when the first output is dropped, so the pane
35/// (live and on reload, until it scrolls out of the window) says so.
36pub const TRIMMED_NOTICE: &[u8] = b"\r\n\x1b[2m[earlier output trimmed: AgentMux keeps a limited amount of each terminal's output]\x1b[0m\r\n";
37
38static CAP_BYTES: AtomicI64 = AtomicI64::new(DEFAULT_MB * MIB);
39/// Log the terminal writers have put in since one of them last checkpointed.
40static LOG_SINCE_RELIEF: AtomicI64 = AtomicI64::new(0);
41
42/// Whether this append is the one that should checkpoint: `pending` has taken in
43/// `WAL_RELIEF_EVERY` of log. All panes share the store's log, so they share the
44/// count; whoever crosses the line resets it.
45fn relief_due(pending: &AtomicI64, start: i64, len: usize) -> bool {
46    let cost = crate::backend::storage::filestore::append_log_cost(start, len);
47    if pending.fetch_add(cost, Ordering::Relaxed) + cost < WAL_RELIEF_EVERY {
48        return false;
49    }
50    pending.store(0, Ordering::Relaxed);
51    true
52}
53
54/// The pass just made left log behind: the next one is due after
55/// `WAL_RELIEF_RETRY` of log, not a whole `WAL_RELIEF_EVERY`.
56fn relief_left_behind(pending: &AtomicI64) {
57    pending.fetch_add(WAL_RELIEF_EVERY - WAL_RELIEF_RETRY, Ordering::Relaxed);
58}
59
60/// The cap in bytes; 0 means no limit.
61pub fn cap_bytes() -> i64 {
62    CAP_BYTES.load(Ordering::Relaxed)
63}
64
65/// Take the setting's value (`None`: not set, or not a whole number of
66/// megabytes, which means the default). Called whenever settings change.
67pub fn apply_setting(value: Option<&serde_json::Value>) {
68    CAP_BYTES.store(cap_from_setting(value), Ordering::Relaxed);
69}
70
71fn cap_from_setting(value: Option<&serde_json::Value>) -> i64 {
72    let mb = match value.and_then(serde_json::Value::as_i64) {
73        Some(mb) if mb >= 0 => mb.min(MAX_MB),
74        _ => DEFAULT_MB,
75    };
76    mb * MIB
77}
78
79/// The options a new `term` file is made with.
80pub fn term_opts() -> FileOpts {
81    opts_for(cap_bytes())
82}
83
84fn opts_for(cap: i64) -> FileOpts {
85    FileOpts { circular: cap > 0, maxsize: cap, ..Default::default() }
86}
87
88/// After `data` was appended to a pane's `term` at offset `start`: bring the
89/// file to the cap, and drop the parts that fell out of its window. Returns
90/// true when output has been dropped from the file and not yet announced, and
91/// `data` ends where a line of text can be inserted (not inside a character or
92/// an escape sequence, which the next read of the PTY continues), so the caller
93/// can write [`TRIMMED_NOTICE`] after it. At a bad boundary the notice waits
94/// for a later append. A store error is logged and costs nothing but the trim.
95pub fn after_append(fs: &FileStore, block_id: &str, start: i64, data: &[u8]) -> bool {
96    after_append_capped(fs, block_id, start, data, cap_bytes())
97}
98
99/// Whether text can be written after `data` without cutting something the PTY's
100/// next bytes continue: a UTF-8 character, or an escape sequence (CSI, OSC and
101/// the other string sequences, or an escape that wants a final byte). Looks back
102/// a bounded distance for the last escape, so a string sequence that began
103/// further back than that counts as finished.
104pub(super) fn ends_at_boundary(data: &[u8]) -> bool {
105    const LOOK_BACK: usize = 256;
106    let n = data.len();
107    for back in 1..=3.min(n) {
108        let b = data[n - back];
109        if b & 0xC0 == 0x80 {
110            continue; // a continuation byte: the character's start is further back
111        }
112        let width = match b {
113            0xF0..=0xFF => 4,
114            0xE0..=0xEF => 3,
115            0xC0..=0xDF => 2,
116            _ => 1,
117        };
118        if width > back {
119            return false;
120        }
121        break;
122    }
123    let Some(esc) = data[n.saturating_sub(LOOK_BACK)..].iter().rposition(|&b| b == 0x1b) else {
124        return true;
125    };
126    let seq = &data[n.saturating_sub(LOOK_BACK) + esc..];
127    match seq.get(1) {
128        None => false,
129        Some(b'[') => seq[2..].iter().any(|b| (0x40..=0x7e).contains(b)),
130        Some(b']' | b'P' | b'X' | b'^' | b'_') => seq[2..].iter().enumerate().any(|(i, &b)| b == 0x07 || (b == 0x1b && seq[2..].get(i + 1) == Some(&b'\\'))),
131        Some(0x20..=0x2f) => seq.len() >= 3,
132        Some(_) => true,
133    }
134}
135
136fn after_append_capped(fs: &FileStore, block_id: &str, start: i64, data: &[u8], cap: i64) -> bool {
137    let len = data.len();
138    // Under a flood the log would only grow: empty it every few megabytes.
139    if relief_due(&LOG_SINCE_RELIEF, start, len) {
140        match fs.checkpoint_between_writes() {
141            Ok(true) => {}
142            Ok(false) => relief_left_behind(&LOG_SINCE_RELIEF),
143            Err(e) => {
144                tracing::debug!(error = %e, "term cap: checkpoint between writes failed");
145                relief_left_behind(&LOG_SINCE_RELIEF);
146            }
147        }
148    }
149    let mut trim = false;
150    let current = match fs.stat(block_id, TERM_FILE) {
151        Ok(Some(f)) => f,
152        Ok(None) => return false,
153        Err(e) => {
154            tracing::warn!(block_id = %block_id, error = %e, "term cap: stat failed");
155            return false;
156        }
157    };
158    // A file made before the cap, or under another setting, is brought over.
159    if current.opts.circular != (cap > 0) || current.opts.maxsize != cap {
160        match fs.set_circular(block_id, TERM_FILE, cap) {
161            Ok(changed) => trim = changed,
162            Err(e) => {
163                tracing::warn!(block_id = %block_id, error = %e, "term cap: could not set the limit");
164                return false;
165            }
166        }
167    }
168    let start = start.max(0);
169    let first_dead_before = fs_first_live(start, cap);
170    if fs_first_live(start + len as i64, cap) > first_dead_before {
171        trim = true;
172    }
173    let announced = current.meta.get("trimmed").and_then(serde_json::Value::as_bool) == Some(true);
174    let mut removed = 0;
175    if trim && cap > 0 {
176        match fs.trim_circular_head(block_id, TERM_FILE) {
177            Ok(n) => removed = n,
178            Err(e) => {
179                tracing::warn!(block_id = %block_id, error = %e, "term cap: trim failed");
180                return false;
181            }
182        }
183    }
184    // Output actually deleted (now, or by an earlier append that wasn't at a
185    // boundary) is announced once, at the first boundary where text fits. A
186    // file merely converted to the cap, or under a wider one, lost nothing.
187    let dropped = removed > 0 || current.meta.contains_key(crate::backend::storage::filestore::RETAINED_FROM_KEY);
188    if announced || !dropped || !ends_at_boundary(data) {
189        return false;
190    }
191    let mut meta = crate::backend::storage::filestore::FileMeta::new();
192    meta.insert("trimmed".to_string(), serde_json::Value::Bool(true));
193    if let Err(e) = fs.write_meta(block_id, TERM_FILE, meta, true) {
194        tracing::warn!(block_id = %block_id, error = %e, "term cap: could not note the trim");
195        return false;
196    }
197    true
198}
199
200fn fs_first_live(size: i64, cap: i64) -> i32 {
201    crate::backend::storage::filestore::first_live_part(size, cap)
202}
203
204#[cfg(test)]
205#[path = "tests_term_cap.rs"]
206mod tests;