Skip to main content

blyte_cli/
dashboard.rs

1//! `blyte dashboard` local HTTP server and job collector (plan 2026-09-30).
2
3use std::collections::HashSet;
4use std::io::{BufRead, Write};
5use std::path::{Path, PathBuf};
6use std::time::UNIX_EPOCH;
7
8#[derive(Debug, Clone)]
9pub struct Sources {
10    pub roots: Vec<PathBuf>,
11    pub runs_dirs: Vec<PathBuf>,
12    pub hours: u64,
13}
14
15#[derive(serde::Deserialize)]
16struct DashboardConfig {
17    roots: Option<Vec<String>>,
18    runs_dirs: Option<Vec<String>>,
19}
20
21fn expand_home(path_str: &str, home: &Path) -> PathBuf {
22    if let Some(rest) = path_str.strip_prefix("~/") {
23        home.join(rest)
24    } else if path_str == "~" {
25        home.to_path_buf()
26    } else {
27        PathBuf::from(path_str)
28    }
29}
30
31impl Sources {
32    pub fn from_args(args: &crate::cli::DashboardArgs) -> Self {
33        Self::from_args_with_where(args).0
34    }
35
36    pub fn from_args_with_where(args: &crate::cli::DashboardArgs) -> (Self, String) {
37        if !args.roots.is_empty() || !args.runs_dirs.is_empty() {
38            return (
39                Self {
40                    roots: args.roots.clone(),
41                    runs_dirs: args.runs_dirs.clone(),
42                    hours: args.hours,
43                },
44                "--root/--runs-dir".to_string(),
45            );
46        }
47
48        let mut roots = Vec::new();
49        let mut runs_dirs = Vec::new();
50        let mut dashboard_contributed = false;
51
52        if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
53            let config_path = home.join(".config/blyte/dashboard.toml");
54            if let Ok(content) = std::fs::read_to_string(&config_path) {
55                if let Ok(cfg) = toml::from_str::<DashboardConfig>(&content) {
56                    if let Some(r) = cfg.roots {
57                        for p in r {
58                            let expanded = expand_home(&p, &home);
59                            if !roots.contains(&expanded) {
60                                roots.push(expanded);
61                                dashboard_contributed = true;
62                            }
63                        }
64                    }
65                    if let Some(d) = cfg.runs_dirs {
66                        for p in d {
67                            let expanded = expand_home(&p, &home);
68                            if !runs_dirs.contains(&expanded) {
69                                runs_dirs.push(expanded);
70                                dashboard_contributed = true;
71                            }
72                        }
73                    }
74                }
75            }
76        }
77
78        let mut dispatch_contributed = false;
79        for reg in crate::registry::registered() {
80            let already_listed = roots
81                .iter()
82                .any(|r| r == &reg || std::fs::canonicalize(r).map(|c| c == reg).unwrap_or(false));
83            if !already_listed {
84                roots.push(reg);
85                dispatch_contributed = true;
86            }
87        }
88
89        let mut parts = Vec::new();
90        if dashboard_contributed {
91            parts.push("dashboard.toml");
92        }
93        if dispatch_contributed {
94            parts.push("dispatch history");
95        }
96        let where_from = parts.join(" and ");
97
98        (
99            Self {
100                roots,
101                runs_dirs,
102                hours: args.hours,
103            },
104            where_from,
105        )
106    }
107}
108
109#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
110pub struct CommitRecord {
111    pub sha: String,
112    pub subject: String,
113}
114
115#[derive(serde::Serialize, Debug, Clone)]
116pub struct Job {
117    pub key: String,
118    pub id: String,
119    pub repo: String,
120    pub status: String,
121    pub gate_running: bool,
122    pub title: String,
123    pub task: String,
124    pub plan: Option<String>,
125    pub now: String,
126    pub started_at: Option<u64>,
127    pub finished_at: Option<u64>,
128    pub elapsed_s: Option<u64>,
129    pub cost_usd: Option<f64>,
130    pub turns: u64,
131    pub gate_attempts: u64,
132    pub gate_failures: Vec<String>,
133    pub model: Option<String>,
134    pub last_tool: Option<String>,
135    pub worktree: Option<String>,
136    pub worktree_exists: Option<bool>,
137    pub log: String,
138    pub commits: Vec<CommitRecord>,
139    pub changed_files: Vec<String>,
140    pub tags: Vec<String>,
141    pub verdict: Option<String>,
142    pub root: Option<PathBuf>,
143    pub plan_file: Option<String>,
144    pub plan_task: Option<String>,
145    pub task_file: Option<String>,
146    #[serde(skip)]
147    pub research: bool,
148    #[serde(skip)]
149    pub start_plan: Option<String>,
150    #[serde(skip)]
151    pub file_tags: Vec<String>,
152    #[serde(skip)]
153    pub verdict_notes: Option<String>,
154    #[serde(skip)]
155    pub verdict_ts: Option<u64>,
156    #[serde(skip)]
157    pub log_mtime: Option<u64>,
158}
159
160#[derive(serde::Serialize, Debug, Clone)]
161pub struct Summary {
162    pub running: usize,
163    pub last_24h: usize,
164    pub repos: usize,
165    pub finished_24h: usize,
166    pub passed_24h: usize,
167    pub cost_24h_usd: f64,
168}
169
170#[derive(serde::Serialize, Debug, Clone)]
171pub struct DashboardResponse {
172    pub generated_at: u64,
173    pub summary: Summary,
174    pub jobs: Vec<Job>,
175}
176
177fn strip_ansi(s: &str) -> std::borrow::Cow<'_, str> {
178    let bytes = s.as_bytes();
179    let Some(first_esc) = bytes.iter().position(|&b| b == 0x1b) else {
180        return std::borrow::Cow::Borrowed(s);
181    };
182
183    let mut out = String::with_capacity(s.len());
184    let mut seg_start = 0;
185    let mut i = first_esc;
186
187    while i < bytes.len() {
188        if bytes[i] == 0x1b && i + 1 < bytes.len() && bytes[i + 1] == b'[' {
189            out.push_str(&s[seg_start..i]);
190            i += 2;
191            while i < bytes.len() {
192                let b = bytes[i];
193                if (0x40..=0x7e).contains(&b) {
194                    i += 1;
195                    break;
196                }
197                if b == b'\n' || b == 0x1b {
198                    out.push(b as char);
199                    i += 1;
200                    break;
201                }
202                i += 1;
203            }
204            seg_start = i;
205        } else {
206            i += 1;
207        }
208        if let Some(rel) = bytes[i..].iter().position(|&b| b == 0x1b) {
209            i += rel;
210        } else {
211            break;
212        }
213    }
214
215    out.push_str(&s[seg_start..]);
216    std::borrow::Cow::Owned(out)
217}
218
219fn extract_title(task: &str) -> String {
220    for line in task.lines() {
221        let trimmed = line.trim();
222        if let Some(pos) = trimmed.find("Task: \"") {
223            let rest = &trimmed[pos + "Task: \"".len()..];
224            if let Some(end) = rest.find('"') {
225                return rest[..end].chars().take(120).collect();
226            }
227        }
228    }
229    for line in task.lines() {
230        let trimmed = line.trim();
231        if trimmed.starts_with('#') {
232            let text = trimmed.trim_start_matches('#').trim();
233            if !text.is_empty() {
234                return text.chars().take(120).collect();
235            }
236        }
237    }
238    for line in task.lines() {
239        let trimmed = line.trim_start_matches(['#', ' ']).trim_end();
240        if !trimmed.is_empty() {
241            return trimmed.chars().take(120).collect();
242        }
243    }
244    String::new()
245}
246
247fn job_title(task: &str, id: &str) -> String {
248    let title = extract_title(task);
249    if id.is_empty() {
250        return title;
251    }
252    let p_colon = format!("Task {id}:");
253    let p_space = format!("Task {id} ");
254    let rest = if let Some(after) = title.strip_prefix(&p_colon) {
255        after.trim()
256    } else if let Some(after) = title.strip_prefix(&p_space) {
257        after.trim()
258    } else {
259        return title;
260    };
261    if rest.is_empty() {
262        title
263    } else {
264        rest.chars().take(120).collect()
265    }
266}
267
268fn extract_plan(task: &str) -> Option<String> {
269    for line in task.lines() {
270        let trimmed = line.trim();
271        if let Some(rest) = trimmed.strip_prefix("Plan: ") {
272            let plan = rest.trim();
273            if !plan.is_empty() {
274                return Some(plan.to_string());
275            }
276        }
277    }
278    None
279}
280
281fn extract_prompt_task_title(prompt: &str) -> Option<String> {
282    for line in prompt.lines() {
283        let trimmed = line.trim();
284        if let Some(pos) = trimmed.find("Task: \"") {
285            let rest = &trimmed[pos + "Task: \"".len()..];
286            if let Some(end) = rest.find('"') {
287                return Some(rest[..end].to_string());
288            }
289        }
290    }
291    None
292}
293
294fn extract_first_task_id(text: &str) -> Option<String> {
295    for line in text.lines() {
296        let plain = plain_line(line);
297        let mut idx = 0;
298        while let Some(pos) = plain[idx..].find("Task") {
299            let start = idx + pos;
300            let after = &plain[start + 4..];
301            if after.starts_with(' ') || after.starts_with('\t') {
302                let trimmed = after.trim_start();
303                let id: String = trimmed
304                    .chars()
305                    .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
306                    .collect();
307                if !id.is_empty() {
308                    return Some(format!("Task {id}"));
309                }
310            }
311            idx = start + 4;
312        }
313    }
314    None
315}
316
317fn parse_heading(line: &str) -> Option<(usize, &str)> {
318    let trimmed = line.trim_start();
319    let hashes = trimmed.chars().take_while(|&c| c == '#').count();
320    if hashes > 0 {
321        let after = &trimmed[hashes..];
322        if after.is_empty() || after.starts_with(' ') || after.starts_with('\t') {
323            return Some((hashes, after.trim()));
324        }
325    }
326    None
327}
328
329fn extract_task_from_plan(plan_content: &str, title: &str) -> Option<String> {
330    let mut target_heading = None;
331    let mut offset = 0;
332
333    for line in plan_content.split_inclusive('\n') {
334        let line_len = line.len();
335        let trimmed = line.trim_end_matches(['\r', '\n']);
336        if let Some((level, text)) = parse_heading(trimmed) {
337            if text == title {
338                target_heading = Some((offset, level));
339                break;
340            }
341        }
342        offset += line_len;
343    }
344
345    let (start_offset, target_level) = target_heading?;
346
347    // A `#` line inside a fenced code block (a shell comment, say) is not a heading.
348    let mut end_offset = plan_content.len();
349    let mut curr_offset = 0;
350    let mut in_fence = false;
351    for line in plan_content.split_inclusive('\n') {
352        let line_len = line.len();
353        if line.trim_start().starts_with("```") {
354            in_fence = !in_fence;
355        } else if curr_offset > start_offset && !in_fence {
356            let trimmed = line.trim_end_matches(['\r', '\n']);
357            if let Some((level, _)) = parse_heading(trimmed) {
358                if level <= target_level {
359                    end_offset = curr_offset;
360                    break;
361                }
362            }
363        }
364        curr_offset += line_len;
365    }
366
367    Some(plan_content[start_offset..end_offset].to_string())
368}
369
370fn extract_now_from_final_message(msg: &str) -> String {
371    let pick = msg
372        .lines()
373        .map(str::trim)
374        .find(|l| !l.is_empty() && !l.starts_with('#'))
375        .or_else(|| msg.lines().map(str::trim).find(|l| !l.is_empty()))
376        .unwrap_or("");
377    plain_line(pick.trim_start_matches(['#', ' ']))
378        .chars()
379        .take(200)
380        .collect()
381}
382
383/// One line of markdown as plain text: no list marker, no `**`, `__` or backticks.
384fn plain_line(line: &str) -> String {
385    let mut l = line.trim();
386    if let Some(rest) = l.strip_prefix("- ").or_else(|| l.strip_prefix("* ")) {
387        l = rest;
388    } else if let Some((n, rest)) = l.split_once(". ") {
389        if !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) {
390            l = rest;
391        }
392    }
393    l.replace("**", "")
394        .replace("__", "")
395        .replace('`', "")
396        .trim()
397        .to_string()
398}
399
400struct LogInfo {
401    turns: u64,
402    last_tool: Option<String>,
403    gate_attempts: u64,
404    gate_running: bool,
405    mtime: Option<u64>,
406}
407
408fn parse_log(path: &Path) -> LogInfo {
409    let mtime = std::fs::metadata(path)
410        .ok()
411        .and_then(|m| m.modified().ok())
412        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
413        .map(|d| d.as_secs());
414
415    let raw = std::fs::read_to_string(path).unwrap_or_default();
416    let text = strip_ansi(&raw);
417
418    let mut max_turn = 0u64;
419    let mut last_tool = None;
420    let mut gate_attempts = 0u64;
421    let mut last_event_line: Option<String> = None;
422
423    for line in text.lines() {
424        let trimmed = line.trim();
425        if let Some(pos) = trimmed.find("[Turn ") {
426            let rest = &trimmed[pos + "[Turn ".len()..];
427            if let Some(end) = rest.find(']') {
428                if let Ok(n) = rest[..end].trim().parse::<u64>() {
429                    if n > max_turn {
430                        max_turn = n;
431                    }
432                }
433            }
434        }
435
436        if let Some(pos) = trimmed.find("● ") {
437            let tool = trimmed[pos + "● ".len()..].trim();
438            last_tool = Some(tool.chars().take(200).collect());
439        }
440
441        if trimmed.starts_with("✓ Gate passed") || trimmed.starts_with("✗ Gate failed") {
442            gate_attempts += 1;
443        }
444
445        if trimmed.contains("[Turn ")
446            || trimmed.contains("● ")
447            || trimmed.starts_with("⏳ Gate running")
448            || trimmed.starts_with("✓ Gate passed")
449            || trimmed.starts_with("✗ Gate failed")
450        {
451            last_event_line = Some(trimmed.to_string());
452        }
453    }
454
455    let gate_running = last_event_line
456        .map(|l| l.starts_with("⏳ Gate running"))
457        .unwrap_or(false);
458
459    LogInfo {
460        turns: max_turn,
461        last_tool,
462        gate_attempts,
463        gate_running,
464        mtime,
465    }
466}
467
468fn file_mtime(path: &Path) -> Option<u64> {
469    std::fs::metadata(path)
470        .ok()
471        .and_then(|m| m.modified().ok())
472        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
473        .map(|d| d.as_secs())
474}
475
476fn regular_file_mtime(path: &Path) -> Option<u64> {
477    let meta = std::fs::metadata(path).ok()?;
478    if !meta.is_file() {
479        return None;
480    }
481    meta.modified()
482        .ok()?
483        .duration_since(UNIX_EPOCH)
484        .ok()
485        .map(|d| d.as_secs())
486}
487
488fn started_with_job(pid: i64, started_at: Option<u64>, now: u64) -> bool {
489    match (get_process_etime(pid), started_at) {
490        (Some(elapsed), Some(started_at)) => now.saturating_sub(elapsed) <= started_at + 60,
491        _ => true,
492    }
493}
494
495fn normalize_path(path: &Path) -> PathBuf {
496    let mut out = PathBuf::new();
497    for comp in path.components() {
498        match comp {
499            std::path::Component::CurDir => {}
500            std::path::Component::ParentDir => match out.components().next_back() {
501                Some(std::path::Component::Normal(_)) => {
502                    out.pop();
503                }
504                Some(std::path::Component::RootDir | std::path::Component::Prefix(_)) => {}
505                _ => out.push(comp.as_os_str()),
506            },
507            other => out.push(other.as_os_str()),
508        }
509    }
510    out
511}
512
513fn git_common_dir(start: &Path) -> Option<PathBuf> {
514    if !start.exists() {
515        return None;
516    }
517    let resolved_start = if start.is_absolute() {
518        start.to_path_buf()
519    } else {
520        std::fs::canonicalize(start).ok()?
521    };
522    for dir in resolved_start.ancestors() {
523        let dot_git = dir.join(".git");
524        let Ok(meta) = std::fs::metadata(&dot_git) else {
525            continue;
526        };
527        if meta.is_dir() {
528            return Some(
529                std::fs::canonicalize(&dot_git).unwrap_or_else(|_| normalize_path(&dot_git)),
530            );
531        }
532        if meta.is_file() {
533            let content = std::fs::read_to_string(&dot_git).ok()?;
534            let first_line = content.lines().next()?.trim();
535            let raw_gitdir = first_line.strip_prefix("gitdir:")?.trim();
536            if raw_gitdir.is_empty() {
537                return None;
538            }
539            let gitdir_path = Path::new(raw_gitdir);
540            let gitdir = if gitdir_path.is_absolute() {
541                gitdir_path.to_path_buf()
542            } else {
543                dir.join(gitdir_path)
544            };
545            let commondir_file = gitdir.join("commondir");
546            let common = if commondir_file.is_file() {
547                let raw_common = std::fs::read_to_string(&commondir_file).ok()?;
548                let trimmed = raw_common.trim();
549                if trimmed.is_empty() {
550                    gitdir
551                } else {
552                    let common_path = Path::new(trimmed);
553                    if common_path.is_absolute() {
554                        common_path.to_path_buf()
555                    } else {
556                        gitdir.join(common_path)
557                    }
558                }
559            } else {
560                gitdir
561            };
562            return Some(
563                std::fs::canonicalize(&common).unwrap_or_else(|_| normalize_path(&common)),
564            );
565        }
566    }
567    None
568}
569
570pub fn parse_etime(s: &str) -> Option<u64> {
571    let s = s.trim();
572    if s.is_empty() {
573        return None;
574    }
575
576    let (days, time_str) = match s.split_once('-') {
577        Some((d, rest)) => {
578            let days = d.parse::<u64>().ok()?;
579            (days, rest)
580        }
581        None => (0, s),
582    };
583
584    let parts: Vec<&str> = time_str.split(':').collect();
585    match parts.len() {
586        2 => {
587            let m = parts[0].parse::<u64>().ok()?;
588            let sec = parts[1].parse::<u64>().ok()?;
589            Some(days * 86400 + m * 60 + sec)
590        }
591        3 => {
592            let h = parts[0].parse::<u64>().ok()?;
593            let m = parts[1].parse::<u64>().ok()?;
594            let sec = parts[2].parse::<u64>().ok()?;
595            Some(days * 86400 + h * 3600 + m * 60 + sec)
596        }
597        _ => None,
598    }
599}
600
601fn get_process_etime(pid: i64) -> Option<u64> {
602    // macOS: ask the kernel for the start time. `ps` is setuid there, so blyte's own sandbox
603    // cannot run it, and this also saves a process per PID.
604    #[cfg(target_os = "macos")]
605    {
606        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
607        let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
608        let ret = unsafe {
609            libc::proc_pidinfo(
610                pid as libc::c_int,
611                libc::PROC_PIDTBSDINFO,
612                0,
613                &mut info as *mut _ as *mut libc::c_void,
614                size,
615            )
616        };
617        if ret == size && info.pbi_start_tvsec > 0 {
618            let now = std::time::SystemTime::now()
619                .duration_since(UNIX_EPOCH)
620                .map(|d| d.as_secs())
621                .unwrap_or(0);
622            return Some(now.saturating_sub(info.pbi_start_tvsec));
623        }
624    }
625
626    if let Ok(output) = std::process::Command::new("ps")
627        .args(["-o", "etime=", "-p", &pid.to_string()])
628        .output()
629    {
630        if output.status.success() {
631            let s = String::from_utf8_lossy(&output.stdout);
632            if let Some(sec) = parse_etime(&s) {
633                return Some(sec);
634            }
635        }
636    }
637
638    None
639}
640
641#[derive(serde::Deserialize, Debug)]
642struct AgySummary {
643    status: Option<String>,
644    error: Option<String>,
645    duration_seconds: Option<f64>,
646    num_turns: Option<u64>,
647    response: Option<String>,
648}
649
650struct RawJob {
651    id: String,
652    repo: String,
653    root: Option<PathBuf>,
654    task: String,
655    task_file: Option<String>,
656    pid: Option<i64>,
657    started_at: Option<u64>,
658    research: bool,
659    start_plan: Option<String>,
660    start_plan_task: Option<String>,
661    file_tags: Vec<String>,
662    log_path: PathBuf,
663    report_path: PathBuf,
664    tags_path: PathBuf,
665    verdict_path: PathBuf,
666    worktree: Option<String>,
667    commits: Vec<CommitRecord>,
668    changed_files: Vec<String>,
669    summary_final_msg: Option<String>,
670    is_runs_dir: bool,
671    agy_summary_path: Option<PathBuf>,
672}
673
674pub fn repo_name(checkout: &Path) -> String {
675    let from_git = git_common_dir(checkout).and_then(|common| {
676        if common.file_name().and_then(|n| n.to_str()) == Some(".git") {
677            common
678                .parent()
679                .and_then(|p| p.file_name())
680                .and_then(|n| n.to_str())
681                .map(|n| n.to_string())
682        } else {
683            None
684        }
685    });
686
687    let raw = from_git.unwrap_or_else(|| {
688        checkout
689            .file_name()
690            .and_then(|n| n.to_str())
691            .map(|n| n.to_string())
692            .or_else(|| {
693                checkout
694                    .canonicalize()
695                    .ok()
696                    .as_deref()
697                    .and_then(Path::file_name)
698                    .and_then(|n| n.to_str())
699                    .map(|n| n.to_string())
700            })
701            .unwrap_or_else(|| "unknown".to_string())
702    });
703
704    if let Some((prefix, _)) = raw.split_once("--") {
705        if !prefix.is_empty() {
706            return prefix.to_string();
707        }
708    }
709    raw
710}
711
712pub fn collect_jobs(src: &Sources, now: u64) -> Vec<Job> {
713    let cutoff = now.saturating_sub(src.hours.saturating_mul(3600));
714    let mut raw_jobs = Vec::new();
715    let mut seen_keys = HashSet::new();
716
717    // 1. Dispatch layout
718    let mut wt_dirs = Vec::new();
719    for root in &src.roots {
720        let r_wt = root.join(".wt");
721        if r_wt.is_dir() && !wt_dirs.contains(&r_wt) {
722            wt_dirs.push(r_wt);
723        }
724        if let Ok(entries) = std::fs::read_dir(root) {
725            for entry in entries.flatten() {
726                let path = entry.path();
727                if path.is_dir() {
728                    let c_wt = path.join(".wt");
729                    if c_wt.is_dir() && !wt_dirs.contains(&c_wt) {
730                        wt_dirs.push(c_wt);
731                    }
732                }
733            }
734        }
735    }
736
737    for wt_dir in &wt_dirs {
738        let repo = wt_dir
739            .parent()
740            .map(repo_name)
741            .unwrap_or_else(|| "unknown".to_string());
742
743        if let Ok(entries) = std::fs::read_dir(wt_dir) {
744            for entry in entries.flatten() {
745                let fname = entry.file_name().to_string_lossy().to_string();
746                if let Some(id) = fname.strip_suffix(".start.json") {
747                    let id = id.to_string();
748                    let key = format!("{repo}/{id}");
749                    if !seen_keys.insert(key) {
750                        continue;
751                    }
752
753                    let report_path = wt_dir.join(format!("{id}.report.json"));
754                    let log_path = wt_dir.join(format!("{id}.log"));
755                    let report_mtime = regular_file_mtime(&report_path);
756                    let log_mtime = file_mtime(&log_path);
757                    if report_mtime.is_some_and(|m| m < cutoff)
758                        && log_mtime.is_none_or(|m| m < cutoff)
759                    {
760                        continue;
761                    }
762
763                    let start_path = wt_dir.join(format!("{id}.start.json"));
764                    let start_val = std::fs::read_to_string(&start_path)
765                        .ok()
766                        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok());
767                    let pid = start_val.as_ref().and_then(|v| v["pid"].as_i64());
768
769                    if report_mtime.is_none() && log_mtime.is_none_or(|m| m < cutoff) {
770                        let is_alive = pid.is_some_and(|p| {
771                            p > 0 && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
772                        });
773                        if !is_alive {
774                            continue;
775                        }
776                    }
777
778                    let started_at = start_val.as_ref().and_then(|v| v["started_at"].as_u64());
779                    let research = start_val
780                        .as_ref()
781                        .and_then(|v| v.get("research"))
782                        .and_then(|v| v.as_bool())
783                        .unwrap_or(false);
784                    let start_plan = start_val
785                        .as_ref()
786                        .and_then(|v| v["plan"].as_str())
787                        .map(|s| s.to_string())
788                        .filter(|s| !s.is_empty());
789                    let start_plan_task = start_val
790                        .as_ref()
791                        .and_then(|v| v["plan_task"].as_str())
792                        .map(|s| s.to_string())
793                        .filter(|s| !s.is_empty());
794                    let task_file = start_val
795                        .as_ref()
796                        .and_then(|v| v["task_file"].as_str())
797                        .map(|s| s.to_string());
798                    let task = task_file
799                        .as_deref()
800                        .and_then(|p| std::fs::read_to_string(p).ok())
801                        .unwrap_or_default();
802                    let mut file_tags = Vec::new();
803                    if let Some(tags_arr) = start_val.as_ref().and_then(|v| v["tags"].as_array()) {
804                        for t in tags_arr {
805                            if let Some(s) = t.as_str() {
806                                file_tags.push(s.to_string());
807                            }
808                        }
809                    }
810                    if let Some(s) = start_val
811                        .as_ref()
812                        .and_then(|v| v["session"].as_str())
813                        .filter(|s| !s.is_empty())
814                    {
815                        let prefix: String = s.chars().take(8).collect();
816                        let tag = format!("session:{prefix}");
817                        if !file_tags.contains(&tag) {
818                            file_tags.push(tag);
819                        }
820                    }
821
822                    let summary_path = wt_dir.join(format!("{id}.json"));
823                    let mut commits = Vec::new();
824                    let mut changed_files = Vec::new();
825                    let mut summary_final_msg = None;
826                    let mut worktree = None;
827                    if summary_path.is_file() {
828                        if let Ok(content) = std::fs::read_to_string(&summary_path) {
829                            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
830                                if let Some(arr) = val["commits"].as_array() {
831                                    for c in arr {
832                                        if let (Some(sha), Some(subject)) =
833                                            (c["sha"].as_str(), c["subject"].as_str())
834                                        {
835                                            commits.push(CommitRecord {
836                                                sha: sha.to_string(),
837                                                subject: subject.to_string(),
838                                            });
839                                        }
840                                    }
841                                }
842                                if let Some(arr) = val["changed_files"].as_array() {
843                                    for f in arr {
844                                        if let Some(s) = f.as_str() {
845                                            changed_files.push(s.to_string());
846                                        }
847                                    }
848                                }
849                                summary_final_msg =
850                                    val["final_message"].as_str().map(|s| s.to_string());
851                                worktree = val["worktree"].as_str().map(|s| s.to_string());
852                            }
853                        }
854                    }
855
856                    raw_jobs.push(RawJob {
857                        id: id.clone(),
858                        repo: repo.clone(),
859                        root: wt_dir.parent().map(|p| p.to_path_buf()),
860                        task,
861                        task_file,
862                        pid,
863                        started_at,
864                        research,
865                        start_plan,
866                        start_plan_task,
867                        file_tags,
868                        log_path,
869                        report_path,
870                        tags_path: wt_dir.join(format!("{id}.tags.json")),
871                        verdict_path: wt_dir.join(format!("{id}.verdict.json")),
872                        worktree,
873                        commits,
874                        changed_files,
875                        summary_final_msg,
876                        is_runs_dir: false,
877                        agy_summary_path: None,
878                    });
879                }
880            }
881        }
882    }
883
884    // 2. Runs-dir layout
885    for runs_dir in &src.runs_dirs {
886        if let Ok(repo_entries) = std::fs::read_dir(runs_dir) {
887            for repo_entry in repo_entries.flatten() {
888                let repo_path = repo_entry.path();
889                if repo_path.is_dir() {
890                    let repo = repo_path
891                        .file_name()
892                        .and_then(|n| n.to_str())
893                        .unwrap_or("unknown")
894                        .to_string();
895
896                    if let Ok(entries) = std::fs::read_dir(&repo_path) {
897                        for entry in entries.flatten() {
898                            let fname = entry.file_name().to_string_lossy().to_string();
899                            if let Some(id) = fname.strip_suffix(".log") {
900                                let id = id.to_string();
901                                let key = format!("{repo}/{id}");
902                                if !seen_keys.insert(key) {
903                                    continue;
904                                }
905
906                                let report_path = repo_path.join(format!("{id}.report.json"));
907                                let agy_path = repo_path.join(format!("{id}.json"));
908                                let log_path = repo_path.join(format!("{id}.log"));
909                                let report_mtime = regular_file_mtime(&report_path);
910                                let agy_mtime = regular_file_mtime(&agy_path);
911                                let log_mtime = file_mtime(&log_path);
912
913                                if report_mtime.is_some_and(|m| m < cutoff)
914                                    && agy_mtime.is_none_or(|m| m < cutoff)
915                                    && log_mtime.is_none_or(|m| m < cutoff)
916                                {
917                                    continue;
918                                }
919                                if report_mtime.is_none()
920                                    && agy_mtime.is_some_and(|m| m < cutoff)
921                                    && log_mtime.is_none_or(|m| m < cutoff)
922                                {
923                                    continue;
924                                }
925
926                                let pid_path = repo_path.join(format!("{id}.pid"));
927                                let (pid, started_at) = if pid_path.is_file() {
928                                    let pid_text =
929                                        std::fs::read_to_string(&pid_path).unwrap_or_default();
930                                    let pid = pid_text.trim().parse::<i64>().ok();
931                                    let mtime = file_mtime(&pid_path);
932                                    (pid, mtime)
933                                } else {
934                                    (None, None)
935                                };
936
937                                if report_mtime.is_none()
938                                    && agy_mtime.is_none()
939                                    && log_mtime.is_none_or(|m| m < cutoff)
940                                {
941                                    let is_alive = pid.is_some_and(|p| {
942                                        p > 0
943                                            && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
944                                            && started_with_job(p, started_at, now)
945                                    });
946                                    if !is_alive {
947                                        continue;
948                                    }
949                                }
950
951                                let prompt_path = repo_path.join(format!("{id}.prompt"));
952                                let task = if prompt_path.is_file() {
953                                    std::fs::read_to_string(&prompt_path).unwrap_or_default()
954                                } else {
955                                    String::new()
956                                };
957
958                                let worktree_path = repo_path.join(format!("{id}.worktree"));
959                                let worktree = if worktree_path.is_file() {
960                                    std::fs::read_to_string(&worktree_path)
961                                        .ok()
962                                        .map(|s| s.trim().to_string())
963                                        .filter(|s| !s.is_empty())
964                                } else {
965                                    None
966                                };
967
968                                let root = worktree.as_ref().and_then(|wt_str| {
969                                    let p = Path::new(wt_str.trim_end_matches('/'));
970                                    if let Some(common) = git_common_dir(p) {
971                                        if common.file_name().and_then(|n| n.to_str())
972                                            == Some(".git")
973                                        {
974                                            if let Some(parent) = common.parent() {
975                                                return Some(parent.to_path_buf());
976                                            }
977                                        }
978                                    }
979                                    if p.parent()
980                                        .and_then(|par| par.file_name())
981                                        .and_then(|n| n.to_str())
982                                        == Some(".wt")
983                                    {
984                                        return p
985                                            .parent()
986                                            .and_then(|par| par.parent())
987                                            .map(Path::to_path_buf);
988                                    }
989                                    if let (Some(par), Some(grandpar)) =
990                                        (p.parent(), p.parent().and_then(|par| par.parent()))
991                                    {
992                                        if par.file_name().and_then(|n| n.to_str())
993                                            == Some("worktrees")
994                                            && grandpar.file_name().and_then(|n| n.to_str())
995                                                == Some(".claude")
996                                        {
997                                            return grandpar.parent().map(Path::to_path_buf);
998                                        }
999                                    }
1000                                    if let Some(file_name) = p.file_name().and_then(|n| n.to_str())
1001                                    {
1002                                        if let Some((base, _)) = file_name.split_once("--") {
1003                                            if !base.is_empty() {
1004                                                return p.parent().map(|par| par.join(base));
1005                                            }
1006                                        }
1007                                    }
1008                                    Some(p.to_path_buf())
1009                                });
1010
1011                                let agy_summary_path = if agy_mtime.is_some() || agy_path.is_file()
1012                                {
1013                                    Some(agy_path)
1014                                } else {
1015                                    None
1016                                };
1017
1018                                raw_jobs.push(RawJob {
1019                                    id: id.clone(),
1020                                    repo: repo.clone(),
1021                                    root,
1022                                    task,
1023                                    task_file: None,
1024                                    pid,
1025                                    started_at,
1026                                    research: false,
1027                                    start_plan: None,
1028                                    start_plan_task: None,
1029                                    file_tags: Vec::new(),
1030                                    log_path,
1031                                    report_path,
1032                                    tags_path: repo_path.join(format!("{id}.tags.json")),
1033                                    verdict_path: repo_path.join(format!("{id}.verdict.json")),
1034                                    worktree,
1035                                    commits: Vec::new(),
1036                                    changed_files: Vec::new(),
1037                                    summary_final_msg: None,
1038                                    is_runs_dir: true,
1039                                    agy_summary_path,
1040                                });
1041                            }
1042                        }
1043                    }
1044                }
1045            }
1046        }
1047    }
1048
1049    let mut jobs = Vec::new();
1050    let mut plan_cache: std::collections::HashMap<PathBuf, Option<String>> =
1051        std::collections::HashMap::new();
1052
1053    for raw in raw_jobs {
1054        let title = job_title(&raw.task, &raw.id);
1055        let plan = extract_plan(&raw.task);
1056        let prompt_task_title = extract_prompt_task_title(&raw.task);
1057        let plan_file = raw.start_plan.clone().or_else(|| plan.clone());
1058        let plan_task = raw.start_plan_task.clone().or_else(|| {
1059            prompt_task_title
1060                .clone()
1061                .or_else(|| extract_first_task_id(&raw.task))
1062        });
1063
1064        let task_content = if let (Some(ref p_str), Some(ref t_title)) = (&plan, &prompt_task_title)
1065        {
1066            let p_path = if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
1067                expand_home(p_str, &home)
1068            } else {
1069                PathBuf::from(p_str)
1070            };
1071            let cached_plan = plan_cache
1072                .entry(p_path.clone())
1073                .or_insert_with(|| std::fs::read_to_string(&p_path).ok());
1074            if let Some(plan_text) = cached_plan {
1075                extract_task_from_plan(plan_text, t_title).unwrap_or_else(|| raw.task.clone())
1076            } else {
1077                raw.task.clone()
1078            }
1079        } else {
1080            raw.task.clone()
1081        };
1082
1083        let mut file_tags = raw.file_tags.clone();
1084        if raw.tags_path.is_file() {
1085            if let Ok(content) = std::fs::read_to_string(&raw.tags_path) {
1086                if let Ok(arr) = serde_json::from_str::<Vec<String>>(&content) {
1087                    for t in arr {
1088                        if !file_tags.contains(&t) {
1089                            file_tags.push(t);
1090                        }
1091                    }
1092                }
1093            }
1094        }
1095
1096        let mut tags = Vec::new();
1097        tags.push(format!("repo: {}", raw.repo));
1098        if let Some(ref p) = plan {
1099            if let Some(stem) = Path::new(p).file_stem().and_then(|s| s.to_str()) {
1100                tags.push(format!("plan: {stem}"));
1101            }
1102        }
1103        for t in &file_tags {
1104            if !tags.contains(t) {
1105                tags.push(t.clone());
1106            }
1107        }
1108
1109        let (verdict, verdict_notes, verdict_ts) = if raw.verdict_path.is_file() {
1110            let val = std::fs::read_to_string(&raw.verdict_path)
1111                .ok()
1112                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok());
1113            let v = val
1114                .as_ref()
1115                .and_then(|obj| obj["verdict"].as_str().map(|s| s.to_string()));
1116            let notes = val
1117                .as_ref()
1118                .and_then(|obj| obj["notes"].as_str().map(|s| s.to_string()));
1119            let ts = val
1120                .as_ref()
1121                .and_then(|obj| obj["ts"].as_u64())
1122                .or_else(|| file_mtime(&raw.verdict_path));
1123            (v, notes, ts)
1124        } else {
1125            (None, None, None)
1126        };
1127
1128        let log_info = parse_log(&raw.log_path);
1129
1130        let report_json = if raw.report_path.is_file() {
1131            std::fs::read_to_string(&raw.report_path)
1132                .ok()
1133                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1134        } else {
1135            None
1136        };
1137
1138        let report_mtime = if raw.report_path.is_file() {
1139            file_mtime(&raw.report_path)
1140        } else {
1141            None
1142        };
1143
1144        let agy_summary = if report_json.is_none() {
1145            raw.agy_summary_path.as_ref().and_then(|p| {
1146                std::fs::read_to_string(p)
1147                    .ok()
1148                    .and_then(|s| serde_json::from_str::<AgySummary>(&s).ok())
1149            })
1150        } else {
1151            None
1152        };
1153
1154        let (
1155            status,
1156            gate_running,
1157            cost_usd,
1158            turns,
1159            gate_attempts,
1160            gate_failures,
1161            model,
1162            finished_at,
1163            elapsed_s,
1164            now_str,
1165        ) = if let Some(ref report) = report_json {
1166            let outcome = report["outcome"].as_str().unwrap_or("unknown").to_string();
1167            let cost = report["cost_usd"].as_f64();
1168            let turns = report["turns"].as_u64().unwrap_or(log_info.turns);
1169            let gate_attempts = report["gate_attempts"]
1170                .as_u64()
1171                .unwrap_or(log_info.gate_attempts);
1172            let model = report["model_id"].as_str().map(|s| s.to_string());
1173
1174            let gate_failures = report["gate_failures"]
1175                .as_array()
1176                .map(|arr| {
1177                    let skip = arr.len().saturating_sub(2);
1178                    arr.iter()
1179                        .skip(skip)
1180                        .map(|v| {
1181                            let s = v.as_str().unwrap_or("");
1182                            let count = s.chars().count();
1183                            if count > 1500 {
1184                                s.chars().skip(count - 1500).collect()
1185                            } else {
1186                                s.to_string()
1187                            }
1188                        })
1189                        .collect()
1190                })
1191                .unwrap_or_default();
1192
1193            let finished_at = report_mtime;
1194            let elapsed_s = if let Some(dur) = report["duration_seconds"].as_f64() {
1195                Some(dur.round() as u64)
1196            } else if let (Some(fin), Some(st)) = (finished_at, raw.started_at) {
1197                if fin >= st {
1198                    Some(fin - st)
1199                } else {
1200                    None
1201                }
1202            } else {
1203                None
1204            };
1205
1206            let report_final_msg = report["final_message"].as_str();
1207            let now_from_msg = raw
1208                .summary_final_msg
1209                .as_deref()
1210                .or(report_final_msg)
1211                .map(extract_now_from_final_message)
1212                .filter(|s| !s.is_empty());
1213            let now_str = if let Some(s) = now_from_msg {
1214                s
1215            } else if let Some(ref tool) = log_info.last_tool {
1216                tool.clone()
1217            } else {
1218                String::new()
1219            };
1220
1221            (
1222                outcome,
1223                false,
1224                cost,
1225                turns,
1226                gate_attempts,
1227                gate_failures,
1228                model,
1229                finished_at,
1230                elapsed_s,
1231                now_str,
1232            )
1233        } else if let Some(ref agy) = agy_summary {
1234            let status = if agy.status.as_deref() == Some("ERROR") {
1235                "error".to_string()
1236            } else {
1237                "finished".to_string()
1238            };
1239            let cost = None;
1240            let turns = agy.num_turns.unwrap_or(log_info.turns);
1241            let gate_attempts = log_info.gate_attempts;
1242            let gate_failures = Vec::new();
1243            let model = None;
1244            let finished_at = raw.agy_summary_path.as_ref().and_then(|p| file_mtime(p));
1245            let elapsed_s = agy.duration_seconds.map(|d| d.round() as u64);
1246            let now_str = if status == "error" {
1247                let err = agy.error.as_deref().unwrap_or("");
1248                let s = extract_now_from_final_message(err);
1249                if !s.is_empty() {
1250                    s
1251                } else {
1252                    err.lines().next().unwrap_or("").chars().take(200).collect()
1253                }
1254            } else {
1255                let resp = agy.response.as_deref().unwrap_or("");
1256                let s = extract_now_from_final_message(resp);
1257                if !s.is_empty() {
1258                    s
1259                } else {
1260                    resp.lines()
1261                        .next()
1262                        .unwrap_or("")
1263                        .chars()
1264                        .take(200)
1265                        .collect()
1266                }
1267            };
1268
1269            (
1270                status,
1271                false,
1272                cost,
1273                turns,
1274                gate_attempts,
1275                gate_failures,
1276                model,
1277                finished_at,
1278                elapsed_s,
1279                now_str,
1280            )
1281        } else {
1282            // A live PID is this job's only if that process started with the job, not after it.
1283            // Only runs-dir jobs are checked: their PID files outlive the job for days, and the
1284            // dispatch layout's test fixture fakes a start time before its own process.
1285            let is_alive = raw.pid.is_some_and(|p| {
1286                p > 0
1287                    && unsafe { libc::kill(p as libc::pid_t, 0) == 0 }
1288                    && (!raw.is_runs_dir || started_with_job(p, raw.started_at, now))
1289            });
1290            let status = if is_alive {
1291                "running".to_string()
1292            } else {
1293                "stopped".to_string()
1294            };
1295            let gate_running = if status == "running" {
1296                log_info.gate_running
1297            } else {
1298                false
1299            };
1300            let cost = None;
1301            let turns = log_info.turns;
1302            let gate_attempts = log_info.gate_attempts;
1303            let gate_failures = Vec::new();
1304            let model = None;
1305            let finished_at = None;
1306            let elapsed_s = if status == "running" {
1307                raw.started_at.map(|s| now.saturating_sub(s))
1308            } else {
1309                None
1310            };
1311            let now_str = log_info.last_tool.clone().unwrap_or_default();
1312
1313            (
1314                status,
1315                gate_running,
1316                cost,
1317                turns,
1318                gate_attempts,
1319                gate_failures,
1320                model,
1321                finished_at,
1322                elapsed_s,
1323                now_str,
1324            )
1325        };
1326
1327        // Rule 7: Kept: every running job, and any other job whose finished_at (or, with no
1328        // report, the log's modified time) is within hours of now.
1329        let keep = if status == "running" {
1330            true
1331        } else {
1332            let effective_finished = finished_at.or(log_info.mtime);
1333            if let Some(fin) = effective_finished {
1334                fin >= cutoff
1335            } else {
1336                false
1337            }
1338        };
1339        if !keep {
1340            continue;
1341        }
1342
1343        let task_truncated: String = task_content.chars().take(2000).collect();
1344        let worktree_exists = raw.worktree.as_deref().map(|wt| Path::new(wt).is_dir());
1345
1346        jobs.push(Job {
1347            key: format!("{}/{}", raw.repo, raw.id),
1348            id: raw.id,
1349            repo: raw.repo,
1350            status,
1351            gate_running,
1352            title,
1353            task: task_truncated,
1354            plan,
1355            now: now_str,
1356            started_at: raw.started_at,
1357            finished_at,
1358            elapsed_s,
1359            cost_usd,
1360            turns,
1361            gate_attempts,
1362            gate_failures,
1363            model,
1364            last_tool: log_info.last_tool,
1365            worktree: raw.worktree,
1366            worktree_exists,
1367            log: raw.log_path.display().to_string(),
1368            commits: raw.commits,
1369            changed_files: raw.changed_files,
1370            tags,
1371            verdict,
1372            root: raw.root,
1373            plan_file,
1374            plan_task,
1375            task_file: raw.task_file,
1376            start_plan: raw.start_plan,
1377            file_tags,
1378            verdict_notes,
1379            verdict_ts,
1380            log_mtime: log_info.mtime,
1381            research: raw.research,
1382        });
1383    }
1384
1385    // Sort jobs: running jobs first, newest started_at first; then the rest, newest finished_at first.
1386    jobs.sort_by(|a, b| {
1387        let a_running = a.status == "running";
1388        let b_running = b.status == "running";
1389        match (a_running, b_running) {
1390            (true, false) => std::cmp::Ordering::Less,
1391            (false, true) => std::cmp::Ordering::Greater,
1392            (true, true) => b
1393                .started_at
1394                .unwrap_or(0)
1395                .cmp(&a.started_at.unwrap_or(0))
1396                .then_with(|| a.key.cmp(&b.key)),
1397            (false, false) => {
1398                let a_fin = a.finished_at.or(a.log_mtime).unwrap_or(0);
1399                let b_fin = b.finished_at.or(b.log_mtime).unwrap_or(0);
1400                b_fin.cmp(&a_fin).then_with(|| a.key.cmp(&b.key))
1401            }
1402        }
1403    });
1404
1405    jobs
1406}
1407
1408pub fn collect(src: &Sources, now: u64) -> serde_json::Value {
1409    let jobs = collect_jobs(src, now);
1410    let running = jobs.iter().filter(|j| j.status == "running").count();
1411    let last_24h = jobs
1412        .iter()
1413        .filter(|j| {
1414            j.started_at
1415                .is_some_and(|s| s >= now.saturating_sub(24 * 3600))
1416        })
1417        .count();
1418    let repos = jobs.iter().map(|j| &j.repo).collect::<HashSet<_>>().len();
1419
1420    let finished_jobs: Vec<_> = jobs
1421        .iter()
1422        .filter(|j| {
1423            j.status != "running"
1424                && j.finished_at
1425                    .or(j.log_mtime)
1426                    .is_some_and(|f| f >= now.saturating_sub(24 * 3600))
1427        })
1428        .collect();
1429
1430    let finished_24h = finished_jobs.len();
1431    let passed_24h = finished_jobs
1432        .iter()
1433        .filter(|j| j.status == "verified")
1434        .count();
1435    let sum_cost: f64 = finished_jobs.iter().filter_map(|j| j.cost_usd).sum();
1436    let cost_24h_usd = (sum_cost * 100.0).round() / 100.0;
1437
1438    let response = DashboardResponse {
1439        generated_at: now,
1440        summary: Summary {
1441            running,
1442            last_24h,
1443            repos,
1444            finished_24h,
1445            passed_24h,
1446            cost_24h_usd,
1447        },
1448        jobs,
1449    };
1450
1451    serde_json::to_value(&response).unwrap()
1452}
1453
1454pub(crate) fn shared_asset(clean_path: &str) -> Option<(u16, &'static str, Vec<u8>)> {
1455    match clean_path {
1456        "/favicon.svg" => {
1457            let svg = include_bytes!("../assets/dashboard/favicon.svg");
1458            Some((200, "image/svg+xml", svg.to_vec()))
1459        }
1460        "/fonts/archivo.woff2" => {
1461            let font = include_bytes!("../assets/dashboard/fonts/archivo.woff2");
1462            Some((200, "font/woff2", font.to_vec()))
1463        }
1464        "/fonts/plex-mono-400.woff2" => {
1465            let font = include_bytes!("../assets/dashboard/fonts/plex-mono-400.woff2");
1466            Some((200, "font/woff2", font.to_vec()))
1467        }
1468        "/fonts/plex-mono-500.woff2" => {
1469            let font = include_bytes!("../assets/dashboard/fonts/plex-mono-500.woff2");
1470            Some((200, "font/woff2", font.to_vec()))
1471        }
1472        _ => None,
1473    }
1474}
1475
1476pub fn route(path: &str, src: &Sources) -> (u16, &'static str, Vec<u8>) {
1477    let clean_path = match path.split_once('?') {
1478        Some((p, _)) => p,
1479        None => path,
1480    };
1481    if let Some(asset) = shared_asset(clean_path) {
1482        return asset;
1483    }
1484    match clean_path {
1485        "/" | "/index.html" => {
1486            let html = include_str!("../assets/dashboard/index.html");
1487            (200, "text/html; charset=utf-8", html.as_bytes().to_vec())
1488        }
1489        "/api/jobs" => {
1490            let now = std::time::SystemTime::now()
1491                .duration_since(UNIX_EPOCH)
1492                .map(|d| d.as_secs())
1493                .unwrap_or(0);
1494            let val = collect(src, now);
1495            let body = serde_json::to_vec(&val).unwrap_or_default();
1496            (200, "application/json", body)
1497        }
1498        "/api/plans" => {
1499            let now = std::time::SystemTime::now()
1500                .duration_since(UNIX_EPOCH)
1501                .map(|d| d.as_secs())
1502                .unwrap_or(0);
1503            let query = path.split_once('?').map(|(_, q)| q).unwrap_or("");
1504            let running_only = query
1505                .split('&')
1506                .any(|p| p == "running=1" || p == "running=true");
1507            let val = crate::plans::collect_plans_filtered(src, now, running_only);
1508            let body = serde_json::to_vec(&val).unwrap_or_default();
1509            (200, "application/json", body)
1510        }
1511        _ => (404, "text/plain; charset=utf-8", b"Not Found\n".to_vec()),
1512    }
1513}
1514
1515pub(crate) fn serve_http<F>(
1516    listener: std::net::TcpListener,
1517    no_store_paths: &'static [&'static str],
1518    handler: F,
1519) where
1520    F: Fn(&str) -> (u16, &'static str, Vec<u8>) + Send + Sync + 'static,
1521{
1522    let handler = std::sync::Arc::new(handler);
1523    for stream in listener.incoming().flatten() {
1524        let handler = std::sync::Arc::clone(&handler);
1525        std::thread::spawn(move || {
1526            handle_http_connection(stream, no_store_paths, handler.as_ref());
1527        });
1528    }
1529}
1530
1531fn handle_http_connection<F>(mut stream: std::net::TcpStream, no_store_paths: &[&str], handler: &F)
1532where
1533    F: Fn(&str) -> (u16, &'static str, Vec<u8>),
1534{
1535    let mut reader = std::io::BufReader::new(&mut stream);
1536    let mut request_line = String::new();
1537    if reader.read_line(&mut request_line).is_err() || request_line.is_empty() {
1538        return;
1539    }
1540    drop(reader);
1541
1542    let parts: Vec<&str> = request_line.split_whitespace().collect();
1543    if parts.len() < 2 || parts[0] != "GET" {
1544        let not_found = b"Not Found\n";
1545        let header = format!(
1546            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1547            not_found.len()
1548        );
1549        let _ = stream.write_all(header.as_bytes());
1550        let _ = stream.write_all(not_found);
1551        let _ = stream.flush();
1552        return;
1553    }
1554
1555    let path = parts[1];
1556    let (code, ctype, body) = handler(path);
1557    let clean_path = match path.split_once('?') {
1558        Some((p, _)) => p,
1559        None => path,
1560    };
1561    let reason = match code {
1562        200 => "OK",
1563        404 => "Not Found",
1564        500 => "Internal Server Error",
1565        _ => "OK",
1566    };
1567    let extra = if no_store_paths.contains(&clean_path) {
1568        "Cache-Control: no-store\r\n"
1569    } else {
1570        ""
1571    };
1572    let header = format!(
1573        "HTTP/1.1 {code} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n",
1574        body.len()
1575    );
1576    let _ = stream.write_all(header.as_bytes());
1577    let _ = stream.write_all(&body);
1578    let _ = stream.flush();
1579}
1580
1581pub fn run(args: &crate::cli::DashboardArgs) -> i32 {
1582    let (sources, where_from) = Sources::from_args_with_where(args);
1583    let listener = match std::net::TcpListener::bind(format!("127.0.0.1:{}", args.port)) {
1584        Ok(l) => l,
1585        Err(e) => {
1586            eprintln!("error binding 127.0.0.1:{}: {e}", args.port);
1587            return 1;
1588        }
1589    };
1590
1591    let local_addr = match listener.local_addr() {
1592        Ok(a) => a,
1593        Err(e) => {
1594            eprintln!("error getting local address: {e}");
1595            return 1;
1596        }
1597    };
1598    let port = local_addr.port();
1599    let url = format!("http://127.0.0.1:{port}");
1600    if sources.roots.is_empty() && sources.runs_dirs.is_empty() {
1601        eprintln!(
1602            "blyte dashboard: nothing to watch yet: run blyte dispatch in a repository, or list roots in ~/.config/blyte/dashboard.toml"
1603        );
1604    } else {
1605        eprintln!(
1606            "blyte dashboard: watching {} repositories and {} run directories ({where_from})",
1607            sources.roots.len(),
1608            sources.runs_dirs.len()
1609        );
1610    }
1611    println!("blyte dashboard: {url}");
1612    let _ = std::io::stdout().flush();
1613
1614    if args.open {
1615        let cmd = if cfg!(target_os = "macos") {
1616            "open"
1617        } else {
1618            "xdg-open"
1619        };
1620        if let Err(e) = std::process::Command::new(cmd).arg(&url).spawn() {
1621            eprintln!("warning: failed to open browser: {e}");
1622        }
1623    }
1624
1625    let live = args.roots.is_empty() && args.runs_dirs.is_empty();
1626    let args = args.clone();
1627    serve_http(listener, &["/api/jobs", "/api/plans"], move |path| {
1628        if live {
1629            let src = Sources::from_args(&args);
1630            route(path, &src)
1631        } else {
1632            route(path, &sources)
1633        }
1634    });
1635
1636    0
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641    use super::*;
1642
1643    #[test]
1644    fn extract_title_first_markdown_heading() {
1645        assert_eq!(
1646            extract_title(
1647                "From the plan docs/p.md:\n\n### Task G2: an empty gate is skipped\n\nbody"
1648            ),
1649            "Task G2: an empty gate is skipped"
1650        );
1651    }
1652
1653    #[test]
1654    fn extract_title_no_heading_fallback() {
1655        assert_eq!(extract_title("fix the bug\nmore"), "fix the bug");
1656    }
1657
1658    #[test]
1659    fn extract_title_task_rule_wins() {
1660        assert_eq!(
1661            extract_title("# Heading\nTask: \"explicit title\"\nmore"),
1662            "explicit title"
1663        );
1664    }
1665
1666    #[test]
1667    fn job_title_strips_task_id_prefix() {
1668        let text1 = "From the plan docs/p.md:\n\n### Task G2: an empty gate is skipped\n\nbody";
1669        assert_eq!(job_title(text1, "G2"), "an empty gate is skipped");
1670        assert_eq!(job_title("Task G3: x", "G2"), "Task G3: x");
1671        assert_eq!(job_title("Task G2:", "G2"), "Task G2:");
1672    }
1673
1674    #[test]
1675    fn session_tag_from_start_file() {
1676        let d = tempfile::tempdir().unwrap();
1677        let wt = d.path().join("repos/repo-a/.wt");
1678        std::fs::create_dir_all(&wt).unwrap();
1679
1680        let me = std::process::id();
1681        std::fs::write(
1682            wt.join("T1.start.json"),
1683            format!(r#"{{"id":"T1","pid":{me},"session":"4f83bf80-a445-4090","tags":["x"]}}"#),
1684        )
1685        .unwrap();
1686        std::fs::write(
1687            wt.join("T2.start.json"),
1688            format!(r#"{{"id":"T2","pid":{me},"session":"abc"}}"#),
1689        )
1690        .unwrap();
1691        std::fs::write(
1692            wt.join("T3.start.json"),
1693            format!(r#"{{"id":"T3","pid":{me},"tags":["x"]}}"#),
1694        )
1695        .unwrap();
1696        std::fs::write(
1697            wt.join("T4.start.json"),
1698            format!(r#"{{"id":"T4","pid":{me},"session":"4f83bf80-a445-4090","tags":["session:4f83bf80"]}}"#),
1699        )
1700        .unwrap();
1701
1702        let src = Sources {
1703            roots: vec![d.path().join("repos")],
1704            runs_dirs: vec![],
1705            hours: 24,
1706        };
1707        let now = std::time::SystemTime::now()
1708            .duration_since(std::time::UNIX_EPOCH)
1709            .unwrap()
1710            .as_secs();
1711        let jobs = collect_jobs(&src, now);
1712
1713        let t1 = jobs.iter().find(|j| j.id == "T1").unwrap();
1714        assert!(t1.tags.contains(&"x".to_string()));
1715        assert!(t1.tags.contains(&"session:4f83bf80".to_string()));
1716
1717        let t2 = jobs.iter().find(|j| j.id == "T2").unwrap();
1718        assert!(t2.tags.contains(&"session:abc".to_string()));
1719
1720        let t3 = jobs.iter().find(|j| j.id == "T3").unwrap();
1721        assert!(!t3.tags.iter().any(|t| t.starts_with("session:")));
1722
1723        let t4 = jobs.iter().find(|j| j.id == "T4").unwrap();
1724        assert_eq!(
1725            t4.tags
1726                .iter()
1727                .filter(|t| t.as_str() == "session:4f83bf80")
1728                .count(),
1729            1
1730        );
1731    }
1732
1733    #[test]
1734    fn strip_ansi_borrows_plain_and_strips_csi_sequences() {
1735        let plain = "[Turn 4]\n● bash\n✓ Gate passed\n";
1736        let res = strip_ansi(plain);
1737        assert!(matches!(res, std::borrow::Cow::Borrowed(_)));
1738        assert_eq!(res.as_ref(), plain);
1739
1740        let colored =
1741            "\x1b[32m[Turn 4]\x1b[0m\n\x1b[1m● bash\x1b[0m\n\x1b[32m✓ Gate passed\x1b[0m\n";
1742        let stripped = strip_ansi(colored);
1743        assert!(matches!(stripped, std::borrow::Cow::Owned(_)));
1744        assert_eq!(stripped.as_ref(), plain);
1745
1746        assert_eq!(strip_ansi("\x1b[32\nhello").as_ref(), "\nhello");
1747        assert_eq!(strip_ansi("\x1b[32\x1b[0mhello").as_ref(), "\x1b[0mhello");
1748        assert_eq!(strip_ansi("\x1bXhello").as_ref(), "\x1bXhello");
1749        assert_eq!(strip_ansi("tail\x1b").as_ref(), "tail\x1b");
1750        assert_eq!(strip_ansi("\x1b[32").as_ref(), "");
1751        assert_eq!(strip_ansi("\x1b[✓mhello").as_ref(), "hello");
1752    }
1753
1754    #[test]
1755    fn git_common_dir_resolves_relative_gitdir_and_commondir() {
1756        let tmp = tempfile::tempdir().unwrap();
1757        let main = tmp.path().join("myrepo");
1758        let worktree_git = main.join(".git/worktrees/wt1");
1759        let wt = tmp.path().join("wt1");
1760        std::fs::create_dir_all(&worktree_git).unwrap();
1761        std::fs::create_dir_all(wt.join("nested")).unwrap();
1762        std::fs::write(worktree_git.join("commondir"), "../..\n").unwrap();
1763        std::fs::write(wt.join(".git"), "gitdir: ../myrepo/.git/worktrees/wt1\n").unwrap();
1764
1765        let common = git_common_dir(&wt.join("nested")).unwrap();
1766        assert_eq!(common.file_name().and_then(|n| n.to_str()), Some(".git"));
1767        assert_eq!(
1768            common
1769                .parent()
1770                .and_then(|p| p.file_name())
1771                .and_then(|n| n.to_str()),
1772            Some("myrepo")
1773        );
1774        assert_eq!(repo_name(&wt.join("nested")), "myrepo");
1775    }
1776}