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