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(std::string::ToString::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::Error { code, message }) => {
78            eprintln!("error: {}", message);
79            code
80        }
81        Ok(_) => 0,
82        Err(e) => {
83            eprintln!("error: {}", e);
84            1
85        }
86    }
87}
88
89fn show_all_logs(log_dir: &std::path::Path, tail: usize) -> i32 {
90    let entries = match std::fs::read_dir(log_dir) {
91        Ok(e) => e,
92        Err(e) => {
93            eprintln!("error: cannot read log dir: {}", e);
94            return 1;
95        }
96    };
97
98    let mut all_lines: Vec<(String, String)> = Vec::new();
99    for entry in entries.flatten() {
100        let name = entry.file_name().to_string_lossy().to_string();
101        if !name.ends_with(".stdout") {
102            continue;
103        }
104        let proc_name = name.trim_end_matches(".stdout").to_string();
105        if let Ok(lines) = tail_file(&entry.path(), tail) {
106            for line in lines {
107                all_lines.push((proc_name.clone(), line));
108            }
109        }
110    }
111
112    for (proc_name, line) in &all_lines {
113        println!("[{}] {}", proc_name, line);
114    }
115    0
116}
117
118fn tail_file(path: &std::path::Path, n: usize) -> std::io::Result<Vec<String>> {
119    let file = File::open(path)?;
120    // Use a ring buffer to keep only the last N lines in memory
121    let mut ring: std::collections::VecDeque<String> = std::collections::VecDeque::with_capacity(n);
122    for line in BufReader::new(file).lines() {
123        let line = line?;
124        if ring.len() == n {
125            ring.pop_front();
126        }
127        ring.push_back(line);
128    }
129    Ok(ring.into_iter().collect())
130}