use std::io::{self, Write};
use std::sync::{Mutex, OnceLock};
const CAP: usize = 2_000;
#[derive(Default)]
struct Buffer {
lines: Option<Vec<String>>,
partial: String,
dropped: usize,
}
fn buffer() -> &'static Mutex<Buffer> {
static B: OnceLock<Mutex<Buffer>> = OnceLock::new();
B.get_or_init(Mutex::default)
}
pub fn capture() {
if let Ok(mut b) = buffer().lock() {
b.lines.get_or_insert_with(Vec::new);
}
}
pub fn drain() -> Vec<String> {
let Ok(mut b) = buffer().lock() else {
return Vec::new();
};
let dropped = std::mem::take(&mut b.dropped);
let mut out = b.lines.as_mut().map(std::mem::take).unwrap_or_default();
if dropped > 0 {
out.insert(
0,
format!("{dropped} earlier log line(s) dropped — the buffer is {CAP} lines"),
);
}
out
}
pub fn release() -> Vec<String> {
let mut out = drain();
if let Ok(mut b) = buffer().lock() {
let tail = std::mem::take(&mut b.partial);
if !tail.trim().is_empty() {
out.push(tail.trim_end().to_string());
}
b.lines = None;
}
out
}
pub struct Writer;
impl Write for Writer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let Ok(mut b) = buffer().lock() else {
return io::stderr().write(buf);
};
if b.lines.is_none() {
drop(b);
return io::stderr().write(buf);
}
b.partial.push_str(&String::from_utf8_lossy(buf));
let mut ready: Vec<String> = Vec::new();
while let Some(i) = b.partial.find('\n') {
let line: String = b.partial.drain(..=i).collect();
let line = strip_ansi(line.trim_end());
if !line.is_empty() {
ready.push(line);
}
}
if let Some(held) = b.lines.as_mut() {
held.extend(ready);
if held.len() > CAP {
let over = held.len() - CAP;
held.drain(..over);
b.dropped += over;
}
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c != '\u{1b}' {
out.push(c);
continue;
}
match chars.next() {
Some('[') => {
for c in chars.by_ref() {
if ('@'..='~').contains(&c) {
break;
}
}
}
Some(']') => {
for c in chars.by_ref() {
if c == '\u{7}' {
break;
}
}
}
_ => {}
}
}
out
}
#[derive(Clone, Copy)]
pub struct Make;
impl tracing_subscriber::fmt::MakeWriter<'_> for Make {
type Writer = Writer;
fn make_writer(&self) -> Writer {
Writer
}
}
pub fn is_alarming(line: &str) -> bool {
let head = line.trim_start();
head.starts_with("ERROR") || head.starts_with("WARN")
}
#[cfg(test)]
mod tests {
use super::*;
fn lock() -> std::sync::MutexGuard<'static, ()> {
static L: OnceLock<Mutex<()>> = OnceLock::new();
L.get_or_init(Mutex::default)
.lock()
.unwrap_or_else(|e| e.into_inner())
}
#[test]
fn nothing_is_held_until_someone_takes_the_screen() {
let _g = lock();
let _ = release();
let _ = Writer.write(b"WARN this belongs on the terminal\n");
assert!(drain().is_empty());
}
#[test]
fn a_line_split_across_writes_is_reassembled() {
let _g = lock();
let _ = release();
capture();
let _ = Writer.write(b"WARN mecha_core::agent: the run finished on a ");
assert!(drain().is_empty());
let _ = Writer.write(b"failed tool call\nDEBUG next\n");
assert_eq!(
drain(),
vec![
"WARN mecha_core::agent: the run finished on a failed tool call".to_string(),
"DEBUG next".to_string(),
]
);
let _ = release();
}
#[test]
fn an_unterminated_line_survives_the_handback() {
let _g = lock();
let _ = release();
capture();
let _ = Writer.write(b"ERROR half a thought");
let left = release();
assert_eq!(left, vec!["ERROR half a thought".to_string()]);
}
#[test]
fn overflow_drops_the_oldest_and_says_how_many() {
let _g = lock();
let _ = release();
capture();
for i in 0..CAP + 5 {
let _ = Writer.write(format!("DEBUG line {i}\n").as_bytes());
}
let out = drain();
assert_eq!(out.len(), CAP + 1);
assert!(out[0].starts_with("5 earlier log line(s) dropped"));
assert_eq!(out[1], "DEBUG line 5");
let _ = release();
}
#[test]
fn colour_is_stripped_before_a_line_becomes_a_transcript_entry() {
let raw = "\u{1b}[33m WARN\u{1b}[0m \u{1b}[2mmecha_core::agent\u{1b}[0m\u{1b}[2m:\u{1b}[0m ended on a failed call";
assert_eq!(
strip_ansi(raw),
" WARN mecha_core::agent: ended on a failed call"
);
assert!(is_alarming(&strip_ansi(raw)));
}
#[test]
fn an_escape_is_never_left_half_stripped() {
assert_eq!(strip_ansi("a\u{1b}[31"), "a");
assert_eq!(strip_ansi("a\u{1b}"), "a");
assert_eq!(strip_ansi("plain text"), "plain text");
}
#[test]
fn only_warnings_and_errors_are_alarming() {
assert!(is_alarming("WARN mecha_core::agent: ..."));
assert!(is_alarming(" ERROR something"));
assert!(!is_alarming("DEBUG mecha_core::mcp: connected"));
assert!(!is_alarming(
"a bare line from something that is not tracing"
));
}
}