Skip to content

Commit de43952

Browse files
ryoppippifdarian
andauthored
fix(claude): show model breakdowns for session --id (#2057)
* docs(skills): credit issue reporters and reply after merging Squash merges of #2050, #2051 and #2034 left out the reporters whose issues drove the fixes, and #2004 and #1987 got no reply after the contributor pinged. The create-pr skill now covers both steps at merge time, so they are no longer left to memory. * fix(claude): show model breakdowns for session --id `ccusage claude session --id <ID>` ignored `--breakdown`, and its JSON had no `modelBreakdowns`. The lookup path summed cost and tokens by hand instead of building the `UsageSummary` that the session list builds with `SessionAccumulator`, so it never had per-model data and never reached the shared table renderer that draws breakdown rows. Build the looked-up session through the same `SessionAccumulator` and render the table with the shared `print_usage_table`, matching how `codex session --id` reuses its session table. `--breakdown` now adds per-model rows, and the JSON keeps its existing fields while adding `modelsUsed` and `modelBreakdowns` (including `storedCost` and `missingPricing` where they apply). The text summary with a separate "Total Entries" line is replaced by the standard session table. Codex already honors `--breakdown` for `--id` and the top-level `ccusage session --id` routes to this Claude path, so no other agent needed a change. Co-authored-by: fdarian <[email protected]> * docs(session): document model breakdowns for claude session --id Describe the table and JSON shape of `ccusage claude session --id` now that it shares the session table and emits `modelBreakdowns`, and note that its breakdown entries mark unpriced models. * Revert "docs(skills): credit issue reporters and reply after merging" This reverts commit 3a33754. --------- Co-authored-by: fdarian <[email protected]>
1 parent 84e3f09 commit de43952

5 files changed

Lines changed: 141 additions & 17 deletions

File tree

‎docs/guide/json-output.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ ccusage daily --json | jq '.totals.unpricedModels // []'
5858

5959
Detection follows the [cost mode](/guide/cost-modes): an entry counts as unpriced only when ccusage had to calculate its cost from tokens and found no price. In `display` mode, or in `auto` mode for an entry that carries its own stored cost, nothing is looked up, so nothing is reported. A model can therefore appear in `unpricedModels` and still show a positive cost when some of its entries carried stored costs. An absent key means no unpriced usage was detected under the selected mode, not that every price is current.
6060

61-
Covered: `daily`, `weekly`, `monthly`, and `session` reports for every agent, including `--instances`, `--sections`, and `--by-agent`. Focused `codex` reports set `missingPricing` on the affected entries of each period's `models` map. Not covered: `blocks` and `session --id`, which have no `totals` object.
61+
Covered: `daily`, `weekly`, `monthly`, and `session` reports for every agent, including `--instances`, `--sections`, and `--by-agent`. Focused `codex` reports set `missingPricing` on the affected entries of each period's `models` map. `blocks` and `session --id` have no `totals` object; Claude's `session --id` still marks unpriced entries of its `modelBreakdowns`.
6262

6363
Update ccusage, or run without `--offline`, once the pricing source lists the model.
6464

‎docs/guide/session-reports.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ This is particularly useful for:
3434
# Get session data in table format
3535
ccusage claude session --id session-abc123-def456
3636

37+
# Add per-model rows to the session table
38+
ccusage claude session --id session-abc123-def456 --breakdown
39+
3740
# Get session data as JSON for scripting
3841
ccusage codex session --id codex://threads/01a0bb8c-c7c0-7630-9d82-860b875930f0 --json
3942

@@ -45,6 +48,8 @@ COST=$(ccusage claude session --id "$SESSION_ID" --json | jq '.totalCost')
4548
echo "Current session: \$${COST}"
4649
```
4750

51+
The table shows the same columns as `ccusage claude session`, restricted to that one session, and `--breakdown` adds a row per model. Claude's JSON output keeps `sessionId`, `totalCost`, `totalTokens`, and the per-request `entries`, and also carries the session's `modelsUsed` and per-model `modelBreakdowns`.
52+
4853
### Session ID Format
4954

5055
For Claude Code, session IDs are the actual filenames (without `.jsonl` extension) stored in Claude data directories. They typically look like:

‎rust/crates/ccusage/src/commands/mod.rs‎

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ use crate::{
2626
format_remaining_time, format_rfc3339_millis, group_project_output, identify_session_blocks,
2727
load_daily_summaries, load_entries, load_entries_since, print_active_block_detail,
2828
print_blocks_table, print_json_or_jq, print_usage_table, session_summary_json, sort_blocks,
29-
sort_summaries, summarize_by_key, summarize_summaries_by_bucket, summary_json,
30-
total_usage_tokens, totals_json, utc_now, wants_json,
29+
sort_summaries, summarize_by_key, summarize_summaries_by_bucket, summary_json, totals_json,
30+
utc_now, wants_json,
3131
};
3232

3333
pub(crate) fn run_daily(args: DailyArgs) -> Result<()> {
@@ -225,17 +225,20 @@ fn run_session_id(id: &str, shared: &SharedArgs) -> Result<()> {
225225
return Ok(());
226226
}
227227

228-
let total_cost = session_entries.iter().map(|entry| entry.cost).sum::<f64>();
229-
let total_tokens = session_entries
230-
.iter()
231-
.map(|entry| total_usage_tokens(entry.data.message.usage))
232-
.sum::<u64>();
228+
let mut session = SessionAccumulator::default();
229+
for entry in &session_entries {
230+
session.add_entry(entry);
231+
}
232+
let mut summary = session.into_summary()?;
233+
summary.session_id = Some(id.to_string());
233234

234235
if wants_json(shared) {
235236
let output = json!({
236237
"sessionId": id,
237-
"totalCost": total_cost,
238-
"totalTokens": total_tokens,
238+
"totalCost": summary.total_cost,
239+
"totalTokens": summary.total_tokens(),
240+
"modelsUsed": summary.models_used,
241+
"modelBreakdowns": summary.model_breakdowns,
239242
"entries": session_entries.iter().map(|entry| json!({
240243
"timestamp": entry.data.timestamp,
241244
"inputTokens": entry.data.message.usage.input_tokens,
@@ -250,13 +253,14 @@ fn run_session_id(id: &str, shared: &SharedArgs) -> Result<()> {
250253
return Ok(());
251254
}
252255

253-
println!("Claude Code Session Usage - {id}");
254-
if !shared.no_cost {
255-
println!("Total Cost: {}", format_currency(total_cost));
256-
}
257-
println!("Total Tokens: {}", format_number(total_tokens));
258-
println!("Total Entries: {}", session_entries.len());
259-
Ok(())
256+
print_usage_table(
257+
&format!("Claude Code Session Usage - {id}"),
258+
"Session",
259+
&[summary],
260+
shared,
261+
false,
262+
None,
263+
)
260264
}
261265

262266
pub(crate) fn run_blocks(args: BlocksArgs) -> Result<()> {

‎rust/crates/ccusage/tests/claude_cli.rs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,94 @@ fn session_id_deduplicates_repeated_message_usage() {
4141
assert_eq!(json["entries"].as_array().unwrap().len(), 1);
4242
}
4343

44+
fn write_two_model_session(fixture: &Fixture) {
45+
let messages = [
46+
r#"{"timestamp":"2026-09-15T12:00:00.000Z","sessionId":"session-a","requestId":"request-a","costUSD":0.25,"message":{"id":"message-a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":2}}}"#,
47+
r#"{"timestamp":"2026-09-15T12:01:00.000Z","sessionId":"session-a","requestId":"request-b","costUSD":1.5,"message":{"id":"message-b","model":"claude-opus-4-20250514","usage":{"input_tokens":30,"output_tokens":4,"cache_read_input_tokens":100}}}"#,
48+
];
49+
let _ = fixture.write_file(
50+
"projects/project-a/session-a/chat.jsonl",
51+
messages.join("\n"),
52+
);
53+
let _ = fixture.write_file(
54+
"projects/project-b/session-b/chat.jsonl",
55+
r#"{"timestamp":"2026-09-15T13:00:00.000Z","sessionId":"session-b","requestId":"request-c","costUSD":9.0,"message":{"id":"message-c","model":"claude-sonnet-4-20250514","usage":{"input_tokens":999,"output_tokens":999}}}"#,
56+
);
57+
}
58+
59+
#[test]
60+
fn session_id_json_includes_model_breakdowns() {
61+
let fixture = Fixture::new();
62+
write_two_model_session(&fixture);
63+
64+
let json: serde_json::Value = serde_json::from_str(&run_ccusage(
65+
&fixture,
66+
&[
67+
"claude",
68+
"session",
69+
"--id",
70+
"session-a",
71+
"--json",
72+
"--mode",
73+
"display",
74+
"--offline",
75+
],
76+
None,
77+
))
78+
.unwrap();
79+
80+
assert_eq!(
81+
json["modelsUsed"],
82+
serde_json::json!(["claude-sonnet-4-20250514", "claude-opus-4-20250514"])
83+
);
84+
let breakdowns = json["modelBreakdowns"].as_array().unwrap();
85+
assert_eq!(breakdowns.len(), 2, "{json}");
86+
assert_eq!(breakdowns[0]["modelName"], "claude-opus-4-20250514");
87+
assert_eq!(breakdowns[0]["inputTokens"], 30);
88+
assert_eq!(breakdowns[0]["outputTokens"], 4);
89+
assert_eq!(breakdowns[0]["cacheReadTokens"], 100);
90+
assert_eq!(breakdowns[0]["cost"], 1.5);
91+
assert_eq!(breakdowns[1]["modelName"], "claude-sonnet-4-20250514");
92+
assert_eq!(breakdowns[1]["inputTokens"], 10);
93+
assert_eq!(breakdowns[1]["cost"], 0.25);
94+
}
95+
96+
#[test]
97+
fn session_id_table_honors_breakdown() {
98+
let fixture = Fixture::new();
99+
write_two_model_session(&fixture);
100+
101+
let output = std::process::Command::new(env!("CARGO_BIN_EXE_ccusage"))
102+
.env_clear()
103+
.env("HOME", fixture.path("home"))
104+
.env("USERPROFILE", fixture.path("userprofile"))
105+
.env("XDG_CONFIG_HOME", fixture.path("xdg-config"))
106+
.env("CLAUDE_CONFIG_DIR", fixture.root())
107+
.env("NO_COLOR", "1")
108+
.env("COLUMNS", "200")
109+
.args([
110+
"claude",
111+
"session",
112+
"--id",
113+
"session-a",
114+
"--breakdown",
115+
"--mode",
116+
"display",
117+
"--offline",
118+
"--timezone",
119+
"UTC",
120+
])
121+
.output()
122+
.expect("failed to run ccusage");
123+
assert!(
124+
output.status.success(),
125+
"ccusage claude session --id --breakdown failed: {}",
126+
String::from_utf8_lossy(&output.stderr)
127+
);
128+
129+
insta::assert_snapshot!(String::from_utf8(output.stdout).unwrap());
130+
}
131+
44132
fn set_file_modified(path: &std::path::Path, unix_seconds: u64) {
45133
let modified = std::time::UNIX_EPOCH + std::time::Duration::from_secs(unix_seconds);
46134
std::fs::File::options()
@@ -876,6 +964,10 @@ fn auto_mode_breakdowns_report_the_stored_part_of_cost() {
876964
let reports = [
877965
(&["claude", "daily"][..], "/daily/0/modelBreakdowns/0"),
878966
(&["claude", "session"][..], "/sessions/0/modelBreakdowns/0"),
967+
(
968+
&["claude", "session", "--id", "session-a"][..],
969+
"/modelBreakdowns/0",
970+
),
879971
(&["claude", "monthly"][..], "/monthly/0/modelBreakdowns/0"),
880972
(
881973
&["daily", "--by-agent"][..],
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
source: crates/ccusage/tests/claude_cli.rs
3+
expression: "String::from_utf8(output.stdout).unwrap()"
4+
---
5+
6+
╭────────────────────────────────────────────╮
7+
│ │
8+
│ Claude Code Session Usage - session-a │
9+
│ │
10+
╰────────────────────────────────────────────╯
11+
12+
┌───────────────┬───────────────┬───────────┬───────────┬───────────────┬─────────────┬───────────────┬─────────────┬───────────────┐
13+
│ Session │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ Last Activity │
14+
├───────────────┼───────────────┼───────────┼───────────┼───────────────┼─────────────┼───────────────┼─────────────┼───────────────┤
15+
│ session-a │ - opus-4 │ 40 │ 6 │ 0 │ 100 │ 146 │ $1.75 │ 2026-09-15 │
16+
│ │ - sonnet-4 │ │ │ │ │ │ │ │
17+
├───────────────┼───────────────┼───────────┼───────────┼───────────────┼─────────────┼───────────────┼─────────────┼───────────────┤
18+
│ └─ opus-4 │ │ 30 │ 4 │ 0 │ 100 │ 134 │ $1.50 │ │
19+
├───────────────┼───────────────┼───────────┼───────────┼───────────────┼─────────────┼───────────────┼─────────────┼───────────────┤
20+
│ └─ sonnet-4 │ │ 10 │ 2 │ 0 │ 0 │ 12 │ $0.25 │ │
21+
├───────────────┼───────────────┼───────────┼───────────┼───────────────┼─────────────┼───────────────┼─────────────┼───────────────┤
22+
│ Total │ │ 40 │ 6 │ 0 │ 100 │ 146 │ $1.75 │ │
23+
└───────────────┴───────────────┴───────────┴───────────┴───────────────┴─────────────┴───────────────┴─────────────┴───────────────┘

0 commit comments

Comments
 (0)