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