Skip to main content

ertangle_adapter/
stderr.rs

1//! Child process stderr collection: a fixed-size ring buffer keeping only the last few lines.
2//!
3//! stderr must be drained continuously, otherwise heavy agent output fills the pipe and blocks the agent.
4//! On non-zero exit, these trailing lines are emitted as `Output` so the user can see the cause.
5
6use crate::ansi::AnsiStripper;
7use crate::AgentEvent;
8use std::collections::VecDeque;
9use std::io::Read;
10use std::process::ChildStderr;
11use std::sync::mpsc::{self, Receiver, Sender};
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14use tr::tr;
15
16/// Maximum number of lines retained.
17const MAX_LINES: usize = 20;
18/// Maximum bytes retained per line (excess is discarded).
19const MAX_LINE_BYTES: usize = 500;
20
21#[derive(Default)]
22struct Inner {
23    lines: VecDeque<String>,
24    cur: Vec<u8>,
25}
26
27impl Inner {
28    fn push_text(&mut self, text: &str) {
29        for ch in text.chars() {
30            if ch == '\n' {
31                self.end_line();
32            } else if self.cur.len() < MAX_LINE_BYTES {
33                let mut buf = [0u8; 4];
34                self.cur
35                    .extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
36            }
37        }
38    }
39
40    fn end_line(&mut self) {
41        let line = String::from_utf8_lossy(&self.cur).trim_end().to_string();
42        self.cur.clear();
43        if line.is_empty() {
44            return;
45        }
46        if self.lines.len() == MAX_LINES {
47            self.lines.pop_front();
48        }
49        self.lines.push_back(line);
50    }
51}
52
53/// Trailing lines of stderr.
54pub struct StderrTail {
55    inner: Arc<Mutex<Inner>>,
56    done: Mutex<Receiver<()>>,
57}
58
59impl StderrTail {
60    /// Spawn a reader thread to continuously drain stderr.
61    pub fn spawn(mut stderr: ChildStderr) -> Arc<StderrTail> {
62        let inner = Arc::new(Mutex::new(Inner::default()));
63        let (done_tx, done_rx) = mpsc::channel();
64        let shared = inner.clone();
65        std::thread::spawn(move || {
66            let mut strip = AnsiStripper::new();
67            let mut buf = [0u8; 8192];
68            // Split non-UTF-8 boundaries are handled by lossy decoding; the priority is not blocking the pipe.
69            while let Ok(n) = stderr.read(&mut buf) {
70                if n == 0 {
71                    break;
72                }
73                let text = strip.feed(buf.get(..n).unwrap_or_default());
74                shared
75                    .lock()
76                    .unwrap_or_else(|e| e.into_inner())
77                    .push_text(&text);
78            }
79            shared.lock().unwrap_or_else(|e| e.into_inner()).end_line();
80            // Reader thread completion notice; ignore if the receiver timed out and dropped.
81            let _ = done_tx.send(());
82        });
83        Arc::new(StderrTail {
84            inner,
85            done: Mutex::new(done_rx),
86        })
87    }
88
89    /// Currently retained lines (oldest first).
90    pub fn lines(&self) -> Vec<String> {
91        self.inner
92            .lock()
93            .unwrap_or_else(|e| e.into_inner())
94            .lines
95            .iter()
96            .cloned()
97            .collect()
98    }
99
100    /// Call after process exit: briefly wait for the reader thread to finish; emit `Output` on non-zero exit if non-empty.
101    pub fn report_exit(&self, code: Option<i32>, tx: &Sender<AgentEvent>) {
102        // Wait for background stderr reader to finish; proceed even on timeout or channel error.
103        let _ = self
104            .done
105            .lock()
106            .unwrap_or_else(|e| e.into_inner())
107            .recv_timeout(Duration::from_millis(500));
108        if !matches!(code, Some(c) if c != 0) {
109            return;
110        }
111        let lines = self.lines();
112        if lines.is_empty() {
113            return;
114        }
115        // Ignore output event if the receiver is already closed.
116        let _ = tx.send(AgentEvent::Output(tr!(
117            "⚠ 處理程序以結束碼 {code} 結束,stderr 最後 {count} 行:\n{lines}\n",
118            code = code.unwrap_or(-1),
119            count = lines.len(),
120            lines = lines.join("\n")
121        )));
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn keeps_only_last_lines_and_truncates_long_ones() {
131        let mut i = Inner::default();
132        for n in 0..50 {
133            i.push_text(&format!("line {n}\n"));
134        }
135        i.push_text(&"x".repeat(5000));
136        i.end_line();
137        assert_eq!(i.lines.len(), MAX_LINES);
138        assert_eq!(i.lines.front().unwrap(), "line 31");
139        assert_eq!(i.lines.back().unwrap().len(), MAX_LINE_BYTES);
140    }
141}