1use crate::channels::tmux;
5use crate::cli;
6use crate::cli::task::reference;
7use crate::engine::runner::ndjson::{self, Formatter};
8use crate::store::cluster;
9use crate::store::cluster::discovery;
10use crate::store::cluster::local::{self, Endpoint};
11use crate::store::cluster::output::{Cursor, Output};
12use crate::store::{Task, TaskStatus, TaskStore};
13use crate::sys::home;
14use crate::sys::tmux::TmuxManager;
15use std::collections::HashMap;
16use std::fs::File;
17use std::io::{IsTerminal, Read, Seek, SeekFrom, Write};
18use std::path::{Path, PathBuf};
19use std::time::{Duration, SystemTime};
20
21use tokio::time;
22
23use std::fs;
24use std::io;
25use std::mem;
26
27const BACKLOG_BYTES: u64 = 64 * 1024;
29
30pub(crate) struct Tail {
31 path: PathBuf,
32 offset: u64,
33 partial: Vec<u8>,
34 skip_first: bool,
35 formatter: Formatter,
36}
37
38impl Tail {
39 pub(crate) fn read_entries(&mut self, formatted: bool) -> Vec<String> {
41 let mut entries = Vec::new();
42 for line in self.read_lines() {
43 if formatted {
44 entries.extend(self.formatter.format(&line));
45 } else {
46 entries.push(line);
47 }
48 }
49 entries
50 }
51
52 pub(crate) fn open(path: PathBuf, color: bool) -> Self {
53 let len = fs::metadata(&path).map_or(0, |m| m.len());
54 let offset = len.saturating_sub(BACKLOG_BYTES);
55 Self {
56 path,
57 offset,
58 partial: Vec::new(),
59 skip_first: offset > 0,
60 formatter: Formatter::new(color),
61 }
62 }
63
64 pub(crate) fn open_at_end(path: PathBuf) -> Self {
66 let offset = fs::metadata(&path).map_or(0, |m| m.len());
67 Self {
68 path,
69 offset,
70 partial: Vec::new(),
71 skip_first: false,
72 formatter: Formatter::new(false),
73 }
74 }
75
76 pub(crate) fn shrank(&self) -> bool {
78 fs::metadata(&self.path).is_ok_and(|m| m.len() < self.offset)
79 }
80
81 pub(crate) fn read_lines(&mut self) -> Vec<String> {
83 let mut buf = Vec::new();
84 let read = File::open(&self.path).and_then(|mut f| {
85 f.seek(SeekFrom::Start(self.offset))?;
86 f.read_to_end(&mut buf)
87 });
88 let Ok(n) = read else {
89 return vec![];
90 };
91
92 self.offset += n as u64;
93 self.partial.extend_from_slice(&buf);
94 let Some(end) = self.partial.iter().rposition(|&b| b == b'\n') else {
95 return vec![];
96 };
97
98 let rest = self.partial.split_off(end + 1);
99 let complete = mem::replace(&mut self.partial, rest);
100 let mut lines: Vec<String> = String::from_utf8_lossy(&complete)
101 .lines()
102 .map(String::from)
103 .collect();
104 if mem::take(&mut self.skip_first) && !lines.is_empty() {
106 lines.remove(0);
107 }
108
109 lines
110 }
111}
112
113pub async fn run(task_id: Option<&str>, formatted: bool) -> anyhow::Result<()> {
115 let color = formatted && io::stdout().is_terminal();
116 let watched = if let Some(id) = task_id {
117 println!("Watching task {id}. Ctrl+C to stop");
118 Some(Watched::resolve(id).await?)
119 } else {
120 println!("Watching all running agents. Ctrl+C to stop");
121 None
122 };
123 let daemon = if cluster::enabled() {
125 local::daemon_endpoint().await
126 } else {
127 None
128 };
129 if let (Some(task), Some(endpoint)) = (&watched, &daemon) {
130 return follow_remote(task, endpoint, formatted, color).await;
131 }
132
133 let others = match daemon {
134 Some(endpoint) => Some(Others::new(endpoint).await?),
135 None => None,
136 };
137 follow_local(watched.as_ref(), others, formatted, color).await
138}
139
140async fn follow_local(
141 watched: Option<&Watched>,
142 mut others: Option<Others>,
143 formatted: bool,
144 color: bool,
145) -> anyhow::Result<()> {
146 let mut tails: HashMap<String, Tail> = HashMap::new();
147 let mut printer = Printer::new(formatted, color);
148 let mut said_waiting = false;
149 loop {
150 let found = match watched {
151 Some(task) => task.sources(),
152 None => session_sources().await,
153 };
154 if let (Some(task), true, false) = (watched, found.is_empty(), said_waiting) {
155 println!("{}", task.nothing_yet());
156 said_waiting = true;
157 }
158
159 let live: Vec<String> = found.iter().map(|(key, _)| key.clone()).collect();
160 for (key, path) in found {
161 let tail = tails
162 .entry(key)
163 .or_insert_with(|| Tail::open(path.clone(), color));
164 if tail.path != path {
165 *tail = Tail::open(path, color);
166 }
167 }
168
169 for tail in tails.values_mut() {
171 let entries = tail.read_entries(formatted);
172 printer.print(&tail.path, &entries);
173 }
174 tails.retain(|key, _| live.contains(key));
175 if let Some(others) = others.as_mut() {
176 others.poll(&mut printer).await;
177 }
178
179 io::stdout().flush()?;
180 time::sleep(Duration::from_secs(1)).await;
181 }
182}
183
184struct Printer {
186 formatted: bool,
187 color: bool,
188 colors: HashMap<String, &'static str>,
189 tag_width: usize,
190}
191
192impl Printer {
193 fn new(formatted: bool, color: bool) -> Self {
194 Self {
195 formatted,
196 color,
197 colors: HashMap::new(),
198 tag_width: 0,
199 }
200 }
201
202 fn print(&mut self, path: &Path, entries: &[String]) {
203 if entries.is_empty() {
204 return;
205 }
206
207 let tag = tag(path);
208 self.tag_width = self.tag_width.max(tag.chars().count());
209 let next = TAG_COLORS[self.colors.len() % TAG_COLORS.len()];
210 let code = *self.colors.entry(key_of(path)).or_insert(next);
211 let (width, color) = (self.tag_width, self.color);
212 let gutter = |show: bool| {
213 let text = if show { tag.as_str() } else { "" };
214 let text = format!("{text:<width$} │");
215 if color {
216 format!("\x1b[{code}m{text}\x1b[0m")
217 } else {
218 text
219 }
220 };
221 for line in tag_lines(entries, self.formatted, gutter) {
222 println!("{line}");
223 }
224 }
225}
226
227struct Remote {
229 cursor: Cursor,
230 formatter: Formatter,
231}
232
233impl Remote {
234 fn new(task: i64, color: bool) -> Self {
235 Self {
236 cursor: Cursor {
237 task,
238 ..Cursor::default()
239 },
240 formatter: Formatter::new(color),
241 }
242 }
243
244 async fn read(
246 &mut self,
247 endpoint: &Endpoint,
248 formatted: bool,
249 color: bool,
250 ) -> anyhow::Result<Fetched> {
251 let chunk = match local::fetch_output(endpoint, &self.cursor).await? {
252 Output::Lines(chunk) => chunk,
253 Output::Offline { node } => return Ok(Fetched::Offline(node)),
254 };
255 if chunk.file != self.cursor.file {
256 self.formatter = Formatter::new(color);
257 }
258
259 let mut entries = Vec::new();
260 for line in &chunk.lines {
261 if formatted {
262 entries.extend(self.formatter.format(line));
263 } else {
264 entries.push(line.clone());
265 }
266 }
267 self.cursor.offset = Some(chunk.offset);
268 self.cursor.file.clone_from(&chunk.file);
269 Ok(Fetched::Entries(chunk.file.map(PathBuf::from), entries))
270 }
271}
272
273enum Fetched {
274 Entries(Option<PathBuf>, Vec<String>),
275 Offline(String),
276}
277
278async fn follow_remote(
280 task: &Watched,
281 endpoint: &Endpoint,
282 formatted: bool,
283 color: bool,
284) -> anyhow::Result<()> {
285 let store_id = task
286 .store_id
287 .ok_or_else(|| anyhow::anyhow!("{} is not in the store", task.id))?;
288 let mut remote = Remote::new(store_id, color);
289 let mut printer = Printer::new(formatted, color);
290 let mut said_waiting = false;
291 loop {
292 match remote.read(endpoint, formatted, color).await? {
293 Fetched::Offline(node) => {
294 println!("{}", offline_message(&task.id, &node));
295 return Ok(());
296 }
297 Fetched::Entries(None, _) if !said_waiting => {
298 println!(
299 "No output for task {} yet, waiting for it to start",
300 task.id
301 );
302 said_waiting = true;
303 }
304 Fetched::Entries(Some(path), entries) => printer.print(&path, &entries),
305 Fetched::Entries(None, _) => {}
306 }
307
308 io::stdout().flush()?;
309 time::sleep(Duration::from_secs(1)).await;
310 }
311}
312
313fn offline_message(task: &str, node: &str) -> String {
314 format!("Task {task} runs on {node}, which is offline. The stream ends here")
315}
316
317struct Others {
319 endpoint: Endpoint,
320 store: TaskStore,
321 me: Option<String>,
322 remotes: HashMap<i64, Remote>,
323 offline: HashMap<i64, String>,
325}
326
327impl Others {
328 async fn new(endpoint: Endpoint) -> anyhow::Result<Self> {
329 Ok(Self {
330 endpoint,
331 store: cli::init_store().await?,
332 me: discovery::status().await.ok().map(|t| t.me.name),
333 remotes: HashMap::new(),
334 offline: HashMap::new(),
335 })
336 }
337
338 async fn running(&self) -> Vec<Task> {
339 let mut running = Vec::new();
340 for status in [TaskStatus::InProgress, TaskStatus::InReview] {
341 running.extend(
342 self.store
343 .list_all_by_status_global(status)
344 .await
345 .unwrap_or_default(),
346 );
347 }
348 running
349 .into_iter()
350 .filter(|t| t.owner_node.is_some() && t.owner_node != self.me)
351 .collect()
352 }
353
354 async fn poll(&mut self, printer: &mut Printer) {
355 let running = self.running().await;
356 self.remotes
357 .retain(|id, _| running.iter().any(|t| t.id == *id));
358 self.offline.retain(|id, node| {
359 running
360 .iter()
361 .any(|t| t.id == *id && t.owner_node.as_deref() == Some(node.as_str()))
362 });
363 for task in running {
364 if self.offline.contains_key(&task.id) {
365 continue;
366 }
367
368 let remote = self
369 .remotes
370 .entry(task.id)
371 .or_insert_with(|| Remote::new(task.id, printer.color));
372 match remote
373 .read(&self.endpoint, printer.formatted, printer.color)
374 .await
375 {
376 Ok(Fetched::Entries(Some(path), entries)) => printer.print(&path, &entries),
377 Ok(Fetched::Entries(None, _)) => {}
378 Ok(Fetched::Offline(node)) => {
379 let id = format!(
380 "{}#{}",
381 task.repo,
382 task.external_id.as_deref().unwrap_or_default()
383 );
384 println!("{}", offline_message(&id, &node));
385 self.offline.insert(task.id, node);
386 self.remotes.remove(&task.id);
387 }
388 Err(e) => tracing::debug!(task = task.id, err = %e, "could not read remote output"),
389 }
390 }
391 }
392}
393
394struct Watched {
396 id: String,
397 store_id: Option<i64>,
398 status: String,
399 dirs: Vec<PathBuf>,
401}
402
403impl Watched {
404 async fn resolve(id: &str) -> anyhow::Result<Self> {
405 let store = cli::init_store().await?;
406 let id = id.strip_suffix("-review").unwrap_or(id);
408 let task = reference::resolve(&store, id).await?;
409 Ok(Self {
410 id: task.display_spec(),
411 store_id: task.store_id,
412 status: task.status.clone(),
413 dirs: reference::state_dirs(&task)?,
414 })
415 }
416
417 fn sources(&self) -> Vec<(String, PathBuf)> {
418 newest_output(&self.dirs)
419 .map(|path| (self.id.clone(), path))
420 .into_iter()
421 .collect()
422 }
423
424 fn nothing_yet(&self) -> String {
426 if self.status != TaskStatus::InProgress.as_str() {
427 return format!(
428 "No output for task {} yet, waiting for it to start",
429 self.id
430 );
431 }
432
433 let searched: Vec<String> = self
434 .dirs
435 .iter()
436 .map(|dir| dir.join("attempts").display().to_string())
437 .collect();
438 format!(
439 "Task {} is in_progress but no output file was found under {}",
440 self.id,
441 searched.join(" or ")
442 )
443 }
444}
445
446async fn session_sources() -> Vec<(String, PathBuf)> {
448 let tmux = TmuxManager::new();
449 tmux::list_orch_sessions()
450 .await
451 .unwrap_or_default()
452 .into_iter()
453 .filter_map(|session| {
454 let (project, task) = tmux.parse_session_name(&session)?;
455 let path = session_output(&project, &task_dir_name(&task))?;
456 Some((session, path))
457 })
458 .collect()
459}
460
461fn task_dir_name(task: &str) -> String {
463 match task.strip_prefix("internal-") {
464 Some(rest) => format!("internal:{rest}"),
465 None => task.to_string(),
466 }
467}
468
469fn session_output(project: &str, name: &str) -> Option<PathBuf> {
471 let state = home::state_dir().ok()?;
472 let dirs: Vec<PathBuf> = subdirs(&state)
473 .iter()
474 .flat_map(|owner| subdirs(owner))
475 .filter(|repo| repo.file_name() == Some(project.as_ref()))
476 .map(|repo| repo.join("tasks").join(name))
477 .collect();
478 newest_output(&dirs)
479}
480
481pub(crate) fn newest_output(dirs: &[PathBuf]) -> Option<PathBuf> {
483 let mut best: Option<(SystemTime, PathBuf)> = None;
484 for dir in dirs {
485 for attempt in subdirs(&dir.join("attempts")) {
486 let output = attempt.join("output.json");
487 let Ok(modified) = output.metadata().and_then(|m| m.modified()) else {
488 continue;
489 };
490 if best.as_ref().is_none_or(|(t, _)| modified > *t) {
491 best = Some((modified, output));
492 }
493 }
494 }
495
496 best.map(|(_, p)| p)
497}
498
499fn subdirs(dir: &Path) -> Vec<PathBuf> {
500 fs::read_dir(dir)
501 .into_iter()
502 .flatten()
503 .flatten()
504 .map(|e| e.path())
505 .filter(|p| p.is_dir())
506 .collect()
507}
508
509const TAG_COLORS: [&str; 6] = ["36", "35", "33", "34", "96", "95"];
510
511fn tag_lines(entries: &[String], formatted: bool, gutter: impl Fn(bool) -> String) -> Vec<String> {
513 let mut out = Vec::new();
514 for entry in entries {
515 let step = !formatted || !entry.starts_with(ndjson::RESULT_PREFIX);
516 if formatted && step {
517 out.push(gutter(false));
518 }
519
520 for (i, line) in entry.lines().enumerate() {
521 out.push(format!("{} {line}", gutter(step && i == 0)));
522 }
523 }
524 out
525}
526
527fn tag(path: &Path) -> String {
529 match path_parts(path).as_slice() {
530 [attempt, _, task, _, repo] => {
531 let task = task.strip_prefix("internal:").unwrap_or(task);
532 format!("{repo}#{task} a{attempt}")
533 }
534 _ => path.display().to_string(),
535 }
536}
537
538fn key_of(path: &Path) -> String {
540 path.ancestors()
541 .nth(3)
542 .map_or_else(String::new, |p| p.display().to_string())
543}
544
545fn path_parts(path: &Path) -> Vec<String> {
546 path.iter()
547 .rev()
548 .skip(1)
549 .take(5)
550 .map(|p| p.to_string_lossy().into_owned())
551 .collect()
552}
553
554pub fn print(entries: &[String]) {
556 for entry in entries {
557 if entry.starts_with(ndjson::RESULT_PREFIX) {
558 println!("{entry}");
559 } else {
560 println!("\n{entry}");
561 }
562 }
563}
564
565#[cfg(test)]
566mod tests {
567 use std::fs::OpenOptions;
568 use std::thread;
569
570 use super::*;
571
572 #[test]
573 fn tail_returns_only_complete_lines() {
574 let dir = tempfile::tempdir().unwrap();
575 let path = dir.path().join("output.json");
576 fs::write(&path, "one\ntw").unwrap();
577 let mut tail = Tail::open(path.clone(), false);
578 assert_eq!(tail.read_lines(), vec!["one"]);
579
580 let mut f = OpenOptions::new().append(true).open(&path).unwrap();
581 f.write_all(b"o\nthree\n").unwrap();
582 assert_eq!(tail.read_lines(), vec!["two", "three"]);
583 assert_eq!(tail.read_lines(), [] as [String; 0]);
584 }
585
586 #[test]
587 fn tail_skips_cut_line_in_backlog() {
588 let dir = tempfile::tempdir().unwrap();
589 let path = dir.path().join("output.json");
590 let long = "x".repeat(usize::try_from(BACKLOG_BYTES).unwrap());
591
592 fs::write(&path, format!("{long}\nlast\n")).unwrap();
593 assert_eq!(Tail::open(path, false).read_lines(), vec!["last"]);
594 }
595
596 #[test]
597 fn task_dir_name_restores_internal_colon() {
598 assert_eq!(task_dir_name("internal-8-review"), "internal:8-review");
599 assert_eq!(task_dir_name("3601"), "3601");
600 }
601
602 #[test]
603 fn in_progress_without_output_names_the_path() {
604 let watched = Watched {
605 id: "owner/repo#5".to_string(),
606 store_id: Some(5),
607 status: TaskStatus::InProgress.as_str().to_string(),
608 dirs: vec![
609 PathBuf::from("/state/owner/repo/tasks/5-review"),
610 PathBuf::from("/state/owner/repo/tasks/5"),
611 ],
612 };
613 let msg = watched.nothing_yet();
614 assert!(msg.contains("in_progress"), "{msg}");
615 assert!(msg.contains("/state/owner/repo/tasks/5/attempts"), "{msg}");
616 assert!(
617 msg.contains("/state/owner/repo/tasks/5-review/attempts"),
618 "{msg}"
619 );
620
621 let waiting = Watched {
622 status: TaskStatus::Routed.as_str().to_string(),
623 ..watched
624 };
625 let msg = waiting.nothing_yet();
626 assert!(msg.contains("waiting for it to start"), "{msg}");
627 assert!(!msg.contains("no output file was found"), "{msg}");
628 }
629
630 #[test]
631 fn newest_output_picks_the_latest_attempt() {
632 let dir = tempfile::tempdir().unwrap();
633 let task = dir.path().join("tasks").join("5");
634 for attempt in ["1", "2"] {
635 let d = task.join("attempts").join(attempt);
636 fs::create_dir_all(&d).unwrap();
637 fs::write(d.join("output.json"), attempt).unwrap();
638 thread::sleep(Duration::from_millis(10));
640 }
641 let found = newest_output(&[task.join("5-review"), task.clone()]).unwrap();
642 assert_eq!(found, task.join("attempts").join("2").join("output.json"));
643 assert!(newest_output(&[dir.path().join("missing")]).is_none());
644 }
645
646 #[test]
647 fn tag_drops_internal_prefix() {
648 let path = Path::new("/s/owner/bean/tasks/internal:189488-review/attempts/1/output.json");
649 assert_eq!(tag(path), "bean#189488-review a1");
650 assert_eq!(key_of(path), "/s/owner/bean/tasks/internal:189488-review");
651 }
652
653 #[test]
654 fn tag_lines_label_each_step_only() {
655 let entries = vec![
656 "⏺ Read(a.rs)".to_string(),
657 " ⎿ Read 3 lines".to_string(),
658 "⏺ Fixing it.\n Then test.".to_string(),
659 ];
660 let gutter = |show: bool| if show { "t1 │" } else { " │" }.to_string();
661 assert_eq!(
662 tag_lines(&entries, true, gutter),
663 vec![
664 " │",
665 "t1 │ ⏺ Read(a.rs)",
666 " │ ⎿ Read 3 lines",
667 " │",
668 "t1 │ ⏺ Fixing it.",
669 " │ Then test.",
670 ]
671 );
672 }
673
674 #[test]
675 fn tag_lines_raw_tags_every_line() {
676 let entries = vec!["{\"a\":1}".to_string(), "{\"b\":2}".to_string()];
677 let gutter = |show: bool| if show { "t │" } else { " │" }.to_string();
678 assert_eq!(
679 tag_lines(&entries, false, gutter),
680 vec!["t │ {\"a\":1}", "t │ {\"b\":2}"]
681 );
682 }
683}