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