ertangle-adapter 1.8.0

Agent adapters (Claude Code, Codex, ACP) for ertangle
Documentation
//! Child process stderr collection: a fixed-size ring buffer keeping only the last few lines.
//!
//! stderr must be drained continuously, otherwise heavy agent output fills the pipe and blocks the agent.
//! On non-zero exit, these trailing lines are emitted as `Output` so the user can see the cause.

use crate::ansi::AnsiStripper;
use crate::AgentEvent;
use std::collections::VecDeque;
use std::io::Read;
use std::process::ChildStderr;
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tr::tr;

/// Maximum number of lines retained.
const MAX_LINES: usize = 20;
/// Maximum bytes retained per line (excess is discarded).
const MAX_LINE_BYTES: usize = 500;

#[derive(Default)]
struct Inner {
    lines: VecDeque<String>,
    cur: Vec<u8>,
}

impl Inner {
    fn push_text(&mut self, text: &str) {
        for ch in text.chars() {
            if ch == '\n' {
                self.end_line();
            } else if self.cur.len() < MAX_LINE_BYTES {
                let mut buf = [0u8; 4];
                self.cur
                    .extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
            }
        }
    }

    fn end_line(&mut self) {
        let line = String::from_utf8_lossy(&self.cur).trim_end().to_string();
        self.cur.clear();
        if line.is_empty() {
            return;
        }
        if self.lines.len() == MAX_LINES {
            self.lines.pop_front();
        }
        self.lines.push_back(line);
    }
}

/// Trailing lines of stderr.
pub struct StderrTail {
    inner: Arc<Mutex<Inner>>,
    done: Mutex<Receiver<()>>,
}

impl StderrTail {
    /// Spawn a reader thread to continuously drain stderr.
    pub fn spawn(mut stderr: ChildStderr) -> Arc<StderrTail> {
        let inner = Arc::new(Mutex::new(Inner::default()));
        let (done_tx, done_rx) = mpsc::channel();
        let shared = inner.clone();
        std::thread::spawn(move || {
            let mut strip = AnsiStripper::new();
            let mut buf = [0u8; 8192];
            // Split non-UTF-8 boundaries are handled by lossy decoding; the priority is not blocking the pipe.
            while let Ok(n) = stderr.read(&mut buf) {
                if n == 0 {
                    break;
                }
                let text = strip.feed(buf.get(..n).unwrap_or_default());
                shared
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .push_text(&text);
            }
            shared.lock().unwrap_or_else(|e| e.into_inner()).end_line();
            // Reader thread completion notice; ignore if the receiver timed out and dropped.
            let _ = done_tx.send(());
        });
        Arc::new(StderrTail {
            inner,
            done: Mutex::new(done_rx),
        })
    }

    /// Currently retained lines (oldest first).
    pub fn lines(&self) -> Vec<String> {
        self.inner
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .lines
            .iter()
            .cloned()
            .collect()
    }

    /// Call after process exit: briefly wait for the reader thread to finish; emit `Output` on non-zero exit if non-empty.
    pub fn report_exit(&self, code: Option<i32>, tx: &Sender<AgentEvent>) {
        // Wait for background stderr reader to finish; proceed even on timeout or channel error.
        let _ = self
            .done
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .recv_timeout(Duration::from_millis(500));
        if !matches!(code, Some(c) if c != 0) {
            return;
        }
        let lines = self.lines();
        if lines.is_empty() {
            return;
        }
        // Ignore output event if the receiver is already closed.
        let _ = tx.send(AgentEvent::Output(tr!(
            "⚠ 處理程序以結束碼 {code} 結束,stderr 最後 {count} 行:\n{lines}\n",
            code = code.unwrap_or(-1),
            count = lines.len(),
            lines = lines.join("\n")
        )));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keeps_only_last_lines_and_truncates_long_ones() {
        let mut i = Inner::default();
        for n in 0..50 {
            i.push_text(&format!("line {n}\n"));
        }
        i.push_text(&"x".repeat(5000));
        i.end_line();
        assert_eq!(i.lines.len(), MAX_LINES);
        assert_eq!(i.lines.front().unwrap(), "line 31");
        assert_eq!(i.lines.back().unwrap().len(), MAX_LINE_BYTES);
    }
}