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