Skip to main content

orch/cli/
dashboard.rs

1use crate::backends::Status;
2use crate::cli;
3use crate::cli::init_task_manager;
4use crate::config;
5use crate::engine::tasks::status_to_task_status;
6use crate::store;
7use crate::store::TaskStatus;
8use crate::store::TaskStore;
9use crate::tmux::TmuxManager;
10use chrono::{DateTime, Duration, Utc};
11use std::collections::HashMap;
12use std::sync::Arc;
13
14/// Simple dashboard command combining task status, active sessions, and recent activity.
15pub async fn dashboard(global: bool, project: Option<String>) -> anyhow::Result<()> {
16    // Use global store when --global flag is set, a project filter is given,
17    // or when no project context is available (running outside a project dir).
18    if global || project.is_some() {
19        return dashboard_from_global_store(project.as_deref()).await;
20    }
21
22    let task_manager = match init_task_manager().await {
23        Ok(tm) => tm,
24        Err(e) => {
25            tracing::debug!("no project context available, falling back to global store: {e:#}");
26            return dashboard_from_global_store(None).await;
27        }
28    };
29
30    let statuses = [
31        Status::New,
32        Status::Routed,
33        Status::InProgress,
34        Status::InReview,
35        Status::Approved,
36        Status::Done,
37        Status::NeedsReview,
38        Status::Blocked,
39        Status::Waiting,
40    ];
41
42    // Fetch all tasks from both backends
43    let all_external = task_manager.list_all_external_tasks().await?;
44    let all_internal = task_manager.list_all_internal().await.unwrap_or_default();
45
46    let mut counts: Vec<(Status, usize, usize)> = Vec::new(); // (status, external, internal)
47    let mut total = 0usize;
48    let mut done_tasks = Vec::new();
49    for s in &statuses {
50        let label = s.as_label();
51        let ext_filtered: Vec<_> = all_external
52            .iter()
53            .filter(|t| t.labels.contains(&label.to_string()))
54            .cloned()
55            .collect();
56        let ts = status_to_task_status(*s);
57        let int_count = all_internal.iter().filter(|t| t.status == ts).count();
58        total += ext_filtered.len() + int_count;
59        counts.push((*s, ext_filtered.len(), int_count));
60        if *s == Status::Done {
61            done_tasks = ext_filtered;
62        }
63    }
64
65    println!("Tasks ({total} total)");
66
67    for (s, ext, int) in &counts {
68        let count = ext + int;
69        if count > 0 {
70            println!(
71                "  {:<12} {:>3}{}",
72                s.as_str(),
73                count,
74                if *int > 0 {
75                    format!(" ({int} internal)")
76                } else {
77                    String::new()
78                }
79            );
80        }
81    }
82
83    let store: Option<Arc<TaskStore>> = cli::init_store().await.ok().map(Arc::new);
84    let repo = config::get_current_repo().unwrap_or_default();
85
86    println!("\nActive Sessions");
87    let tmux = TmuxManager::new();
88    let sessions = tmux.list_sessions().await.unwrap_or_default();
89    for s in &sessions {
90        let agent = store::opt_store_get_task(&store, &repo, &s.task_id)
91            .await
92            .and_then(|t| t.agent)
93            .unwrap_or_default();
94        println!("  {:<25} {:<8} #{}", s.name, agent, s.task_id);
95    }
96
97    println!("\nRecent (last 24h)");
98    let cutoff: DateTime<Utc> = Utc::now() - Duration::hours(24);
99    for r in done_tasks.iter().take(10) {
100        if let Ok(dt) = DateTime::parse_from_rfc3339(&r.updated_at) {
101            let dt_utc = dt.with_timezone(&Utc);
102            if dt_utc >= cutoff {
103                let agent = store::opt_store_get_task(&store, &repo, &r.id.0)
104                    .await
105                    .and_then(|t| t.agent)
106                    .unwrap_or_default();
107                let elapsed = Utc::now() - dt_utc;
108                let mins = elapsed.num_minutes();
109                println!(
110                    "  ✅ #{:<4} {:<30} {:<8} done {:>4}m ago",
111                    r.id.0, r.title, agent, mins
112                );
113            }
114        }
115    }
116
117    Ok(())
118}
119
120/// Dashboard using the global store — works from any directory, across all projects.
121async fn dashboard_from_global_store(project: Option<&str>) -> anyhow::Result<()> {
122    let store = if let Ok(s) = cli::init_store().await {
123        Arc::new(s)
124    } else {
125        println!("Tasks (0 total)\n\nActive Sessions\n\nRecent (last 24h)");
126        return Ok(());
127    };
128
129    // Load all active tasks and recent done tasks from the store.
130    let mut active = store.list_all_active_global().await.unwrap_or_default();
131    let mut done = store
132        .list_all_by_status_global(TaskStatus::Done)
133        .await
134        .unwrap_or_default();
135
136    // Apply optional project filter.
137    if let Some(p) = project {
138        active.retain(|t| matches_project_filter(&t.repo, p));
139        done.retain(|t| matches_project_filter(&t.repo, p));
140    }
141
142    // Build a map from external_id -> agent for quick session lookups.
143    let agent_by_ext_id: HashMap<String, String> = active
144        .iter()
145        .filter_map(|t| {
146            let ext_id = t.external_id.as_deref()?;
147            let agent = t.agent.as_deref()?;
148            Some((ext_id.to_string(), agent.to_string()))
149        })
150        .collect();
151
152    // Count by status.
153    let status_order = [
154        TaskStatus::New,
155        TaskStatus::Routed,
156        TaskStatus::InProgress,
157        TaskStatus::InReview,
158        TaskStatus::Approved,
159        TaskStatus::NeedsReview,
160        TaskStatus::Blocked,
161        TaskStatus::Done,
162    ];
163
164    let done_count = done.len();
165    let total = active.len() + done_count;
166    println!("Tasks ({total} total)");
167
168    for ts in &status_order {
169        let count = if *ts == TaskStatus::Done {
170            done_count
171        } else {
172            active.iter().filter(|t| t.status == *ts).count()
173        };
174        if count > 0 {
175            println!("  {:<12} {:>3}", ts.as_str().replace('_', ""), count);
176        }
177    }
178
179    println!("\nActive Sessions");
180    let tmux = TmuxManager::new();
181    let sessions = tmux.list_sessions().await.unwrap_or_default();
182    for s in &sessions {
183        let agent = agent_by_ext_id
184            .get(&s.task_id)
185            .map(String::as_str)
186            .unwrap_or_default();
187        println!("  {:<25} {:<8} #{}", s.name, agent, s.task_id);
188    }
189
190    println!("\nRecent (last 24h)");
191    let cutoff: DateTime<Utc> = Utc::now() - Duration::hours(24);
192    for r in done.iter().take(10) {
193        if let Ok(dt) = DateTime::parse_from_rfc3339(&r.updated_at) {
194            let dt_utc = dt.with_timezone(&Utc);
195            if dt_utc >= cutoff {
196                let agent = r.agent.as_deref().unwrap_or_default();
197                let elapsed = Utc::now() - dt_utc;
198                let mins = elapsed.num_minutes();
199                let id_str = r.external_id.clone().unwrap_or_else(|| r.id.to_string());
200                println!(
201                    "  ✅ #{:<4} {:<30} {:<8} done {:>4}m ago",
202                    id_str, r.title, agent, mins
203                );
204            }
205        }
206    }
207
208    Ok(())
209}
210
211fn matches_project_filter(repo: &str, project: &str) -> bool {
212    let repo_name = repo.rsplit('/').next().unwrap_or(repo);
213    repo == project || repo_name == project || repo.ends_with(&format!("/{project}"))
214}