1use crate::cli;
2use crate::cli::task::reference;
3use crate::store::{self, CostByGroup, TaskStore};
4use std::fmt::Write as _;
5use std::sync::Arc;
6
7pub async fn show_task(id: &str) -> anyhow::Result<()> {
9 let owned = cli::init_store().await?;
10 let resolved = reference::resolve(&owned, id).await?;
11 let store: Option<Arc<TaskStore>> = Some(Arc::new(owned));
12 let repo = resolved.repo.clone();
13 let id = resolved.external_id.as_str();
14
15 let usage = store::get_token_usage(&store, &repo, id).await;
16 let cost = store::get_reported_cost(&store, &repo, id).await;
17 let model = store::opt_store_get_task(&store, &repo, id)
18 .await
19 .and_then(|t| t.model)
20 .unwrap_or_default();
21
22 if usage.total_tokens() == 0 {
23 println!("No token data available for task #{id}");
24 println!("Run the task first to collect token usage.");
25 return Ok(());
26 }
27
28 println!("Task #{id}: cost breakdown");
29 println!(
30 "├── Input tokens: {:>12}",
31 format_tokens(usage.input_tokens)
32 );
33 println!(
34 "├── Output tokens: {:>12}",
35 format_tokens(usage.output_tokens)
36 );
37 println!(
38 "└── Cost: {:>12}",
39 format_cost(cost.unwrap_or(0.0))
40 );
41 println!();
42 println!(
43 "Model: {}",
44 if model.is_empty() { "unknown" } else { &model }
45 );
46
47 Ok(())
48}
49
50pub async fn show_summary() -> anyhow::Result<()> {
52 let store = cli::init_store().await?;
53
54 let summary = store.get_cost_summary().await?;
55
56 println!();
57 println!("Cost Summary");
58 println!("{}", "=".repeat(60));
59 println!();
60 println!(
61 "{:<8} {:>10} {:>10} {:>10} {:>8}",
62 "PERIOD", "INPUT", "OUTPUT", "COST", "TASKS"
63 );
64 println!("{}", "-".repeat(60));
65
66 for period in &summary.periods {
67 println!(
68 "{:<8} {:>10} {:>10} {:>10} {:>8}",
69 period.label,
70 format_tokens(u64::try_from(period.input_tokens).unwrap_or(0)),
71 format_tokens(u64::try_from(period.output_tokens).unwrap_or(0)),
72 format_cost(period.total_cost_usd),
73 period.task_count,
74 );
75 }
76 println!();
77
78 Ok(())
79}
80
81pub async fn show_by_agent() -> anyhow::Result<()> {
83 let store = cli::init_store().await?;
84
85 let groups = store.get_cost_by_agent().await?;
86
87 if groups.is_empty() {
88 println!("No cost data available yet.");
89 return Ok(());
90 }
91
92 print!(
93 "{}",
94 format_cost_groups("Cost by Agent", "AGENT", 12, &groups)
95 );
96 Ok(())
97}
98
99pub async fn show_by_model() -> anyhow::Result<()> {
101 let store = cli::init_store().await?;
102
103 let groups = store.get_cost_by_model().await?;
104
105 if groups.is_empty() {
106 println!("No cost data available yet.");
107 return Ok(());
108 }
109
110 print!(
111 "{}",
112 format_cost_groups("Cost by Model", "MODEL", 20, &groups)
113 );
114 Ok(())
115}
116
117pub(crate) fn format_cost(cost_usd: f64) -> String {
120 if cost_usd > 0.0 {
121 format!("${cost_usd:.4}")
122 } else {
123 "not reported".to_string()
124 }
125}
126
127fn format_tokens(n: u64) -> String {
128 cli::format_thousands(&n.to_string())
129}
130
131fn format_cost_groups(
132 title: &str,
133 header: &str,
134 name_width: usize,
135 groups: &[CostByGroup],
136) -> String {
137 let mut out = String::new();
138 let _ = writeln!(out);
139 let _ = writeln!(out, "{title}");
140 let _ = writeln!(out, "{}", "=".repeat(60));
141 let _ = writeln!(out);
142 let _ = writeln!(
143 out,
144 "{header:<name_width$} {:>10} {:>10} {:>10} {:>8}",
145 "INPUT", "OUTPUT", "COST", "TASKS"
146 );
147 let _ = writeln!(out, "{}", "-".repeat(60));
148 let mut total_cost = 0.0;
149 for group in groups {
150 total_cost += group.total_cost_usd;
151 let _ = writeln!(
152 out,
153 "{:<name_width$} {:>10} {:>10} {:>10} {:>8}",
154 group.name,
155 format_tokens(u64::try_from(group.input_tokens).unwrap_or(0)),
156 format_tokens(u64::try_from(group.output_tokens).unwrap_or(0)),
157 format_cost(group.total_cost_usd),
158 group.task_count,
159 );
160 }
161 let _ = writeln!(out, "{}", "-".repeat(60));
162 let _ = writeln!(
163 out,
164 "{:<name_width$} {:>10} {:>10} {:>10}",
165 "",
166 "",
167 "",
168 format_cost(total_cost)
169 );
170 let _ = writeln!(out);
171 out
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 #[test]
179 fn format_tokens_zero() {
180 assert_eq!(format_tokens(0), "0");
181 }
182
183 #[test]
184 fn format_tokens_small() {
185 assert_eq!(format_tokens(123), "123");
186 assert_eq!(format_tokens(999), "999");
187 }
188
189 #[test]
190 fn format_tokens_thousands() {
191 assert_eq!(format_tokens(1_000), "1,000");
192 assert_eq!(format_tokens(1_234), "1,234");
193 }
194
195 #[test]
196 fn format_tokens_millions() {
197 assert_eq!(format_tokens(1_234_567), "1,234,567");
198 }
199
200 #[test]
201 fn format_cost_positive_zero_and_negative() {
202 assert_eq!(format_cost(0.0), "not reported");
203 assert_eq!(format_cost(-0.01), "not reported");
204 assert_eq!(format_cost(0.5), "$0.5000");
205 assert_eq!(format_cost(1.23456), "$1.2346");
206 }
207
208 fn group(name: &str, input: i64, output: i64, cost: f64, tasks: i64) -> CostByGroup {
209 CostByGroup {
210 name: name.to_string(),
211 input_tokens: input,
212 output_tokens: output,
213 total_cost_usd: cost,
214 task_count: tasks,
215 }
216 }
217
218 #[test]
219 fn cost_by_agent_table_layout() {
220 let groups = [group("claude", 1_234, 56, 0.5, 2)];
221 assert_eq!(
222 format_cost_groups("Cost by Agent", "AGENT", 12, &groups),
223 "\nCost by Agent\n============================================================\n\nAGENT INPUT OUTPUT COST TASKS\n------------------------------------------------------------\nclaude 1,234 56 $0.5000 2\n------------------------------------------------------------\n $0.5000\n\n"
224 );
225 }
226
227 #[test]
228 fn cost_by_model_table_layout_and_unreported_total() {
229 let groups = [group("sonnet", 0, 1_234_567, 0.0, 1)];
230 assert_eq!(
231 format_cost_groups("Cost by Model", "MODEL", 20, &groups),
232 "\nCost by Model\n============================================================\n\nMODEL INPUT OUTPUT COST TASKS\n------------------------------------------------------------\nsonnet 0 1,234,567 not reported 1\n------------------------------------------------------------\n not reported\n\n"
233 );
234 }
235}