1use crate::cli;
2use crate::cli::task_ref;
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 = task_ref::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 if n == 0 {
129 return "0".to_string();
130 }
131 let s = n.to_string();
132 let mut result = String::new();
133 for (i, c) in s.chars().rev().enumerate() {
134 if i > 0 && i % 3 == 0 {
135 result.push(',');
136 }
137 result.push(c);
138 }
139 result.chars().rev().collect()
140}
141
142fn format_cost_groups(
143 title: &str,
144 header: &str,
145 name_width: usize,
146 groups: &[CostByGroup],
147) -> String {
148 let mut out = String::new();
149 let _ = writeln!(out);
150 let _ = writeln!(out, "{title}");
151 let _ = writeln!(out, "{}", "=".repeat(60));
152 let _ = writeln!(out);
153 let _ = writeln!(
154 out,
155 "{header:<name_width$} {:>10} {:>10} {:>10} {:>8}",
156 "INPUT", "OUTPUT", "COST", "TASKS"
157 );
158 let _ = writeln!(out, "{}", "-".repeat(60));
159 let mut total_cost = 0.0;
160 for group in groups {
161 total_cost += group.total_cost_usd;
162 let _ = writeln!(
163 out,
164 "{:<name_width$} {:>10} {:>10} {:>10} {:>8}",
165 group.name,
166 format_tokens(u64::try_from(group.input_tokens).unwrap_or(0)),
167 format_tokens(u64::try_from(group.output_tokens).unwrap_or(0)),
168 format_cost(group.total_cost_usd),
169 group.task_count,
170 );
171 }
172 let _ = writeln!(out, "{}", "-".repeat(60));
173 let _ = writeln!(
174 out,
175 "{:<name_width$} {:>10} {:>10} {:>10}",
176 "",
177 "",
178 "",
179 format_cost(total_cost)
180 );
181 let _ = writeln!(out);
182 out
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn format_tokens_zero() {
191 assert_eq!(format_tokens(0), "0");
192 }
193
194 #[test]
195 fn format_tokens_small() {
196 assert_eq!(format_tokens(123), "123");
197 }
198
199 #[test]
200 fn format_tokens_thousands() {
201 assert_eq!(format_tokens(1_234), "1,234");
202 }
203
204 #[test]
205 fn format_tokens_millions() {
206 assert_eq!(format_tokens(1_234_567), "1,234,567");
207 }
208
209 #[test]
210 fn format_cost_positive_zero_and_negative() {
211 assert_eq!(format_cost(0.0), "not reported");
212 assert_eq!(format_cost(-0.01), "not reported");
213 assert_eq!(format_cost(0.5), "$0.5000");
214 assert_eq!(format_cost(1.23456), "$1.2346");
215 }
216
217 fn group(name: &str, input: i64, output: i64, cost: f64, tasks: i64) -> CostByGroup {
218 CostByGroup {
219 name: name.to_string(),
220 input_tokens: input,
221 output_tokens: output,
222 total_cost_usd: cost,
223 task_count: tasks,
224 }
225 }
226
227 #[test]
228 fn cost_by_agent_table_layout() {
229 let groups = [group("claude", 1_234, 56, 0.5, 2)];
230 assert_eq!(
231 format_cost_groups("Cost by Agent", "AGENT", 12, &groups),
232 "\nCost by Agent\n============================================================\n\nAGENT INPUT OUTPUT COST TASKS\n------------------------------------------------------------\nclaude 1,234 56 $0.5000 2\n------------------------------------------------------------\n $0.5000\n\n"
233 );
234 }
235
236 #[test]
237 fn cost_by_model_table_layout_and_unreported_total() {
238 let groups = [group("sonnet", 0, 1_234_567, 0.0, 1)];
239 assert_eq!(
240 format_cost_groups("Cost by Model", "MODEL", 20, &groups),
241 "\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"
242 );
243 }
244}