use crate::agent::client::{AgentClient, SseMessage};
use std::time::Duration;
const USAGE: &str = "usage: zc jobs [--state live|done] [--json] | zc jobs --live [--json]";
#[derive(Debug, Default, PartialEq)]
pub struct Args {
pub live: bool,
pub state: Option<String>,
pub help: bool,
}
pub fn parse(args: &[String]) -> Result<Args, String> {
let mut out = Args::default();
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--live" | "-f" | "--follow" => out.live = true,
"--state" => out.state = Some(it.next().ok_or("--state needs live or done")?.clone()),
s if s.starts_with("--state=") => out.state = Some(s["--state=".len()..].to_string()),
"--json" => {}
"-h" | "--help" => out.help = true,
other => return Err(format!("unknown argument '{other}'")),
}
}
if let Some(s) = &out.state {
if s != "live" && s != "done" {
return Err(format!("--state must be live or done, got '{s}'"));
}
}
Ok(out)
}
fn short_time(ts: &str) -> String {
chrono::DateTime::parse_from_rfc3339(ts)
.map(|t| {
t.with_timezone(&chrono::Local)
.format("%H:%M:%S")
.to_string()
})
.unwrap_or_else(|_| ts.to_string())
}
fn duration(job: &serde_json::Value) -> Option<String> {
let start = chrono::DateTime::parse_from_rfc3339(job["started_at"].as_str()?).ok()?;
let end = chrono::DateTime::parse_from_rfc3339(job["finished_at"].as_str()?).ok()?;
let s = (end - start).num_seconds().max(0);
Some(if s >= 60 {
format!("{}m{:02}s", s / 60, s % 60)
} else {
format!("{s}s")
})
}
pub fn format_job(verb: &str, job: &serde_json::Value) -> String {
let when = match verb {
"finished" => job["finished_at"].as_str(),
_ => job["started_at"].as_str(),
}
.map(short_time)
.unwrap_or_default();
let requests = job["requests"].as_u64().unwrap_or(0);
let plural = if requests == 1 { "" } else { "s" };
let tail = match (verb, duration(job)) {
("finished", Some(d)) => format!(" {requests} request{plural} in {d}"),
("running", _) => format!(" {requests} request{plural} so far"),
_ => String::new(),
};
format!(
"{when} {verb:<8} {:<6} {}{tail}",
job["id"].as_str().unwrap_or("?"),
job["worker"].as_str().unwrap_or("?"),
)
}
pub fn run(args: &[String], json: bool) -> i32 {
let a = match parse(args) {
Ok(a) => a,
Err(e) => {
eprintln!("zc jobs: {e}\n{USAGE}");
return 2;
}
};
if a.help {
println!("{USAGE}\n\nJobs this node's workers ran or run, from the zc agent.\n --live stream jobs as they start and finish (Ctrl-C to stop)");
return 0;
}
let Some(dir) = crate::credentials::dir().map(|d| d.join("agent")) else {
eprintln!("zc jobs: no HOME or ZAKURO_HOME");
return 1;
};
let Some(client) = AgentClient::from_dir(&dir) else {
eprintln!("zc jobs: the zc agent is not installed (zc agent install)");
return 1;
};
if a.live {
return live(&dir, json);
}
let path = match &a.state {
Some(s) => format!("/v2/jobs?state={s}"),
None => "/v2/jobs".to_string(),
};
match client.get(&path, Duration::from_secs(5)) {
Ok(v) if json => {
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
0
}
Ok(v) => {
let jobs = v["jobs"].as_array().cloned().unwrap_or_default();
if jobs.is_empty() {
println!("No jobs yet.");
}
for j in &jobs {
let verb = if j["state"] == "live" {
"running"
} else {
"finished"
};
println!("{}", format_job(verb, j));
}
0
}
Err(e) => {
eprintln!("zc jobs: the zc agent is not reachable: {e}");
1
}
}
}
pub fn render_event(m: &SseMessage, json: bool) -> Option<String> {
let v: serde_json::Value = serde_json::from_str(&m.data).ok()?;
if json {
return matches!(m.event.as_str(), "job.started" | "job.finished" | "resync")
.then(|| v.to_string());
}
match m.event.as_str() {
"job.started" => Some(format_job("started", &v["data"])),
"job.finished" => Some(format_job("finished", &v["data"])),
_ => None,
}
}
fn live(dir: &std::path::Path, json: bool) -> i32 {
if !json {
if let Some(c) = AgentClient::from_dir(dir) {
if let Ok(v) = c.get("/v2/jobs?state=live", Duration::from_secs(5)) {
for j in v["jobs"].as_array().into_iter().flatten() {
println!("{}", format_job("running", j));
}
}
}
}
let mut last_id: Option<u64> = None;
let mut backoff = Duration::from_millis(500);
loop {
let result = match AgentClient::from_dir(dir) {
None => Err("no agent.json".to_string()),
Some(client) => client.events(last_id, |m| {
if let Some(id) = m.id.as_deref().and_then(|i| i.parse().ok()) {
last_id = Some(id);
}
if let Some(line) = render_event(&m, json) {
println!("{line}");
}
backoff = Duration::from_millis(500);
true
}),
};
match result {
Ok(()) => eprintln!(" (the agent closed the stream; reconnecting)"),
Err(e) => eprintln!(" (the agent is not reachable: {e}; retrying)"),
}
std::thread::sleep(backoff);
backoff = (backoff * 2).min(Duration::from_secs(10));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn parses_flags_and_refuses_unknown_ones() {
assert_eq!(parse(&args(&[])).unwrap(), Args::default());
assert!(parse(&args(&["--live"])).unwrap().live);
assert_eq!(
parse(&args(&["--state", "done"])).unwrap().state.as_deref(),
Some("done")
);
assert_eq!(
parse(&args(&["--state=live"])).unwrap().state.as_deref(),
Some("live")
);
assert!(parse(&args(&["--state", "x"])).is_err());
assert!(parse(&args(&["--nope"])).is_err());
assert!(parse(&args(&["--json"])).is_ok(), "--json is read by main");
}
#[test]
fn job_events_render_one_line_each_and_others_are_ignored() {
let data = |kind: &str| {
serde_json::json!({"id": 7, "type": kind, "at": "2026-09-13T01:42:00Z", "data": {
"id": "j7", "state": "done", "worker": "mbp-w0", "requests": 3,
"started_at": "2026-09-13T01:41:00Z", "finished_at": "2026-09-13T01:42:05Z",
"source": null, "squad": null}})
.to_string()
};
let msg = |kind: &str| SseMessage {
id: Some("7".into()),
event: kind.into(),
data: data(kind),
};
let line = render_event(&msg("job.finished"), false).unwrap();
assert!(
line.contains("finished j7 mbp-w0 3 requests in 1m05s"),
"{line}"
);
assert!(render_event(&msg("job.started"), false)
.unwrap()
.contains("started"));
assert_eq!(render_event(&msg("summary.changed"), false), None);
assert!(render_event(&msg("job.started"), true)
.unwrap()
.starts_with('{'));
assert_eq!(render_event(&msg("problem.raised"), true), None);
}
}