1use crate::cli::ndjson::{self, Formatter};
5use std::collections::HashMap;
6use std::fs::File;
7use std::io::{IsTerminal, Read, Seek, SeekFrom, Write};
8use std::path::{Path, PathBuf};
9use std::time::{Duration, SystemTime};
10
11const BACKLOG_BYTES: u64 = 64 * 1024;
13
14struct Tail {
15 path: PathBuf,
16 offset: u64,
17 partial: Vec<u8>,
18 skip_first: bool,
19 formatter: Formatter,
20}
21
22impl Tail {
23 fn open(path: PathBuf, color: bool) -> Self {
24 let len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
25 let offset = len.saturating_sub(BACKLOG_BYTES);
26 Self {
27 path,
28 offset,
29 partial: Vec::new(),
30 skip_first: offset > 0,
31 formatter: Formatter::new(color),
32 }
33 }
34
35 fn read_lines(&mut self) -> Vec<String> {
37 let mut buf = Vec::new();
38 let read = File::open(&self.path).and_then(|mut f| {
39 f.seek(SeekFrom::Start(self.offset))?;
40 f.read_to_end(&mut buf)
41 });
42 let Ok(n) = read else {
43 return vec![];
44 };
45
46 self.offset += n as u64;
47 self.partial.extend_from_slice(&buf);
48 let Some(end) = self.partial.iter().rposition(|&b| b == b'\n') else {
49 return vec![];
50 };
51
52 let rest = self.partial.split_off(end + 1);
53 let complete = std::mem::replace(&mut self.partial, rest);
54 let mut lines: Vec<String> = String::from_utf8_lossy(&complete)
55 .lines()
56 .map(String::from)
57 .collect();
58 if std::mem::take(&mut self.skip_first) && !lines.is_empty() {
60 lines.remove(0);
61 }
62
63 lines
64 }
65}
66
67pub async fn run(task_id: Option<&str>, formatted: bool) -> anyhow::Result<()> {
69 let color = formatted && std::io::stdout().is_terminal();
70 let watched = match task_id {
71 Some(id) => {
72 println!("Watching task {id}. Ctrl+C to stop");
73 Some(Watched::resolve(id).await?)
74 }
75 None => {
76 println!("Watching all running agents. Ctrl+C to stop");
77 None
78 }
79 };
80
81 let mut tails: HashMap<String, Tail> = HashMap::new();
82 let mut colors: HashMap<String, &str> = HashMap::new();
83 let mut tag_width = 0;
84 let mut said_waiting = false;
85 loop {
86 let found = match &watched {
87 Some(task) => task.sources(),
88 None => session_sources().await,
89 };
90 if let (Some(task), true, false) = (&watched, found.is_empty(), said_waiting) {
91 println!("{}", task.nothing_yet());
92 said_waiting = true;
93 }
94
95 let live: Vec<String> = found.iter().map(|(key, _)| key.clone()).collect();
96 for (key, path) in found {
97 let tail = tails
98 .entry(key)
99 .or_insert_with(|| Tail::open(path.clone(), color));
100 if tail.path != path {
101 *tail = Tail::open(path, color);
102 }
103 }
104
105 for tail in tails.values_mut() {
107 let mut entries = Vec::new();
108 for line in tail.read_lines() {
109 if formatted {
110 entries.extend(tail.formatter.format(&line));
111 } else {
112 entries.push(line);
113 }
114 }
115 if entries.is_empty() {
116 continue;
117 }
118
119 let tag = tag(&tail.path);
121 tag_width = tag_width.max(tag.chars().count());
122 let next = TAG_COLORS[colors.len() % TAG_COLORS.len()];
123 let code = *colors.entry(key_of(&tail.path)).or_insert(next);
124 let gutter = |show: bool| {
125 let text = if show { tag.as_str() } else { "" };
126 let text = format!("{text:<tag_width$} │");
127 if color {
128 format!("\x1b[{code}m{text}\x1b[0m")
129 } else {
130 text
131 }
132 };
133 for line in tag_lines(&entries, formatted, gutter) {
134 println!("{line}");
135 }
136 }
137 tails.retain(|key, _| live.contains(key));
138
139 std::io::stdout().flush()?;
140 tokio::time::sleep(Duration::from_secs(1)).await;
141 }
142}
143
144struct Watched {
146 id: String,
147 status: String,
148 dirs: Vec<PathBuf>,
150}
151
152impl Watched {
153 async fn resolve(id: &str) -> anyhow::Result<Self> {
154 let store = crate::cli::init_store().await?;
155 let id = id.strip_suffix("-review").unwrap_or(id);
157 let task = crate::cli::task_ref::resolve(&store, id).await?;
158 Ok(Self {
159 id: task.display_spec(),
160 status: task.status.clone(),
161 dirs: crate::cli::task_ref::state_dirs(&task)?,
162 })
163 }
164
165 fn sources(&self) -> Vec<(String, PathBuf)> {
166 newest_output(&self.dirs)
167 .map(|path| (self.id.clone(), path))
168 .into_iter()
169 .collect()
170 }
171
172 fn nothing_yet(&self) -> String {
174 if self.status != crate::store::TaskStatus::InProgress.as_str() {
175 return format!(
176 "No output for task {} yet, waiting for it to start",
177 self.id
178 );
179 }
180
181 let searched: Vec<String> = self
182 .dirs
183 .iter()
184 .map(|dir| dir.join("attempts").display().to_string())
185 .collect();
186 format!(
187 "Task {} is in_progress but no output file was found under {}",
188 self.id,
189 searched.join(" or ")
190 )
191 }
192}
193
194async fn session_sources() -> Vec<(String, PathBuf)> {
196 let tmux = crate::tmux::TmuxManager::new();
197 crate::channels::tmux::list_orch_sessions()
198 .await
199 .unwrap_or_default()
200 .into_iter()
201 .filter_map(|session| {
202 let (project, task) = tmux.parse_session_name(&session)?;
203 let path = session_output(&project, &task_dir_name(&task))?;
204 Some((session, path))
205 })
206 .collect()
207}
208
209fn task_dir_name(task: &str) -> String {
211 match task.strip_prefix("internal-") {
212 Some(rest) => format!("internal:{rest}"),
213 None => task.to_string(),
214 }
215}
216
217fn session_output(project: &str, name: &str) -> Option<PathBuf> {
219 let state = crate::home::state_dir().ok()?;
220 let dirs: Vec<PathBuf> = subdirs(&state)
221 .iter()
222 .flat_map(|owner| subdirs(owner))
223 .filter(|repo| repo.file_name() == Some(project.as_ref()))
224 .map(|repo| repo.join("tasks").join(name))
225 .collect();
226 newest_output(&dirs)
227}
228
229fn newest_output(dirs: &[PathBuf]) -> Option<PathBuf> {
231 let mut best: Option<(SystemTime, PathBuf)> = None;
232 for dir in dirs {
233 for attempt in subdirs(&dir.join("attempts")) {
234 let output = attempt.join("output.json");
235 let Ok(modified) = output.metadata().and_then(|m| m.modified()) else {
236 continue;
237 };
238 if best.as_ref().is_none_or(|(t, _)| modified > *t) {
239 best = Some((modified, output));
240 }
241 }
242 }
243
244 best.map(|(_, p)| p)
245}
246
247fn subdirs(dir: &Path) -> Vec<PathBuf> {
248 std::fs::read_dir(dir)
249 .into_iter()
250 .flatten()
251 .flatten()
252 .map(|e| e.path())
253 .filter(|p| p.is_dir())
254 .collect()
255}
256
257const TAG_COLORS: [&str; 6] = ["36", "35", "33", "34", "96", "95"];
258
259fn tag_lines(entries: &[String], formatted: bool, gutter: impl Fn(bool) -> String) -> Vec<String> {
261 let mut out = Vec::new();
262 for entry in entries {
263 let step = !formatted || !entry.starts_with(ndjson::RESULT_PREFIX);
264 if formatted && step {
265 out.push(gutter(false));
266 }
267
268 for (i, line) in entry.lines().enumerate() {
269 out.push(format!("{} {line}", gutter(step && i == 0)));
270 }
271 }
272 out
273}
274
275fn tag(path: &Path) -> String {
277 match path_parts(path).as_slice() {
278 [attempt, _, task, _, repo] => {
279 let task = task.strip_prefix("internal:").unwrap_or(task);
280 format!("{repo}#{task} a{attempt}")
281 }
282 _ => path.display().to_string(),
283 }
284}
285
286fn key_of(path: &Path) -> String {
288 path.ancestors()
289 .nth(3)
290 .map_or_else(String::new, |p| p.display().to_string())
291}
292
293fn path_parts(path: &Path) -> Vec<String> {
294 path.iter()
295 .rev()
296 .skip(1)
297 .take(5)
298 .map(|p| p.to_string_lossy().into_owned())
299 .collect()
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn tail_returns_only_complete_lines() {
308 let dir = tempfile::tempdir().unwrap();
309 let path = dir.path().join("output.json");
310 std::fs::write(&path, "one\ntw").unwrap();
311 let mut tail = Tail::open(path.clone(), false);
312 assert_eq!(tail.read_lines(), vec!["one"]);
313
314 let mut f = std::fs::OpenOptions::new()
315 .append(true)
316 .open(&path)
317 .unwrap();
318 f.write_all(b"o\nthree\n").unwrap();
319 assert_eq!(tail.read_lines(), vec!["two", "three"]);
320 assert!(tail.read_lines().is_empty());
321 }
322
323 #[test]
324 fn tail_skips_cut_line_in_backlog() {
325 let dir = tempfile::tempdir().unwrap();
326 let path = dir.path().join("output.json");
327 let long = "x".repeat(BACKLOG_BYTES as usize);
328 std::fs::write(&path, format!("{long}\nlast\n")).unwrap();
329 assert_eq!(Tail::open(path, false).read_lines(), vec!["last"]);
330 }
331
332 #[test]
333 fn task_dir_name_restores_internal_colon() {
334 assert_eq!(task_dir_name("internal-8-review"), "internal:8-review");
335 assert_eq!(task_dir_name("3601"), "3601");
336 }
337
338 #[test]
339 fn in_progress_without_output_names_the_path() {
340 let watched = Watched {
341 id: "owner/repo#5".to_string(),
342 status: crate::store::TaskStatus::InProgress.as_str().to_string(),
343 dirs: vec![
344 PathBuf::from("/state/owner/repo/tasks/5-review"),
345 PathBuf::from("/state/owner/repo/tasks/5"),
346 ],
347 };
348 let msg = watched.nothing_yet();
349 assert!(msg.contains("in_progress"), "{msg}");
350 assert!(msg.contains("/state/owner/repo/tasks/5/attempts"), "{msg}");
351 assert!(
352 msg.contains("/state/owner/repo/tasks/5-review/attempts"),
353 "{msg}"
354 );
355
356 let waiting = Watched {
357 status: crate::store::TaskStatus::Routed.as_str().to_string(),
358 ..watched
359 };
360 let msg = waiting.nothing_yet();
361 assert!(msg.contains("waiting for it to start"), "{msg}");
362 assert!(!msg.contains("no output file was found"), "{msg}");
363 }
364
365 #[test]
366 fn newest_output_picks_the_latest_attempt() {
367 let dir = tempfile::tempdir().unwrap();
368 let task = dir.path().join("tasks").join("5");
369 for attempt in ["1", "2"] {
370 let d = task.join("attempts").join(attempt);
371 std::fs::create_dir_all(&d).unwrap();
372 std::fs::write(d.join("output.json"), attempt).unwrap();
373 std::thread::sleep(Duration::from_millis(10));
375 }
376 let found = newest_output(&[task.join("5-review"), task.clone()]).unwrap();
377 assert_eq!(found, task.join("attempts").join("2").join("output.json"));
378 assert!(newest_output(&[dir.path().join("missing")]).is_none());
379 }
380
381 #[test]
382 fn tag_drops_internal_prefix() {
383 let path = Path::new("/s/owner/bean/tasks/internal:189488-review/attempts/1/output.json");
384 assert_eq!(tag(path), "bean#189488-review a1");
385 assert_eq!(key_of(path), "/s/owner/bean/tasks/internal:189488-review");
386 }
387
388 #[test]
389 fn tag_lines_label_each_step_only() {
390 let entries = vec![
391 "⏺ Read(a.rs)".to_string(),
392 " ⎿ Read 3 lines".to_string(),
393 "⏺ Fixing it.\n Then test.".to_string(),
394 ];
395 let gutter = |show: bool| if show { "t1 │" } else { " │" }.to_string();
396 assert_eq!(
397 tag_lines(&entries, true, gutter),
398 vec![
399 " │",
400 "t1 │ ⏺ Read(a.rs)",
401 " │ ⎿ Read 3 lines",
402 " │",
403 "t1 │ ⏺ Fixing it.",
404 " │ Then test.",
405 ]
406 );
407 }
408
409 #[test]
410 fn tag_lines_raw_tags_every_line() {
411 let entries = vec!["{\"a\":1}".to_string(), "{\"b\":2}".to_string()];
412 let gutter = |show: bool| if show { "t │" } else { " │" }.to_string();
413 assert_eq!(
414 tag_lines(&entries, false, gutter),
415 vec!["t │ {\"a\":1}", "t │ {\"b\":2}"]
416 );
417 }
418}