Skip to main content

agent_procs/cli/
logs.rs

1use crate::paths;
2use crate::protocol::{Request, Response};
3use std::fs::File;
4use std::io::{BufRead, BufReader};
5
6#[allow(clippy::too_many_arguments)]
7pub async fn execute(
8    session: &str,
9    target: Option<&str>,
10    tail: usize,
11    follow: bool,
12    stderr: bool,
13    all: bool,
14    timeout: Option<u64>,
15    lines: Option<usize>,
16) -> i32 {
17    if follow {
18        return execute_follow(session, target, all, timeout, lines).await;
19    }
20
21    // Non-follow: read from disk (unchanged)
22    let log_dir = paths::log_dir(session);
23
24    if all || target.is_none() {
25        return show_all_logs(&log_dir, tail);
26    }
27
28    let target = target.unwrap();
29    let stream = if stderr { "stderr" } else { "stdout" };
30    let path = log_dir.join(format!("{}.{}", target, stream));
31
32    match tail_file(&path, tail) {
33        Ok(lines) => {
34            for line in lines {
35                println!("{}", line);
36            }
37            0
38        }
39        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
40            eprintln!("error: no logs for process '{}' ({})", target, stream);
41            2
42        }
43        Err(e) => {
44            eprintln!("error reading logs: {}", e);
45            1
46        }
47    }
48}
49
50async fn execute_follow(
51    session: &str,
52    target: Option<&str>,
53    all: bool,
54    timeout: Option<u64>,
55    lines: Option<usize>,
56) -> i32 {
57    let req = Request::Logs {
58        target: target.map(|t| t.to_string()),
59        tail: 0,
60        follow: true,
61        stderr: false,
62        all: all || target.is_none(),
63        timeout_secs: timeout.or(Some(30)), // CLI default; TUI passes None for infinite
64        lines,
65    };
66
67    let show_prefix = all || target.is_none();
68    match crate::cli::stream_responses(session, &req, false, |process, _stream, line| {
69        if show_prefix {
70            println!("[{}] {}", process, line);
71        } else {
72            println!("{}", line);
73        }
74    })
75    .await
76    {
77        Ok(Response::LogEnd) => 0,
78        Ok(Response::Error { code, message }) => {
79            eprintln!("error: {}", message);
80            code
81        }
82        Ok(_) => 0,
83        Err(e) => {
84            eprintln!("error: {}", e);
85            1
86        }
87    }
88}
89
90fn show_all_logs(log_dir: &std::path::Path, tail: usize) -> i32 {
91    let entries = match std::fs::read_dir(log_dir) {
92        Ok(e) => e,
93        Err(e) => {
94            eprintln!("error: cannot read log dir: {}", e);
95            return 1;
96        }
97    };
98
99    let mut all_lines: Vec<(String, String)> = Vec::new();
100    for entry in entries.flatten() {
101        let name = entry.file_name().to_string_lossy().to_string();
102        if !name.ends_with(".stdout") {
103            continue;
104        }
105        let proc_name = name.trim_end_matches(".stdout").to_string();
106        if let Ok(lines) = tail_file(&entry.path(), tail) {
107            for line in lines {
108                all_lines.push((proc_name.to_string(), line));
109            }
110        }
111    }
112
113    for (proc_name, line) in &all_lines {
114        println!("[{}] {}", proc_name, line);
115    }
116    0
117}
118
119fn tail_file(path: &std::path::Path, n: usize) -> std::io::Result<Vec<String>> {
120    let file = File::open(path)?;
121    // Use a ring buffer to keep only the last N lines in memory
122    let mut ring: std::collections::VecDeque<String> = std::collections::VecDeque::with_capacity(n);
123    for line in BufReader::new(file).lines() {
124        let line = line?;
125        if ring.len() == n {
126            ring.pop_front();
127        }
128        ring.push_back(line);
129    }
130    Ok(ring.into_iter().collect())
131}