use crate::channels::tmux;
use crate::cli;
use crate::cli::task::reference;
use crate::engine::runner::ndjson::{self, Formatter};
use crate::store::cluster;
use crate::store::cluster::discovery;
use crate::store::cluster::local::{self, Endpoint};
use crate::store::cluster::output::{Cursor, Output};
use crate::store::{Task, TaskStatus, TaskStore};
use crate::sys::home;
use crate::sys::tmux::TmuxManager;
use std::collections::HashMap;
use std::fs::File;
use std::io::{IsTerminal, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use tokio::time;
use std::fs;
use std::io;
use std::mem;
const BACKLOG_BYTES: u64 = 64 * 1024;
pub(crate) struct Tail {
path: PathBuf,
offset: u64,
partial: Vec<u8>,
skip_first: bool,
formatter: Formatter,
}
impl Tail {
pub(crate) fn read_entries(&mut self, formatted: bool) -> Vec<String> {
let mut entries = Vec::new();
for line in self.read_lines() {
if formatted {
entries.extend(self.formatter.format(&line));
} else {
entries.push(line);
}
}
entries
}
pub(crate) fn open(path: PathBuf, color: bool) -> Self {
let len = fs::metadata(&path).map_or(0, |m| m.len());
let offset = len.saturating_sub(BACKLOG_BYTES);
Self {
path,
offset,
partial: Vec::new(),
skip_first: offset > 0,
formatter: Formatter::new(color),
}
}
pub(crate) fn open_at_end(path: PathBuf) -> Self {
let offset = fs::metadata(&path).map_or(0, |m| m.len());
Self {
path,
offset,
partial: Vec::new(),
skip_first: false,
formatter: Formatter::new(false),
}
}
pub(crate) fn shrank(&self) -> bool {
fs::metadata(&self.path).is_ok_and(|m| m.len() < self.offset)
}
pub(crate) fn read_lines(&mut self) -> Vec<String> {
let mut buf = Vec::new();
let read = File::open(&self.path).and_then(|mut f| {
f.seek(SeekFrom::Start(self.offset))?;
f.read_to_end(&mut buf)
});
let Ok(n) = read else {
return vec![];
};
self.offset += n as u64;
self.partial.extend_from_slice(&buf);
let Some(end) = self.partial.iter().rposition(|&b| b == b'\n') else {
return vec![];
};
let rest = self.partial.split_off(end + 1);
let complete = mem::replace(&mut self.partial, rest);
let mut lines: Vec<String> = String::from_utf8_lossy(&complete)
.lines()
.map(String::from)
.collect();
if mem::take(&mut self.skip_first) && !lines.is_empty() {
lines.remove(0);
}
lines
}
}
pub async fn run(task_id: Option<&str>, formatted: bool) -> anyhow::Result<()> {
let color = formatted && io::stdout().is_terminal();
let watched = if let Some(id) = task_id {
println!("Watching task {id}. Ctrl+C to stop");
Some(Watched::resolve(id).await?)
} else {
println!("Watching all running agents. Ctrl+C to stop");
None
};
let daemon = if cluster::enabled() {
local::daemon_endpoint().await
} else {
None
};
if let (Some(task), Some(endpoint)) = (&watched, &daemon) {
return follow_remote(task, endpoint, formatted, color).await;
}
let others = match daemon {
Some(endpoint) => Some(Others::new(endpoint).await?),
None => None,
};
follow_local(watched.as_ref(), others, formatted, color).await
}
async fn follow_local(
watched: Option<&Watched>,
mut others: Option<Others>,
formatted: bool,
color: bool,
) -> anyhow::Result<()> {
let mut tails: HashMap<String, Tail> = HashMap::new();
let mut printer = Printer::new(formatted, color);
let mut said_waiting = false;
loop {
let found = match watched {
Some(task) => task.sources(),
None => session_sources().await,
};
if let (Some(task), true, false) = (watched, found.is_empty(), said_waiting) {
println!("{}", task.nothing_yet());
said_waiting = true;
}
let live: Vec<String> = found.iter().map(|(key, _)| key.clone()).collect();
for (key, path) in found {
let tail = tails
.entry(key)
.or_insert_with(|| Tail::open(path.clone(), color));
if tail.path != path {
*tail = Tail::open(path, color);
}
}
for tail in tails.values_mut() {
let entries = tail.read_entries(formatted);
printer.print(&tail.path, &entries);
}
tails.retain(|key, _| live.contains(key));
if let Some(others) = others.as_mut() {
others.poll(&mut printer).await;
}
io::stdout().flush()?;
time::sleep(Duration::from_secs(1)).await;
}
}
struct Printer {
formatted: bool,
color: bool,
colors: HashMap<String, &'static str>,
tag_width: usize,
}
impl Printer {
fn new(formatted: bool, color: bool) -> Self {
Self {
formatted,
color,
colors: HashMap::new(),
tag_width: 0,
}
}
fn print(&mut self, path: &Path, entries: &[String]) {
if entries.is_empty() {
return;
}
let tag = tag(path);
self.tag_width = self.tag_width.max(tag.chars().count());
let next = TAG_COLORS[self.colors.len() % TAG_COLORS.len()];
let code = *self.colors.entry(key_of(path)).or_insert(next);
let (width, color) = (self.tag_width, self.color);
let gutter = |show: bool| {
let text = if show { tag.as_str() } else { "" };
let text = format!("{text:<width$} │");
if color {
format!("\x1b[{code}m{text}\x1b[0m")
} else {
text
}
};
for line in tag_lines(entries, self.formatted, gutter) {
println!("{line}");
}
}
}
struct Remote {
cursor: Cursor,
formatter: Formatter,
}
impl Remote {
fn new(task: i64, color: bool) -> Self {
Self {
cursor: Cursor {
task,
..Cursor::default()
},
formatter: Formatter::new(color),
}
}
async fn read(
&mut self,
endpoint: &Endpoint,
formatted: bool,
color: bool,
) -> anyhow::Result<Fetched> {
let chunk = match local::fetch_output(endpoint, &self.cursor).await? {
Output::Lines(chunk) => chunk,
Output::Offline { node } => return Ok(Fetched::Offline(node)),
};
if chunk.file != self.cursor.file {
self.formatter = Formatter::new(color);
}
let mut entries = Vec::new();
for line in &chunk.lines {
if formatted {
entries.extend(self.formatter.format(line));
} else {
entries.push(line.clone());
}
}
self.cursor.offset = Some(chunk.offset);
self.cursor.file.clone_from(&chunk.file);
Ok(Fetched::Entries(chunk.file.map(PathBuf::from), entries))
}
}
enum Fetched {
Entries(Option<PathBuf>, Vec<String>),
Offline(String),
}
async fn follow_remote(
task: &Watched,
endpoint: &Endpoint,
formatted: bool,
color: bool,
) -> anyhow::Result<()> {
let store_id = task
.store_id
.ok_or_else(|| anyhow::anyhow!("{} is not in the store", task.id))?;
let mut remote = Remote::new(store_id, color);
let mut printer = Printer::new(formatted, color);
let mut said_waiting = false;
loop {
match remote.read(endpoint, formatted, color).await? {
Fetched::Offline(node) => {
println!("{}", offline_message(&task.id, &node));
return Ok(());
}
Fetched::Entries(None, _) if !said_waiting => {
println!(
"No output for task {} yet, waiting for it to start",
task.id
);
said_waiting = true;
}
Fetched::Entries(Some(path), entries) => printer.print(&path, &entries),
Fetched::Entries(None, _) => {}
}
io::stdout().flush()?;
time::sleep(Duration::from_secs(1)).await;
}
}
fn offline_message(task: &str, node: &str) -> String {
format!("Task {task} runs on {node}, which is offline. The stream ends here")
}
struct Others {
endpoint: Endpoint,
store: TaskStore,
me: Option<String>,
remotes: HashMap<i64, Remote>,
offline: HashMap<i64, String>,
}
impl Others {
async fn new(endpoint: Endpoint) -> anyhow::Result<Self> {
Ok(Self {
endpoint,
store: cli::init_store().await?,
me: discovery::status().await.ok().map(|t| t.me.name),
remotes: HashMap::new(),
offline: HashMap::new(),
})
}
async fn running(&self) -> Vec<Task> {
let mut running = Vec::new();
for status in [TaskStatus::InProgress, TaskStatus::InReview] {
running.extend(
self.store
.list_all_by_status_global(status)
.await
.unwrap_or_default(),
);
}
running
.into_iter()
.filter(|t| t.owner_node.is_some() && t.owner_node != self.me)
.collect()
}
async fn poll(&mut self, printer: &mut Printer) {
let running = self.running().await;
self.remotes
.retain(|id, _| running.iter().any(|t| t.id == *id));
self.offline.retain(|id, node| {
running
.iter()
.any(|t| t.id == *id && t.owner_node.as_deref() == Some(node.as_str()))
});
for task in running {
if self.offline.contains_key(&task.id) {
continue;
}
let remote = self
.remotes
.entry(task.id)
.or_insert_with(|| Remote::new(task.id, printer.color));
match remote
.read(&self.endpoint, printer.formatted, printer.color)
.await
{
Ok(Fetched::Entries(Some(path), entries)) => printer.print(&path, &entries),
Ok(Fetched::Entries(None, _)) => {}
Ok(Fetched::Offline(node)) => {
let id = format!(
"{}#{}",
task.repo,
task.external_id.as_deref().unwrap_or_default()
);
println!("{}", offline_message(&id, &node));
self.offline.insert(task.id, node);
self.remotes.remove(&task.id);
}
Err(e) => tracing::debug!(task = task.id, err = %e, "could not read remote output"),
}
}
}
}
struct Watched {
id: String,
store_id: Option<i64>,
status: String,
dirs: Vec<PathBuf>,
}
impl Watched {
async fn resolve(id: &str) -> anyhow::Result<Self> {
let store = cli::init_store().await?;
let id = id.strip_suffix("-review").unwrap_or(id);
let task = reference::resolve(&store, id).await?;
Ok(Self {
id: task.display_spec(),
store_id: task.store_id,
status: task.status.clone(),
dirs: reference::state_dirs(&task)?,
})
}
fn sources(&self) -> Vec<(String, PathBuf)> {
newest_output(&self.dirs)
.map(|path| (self.id.clone(), path))
.into_iter()
.collect()
}
fn nothing_yet(&self) -> String {
if self.status != TaskStatus::InProgress.as_str() {
return format!(
"No output for task {} yet, waiting for it to start",
self.id
);
}
let searched: Vec<String> = self
.dirs
.iter()
.map(|dir| dir.join("attempts").display().to_string())
.collect();
format!(
"Task {} is in_progress but no output file was found under {}",
self.id,
searched.join(" or ")
)
}
}
async fn session_sources() -> Vec<(String, PathBuf)> {
let tmux = TmuxManager::new();
tmux::list_orch_sessions()
.await
.unwrap_or_default()
.into_iter()
.filter_map(|session| {
let (project, task) = tmux.parse_session_name(&session)?;
let path = session_output(&project, &task_dir_name(&task))?;
Some((session, path))
})
.collect()
}
fn task_dir_name(task: &str) -> String {
match task.strip_prefix("internal-") {
Some(rest) => format!("internal:{rest}"),
None => task.to_string(),
}
}
fn session_output(project: &str, name: &str) -> Option<PathBuf> {
let state = home::state_dir().ok()?;
let dirs: Vec<PathBuf> = subdirs(&state)
.iter()
.flat_map(|owner| subdirs(owner))
.filter(|repo| repo.file_name() == Some(project.as_ref()))
.map(|repo| repo.join("tasks").join(name))
.collect();
newest_output(&dirs)
}
pub(crate) fn newest_output(dirs: &[PathBuf]) -> Option<PathBuf> {
let mut best: Option<(SystemTime, PathBuf)> = None;
for dir in dirs {
for attempt in subdirs(&dir.join("attempts")) {
let output = attempt.join("output.json");
let Ok(modified) = output.metadata().and_then(|m| m.modified()) else {
continue;
};
if best.as_ref().is_none_or(|(t, _)| modified > *t) {
best = Some((modified, output));
}
}
}
best.map(|(_, p)| p)
}
fn subdirs(dir: &Path) -> Vec<PathBuf> {
fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect()
}
const TAG_COLORS: [&str; 6] = ["36", "35", "33", "34", "96", "95"];
fn tag_lines(entries: &[String], formatted: bool, gutter: impl Fn(bool) -> String) -> Vec<String> {
let mut out = Vec::new();
for entry in entries {
let step = !formatted || !entry.starts_with(ndjson::RESULT_PREFIX);
if formatted && step {
out.push(gutter(false));
}
for (i, line) in entry.lines().enumerate() {
out.push(format!("{} {line}", gutter(step && i == 0)));
}
}
out
}
fn tag(path: &Path) -> String {
match path_parts(path).as_slice() {
[attempt, _, task, _, repo] => {
let task = task.strip_prefix("internal:").unwrap_or(task);
format!("{repo}#{task} a{attempt}")
}
_ => path.display().to_string(),
}
}
fn key_of(path: &Path) -> String {
path.ancestors()
.nth(3)
.map_or_else(String::new, |p| p.display().to_string())
}
fn path_parts(path: &Path) -> Vec<String> {
path.iter()
.rev()
.skip(1)
.take(5)
.map(|p| p.to_string_lossy().into_owned())
.collect()
}
pub fn print(entries: &[String]) {
for entry in entries {
if entry.starts_with(ndjson::RESULT_PREFIX) {
println!("{entry}");
} else {
println!("\n{entry}");
}
}
}
#[cfg(test)]
mod tests {
use std::fs::OpenOptions;
use std::thread;
use super::*;
#[test]
fn tail_returns_only_complete_lines() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("output.json");
fs::write(&path, "one\ntw").unwrap();
let mut tail = Tail::open(path.clone(), false);
assert_eq!(tail.read_lines(), vec!["one"]);
let mut f = OpenOptions::new().append(true).open(&path).unwrap();
f.write_all(b"o\nthree\n").unwrap();
assert_eq!(tail.read_lines(), vec!["two", "three"]);
assert_eq!(tail.read_lines(), [] as [String; 0]);
}
#[test]
fn tail_skips_cut_line_in_backlog() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("output.json");
let long = "x".repeat(usize::try_from(BACKLOG_BYTES).unwrap());
fs::write(&path, format!("{long}\nlast\n")).unwrap();
assert_eq!(Tail::open(path, false).read_lines(), vec!["last"]);
}
#[test]
fn task_dir_name_restores_internal_colon() {
assert_eq!(task_dir_name("internal-8-review"), "internal:8-review");
assert_eq!(task_dir_name("3601"), "3601");
}
#[test]
fn in_progress_without_output_names_the_path() {
let watched = Watched {
id: "owner/repo#5".to_string(),
store_id: Some(5),
status: TaskStatus::InProgress.as_str().to_string(),
dirs: vec![
PathBuf::from("/state/owner/repo/tasks/5-review"),
PathBuf::from("/state/owner/repo/tasks/5"),
],
};
let msg = watched.nothing_yet();
assert!(msg.contains("in_progress"), "{msg}");
assert!(msg.contains("/state/owner/repo/tasks/5/attempts"), "{msg}");
assert!(
msg.contains("/state/owner/repo/tasks/5-review/attempts"),
"{msg}"
);
let waiting = Watched {
status: TaskStatus::Routed.as_str().to_string(),
..watched
};
let msg = waiting.nothing_yet();
assert!(msg.contains("waiting for it to start"), "{msg}");
assert!(!msg.contains("no output file was found"), "{msg}");
}
#[test]
fn newest_output_picks_the_latest_attempt() {
let dir = tempfile::tempdir().unwrap();
let task = dir.path().join("tasks").join("5");
for attempt in ["1", "2"] {
let d = task.join("attempts").join(attempt);
fs::create_dir_all(&d).unwrap();
fs::write(d.join("output.json"), attempt).unwrap();
thread::sleep(Duration::from_millis(10));
}
let found = newest_output(&[task.join("5-review"), task.clone()]).unwrap();
assert_eq!(found, task.join("attempts").join("2").join("output.json"));
assert!(newest_output(&[dir.path().join("missing")]).is_none());
}
#[test]
fn tag_drops_internal_prefix() {
let path = Path::new("/s/owner/bean/tasks/internal:189488-review/attempts/1/output.json");
assert_eq!(tag(path), "bean#189488-review a1");
assert_eq!(key_of(path), "/s/owner/bean/tasks/internal:189488-review");
}
#[test]
fn tag_lines_label_each_step_only() {
let entries = vec![
"⏺ Read(a.rs)".to_string(),
" ⎿ Read 3 lines".to_string(),
"⏺ Fixing it.\n Then test.".to_string(),
];
let gutter = |show: bool| if show { "t1 │" } else { " │" }.to_string();
assert_eq!(
tag_lines(&entries, true, gutter),
vec![
" │",
"t1 │ ⏺ Read(a.rs)",
" │ ⎿ Read 3 lines",
" │",
"t1 │ ⏺ Fixing it.",
" │ Then test.",
]
);
}
#[test]
fn tag_lines_raw_tags_every_line() {
let entries = vec!["{\"a\":1}".to_string(), "{\"b\":2}".to_string()];
let gutter = |show: bool| if show { "t │" } else { " │" }.to_string();
assert_eq!(
tag_lines(&entries, false, gutter),
vec!["t │ {\"a\":1}", "t │ {\"b\":2}"]
);
}
}