Skip to content

Commit 3395151

Browse files
committed
Merge remote-tracking branch 'origin/main' into fix/session-until-inclusive
# Conflicts: # rust/crates/ccusage-adapter-all/src/loader.rs
2 parents d5651ee + 7db7a30 commit 3395151

20 files changed

Lines changed: 5753 additions & 887 deletions

File tree

‎apps/ccusage/config-schema.json‎

Lines changed: 3813 additions & 674 deletions
Large diffs are not rendered by default.

‎docs/guide/all-reports.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ ccusage detects local usage files from Claude Code, Codex, OpenCode, Amp, Droid,
4646

4747
Unified tables include an **Agent** column so you can compare sources in one view. Focused views remove that comparison layer and show the selected source in more detail where applicable.
4848

49+
When one tool runs another, usage can be logged by both. OpenCode's Claude Agent provider is one example: unified views skip the OpenCode copy of turns that Claude Code's own log has, matching them by session and, in daily views, by day, so a turn that runs across midnight can still be counted twice or partly left out. See [OpenCode](./opencode/#claude-agent-provider).
50+
4951
## Supported Sources
5052

5153
| Source | Namespace | Example focused view |

‎docs/guide/config-files.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ ccusage antigravity daily
287287
ccusage zcode daily
288288
```
289289

290-
Source-specific settings are also applied when running unified reports such as `ccusage daily`. Each source uses the same merged options as its focused command: global `defaults`, `commands.<report>`, `commands."<source>:<report>"`, `<source>.defaults`, and `<source>.commands.<report>`, with command-line flags taking precedence for every source. Set `offline` and `pricingOverrides` globally to share them across sources, or in a source section to specialize them. Set `claude.commands.daily.project` to filter Claude rows in unified daily reports and their sections. Unified weekly reports use the unified command's `startOfWeek` for every source and for `--last` calculation; source-level `startOfWeek` values are ignored. Each source groups dates with its resolved timezone before rows are combined, so sources with different timezones can place the same event on adjacent calendar dates.
290+
Source-specific settings are also applied when running unified reports such as `ccusage daily`. Each source uses the same merged options as its focused command: global `defaults`, `commands.<report>`, `commands."<source> <report>"`, `commands."<source>:<report>"`, `<source>.defaults`, and `<source>.commands.<report>`, with command-line flags taking precedence for every source. Set `offline` and `pricingOverrides` globally to share them across sources, or in a source section to specialize them. Set `claude.commands.daily.project` to filter Claude rows in unified daily reports and their sections. Unified weekly reports use the unified command's `startOfWeek` for every source and for `--last` calculation; source-level `startOfWeek` values are ignored. Each source groups dates with its resolved timezone before rows are combined, so sources with different timezones can place the same event on adjacent calendar dates.
291291

292292
Use `pi.stores` for additional pi-format session stores, such as tools or forks that write sessions outside `~/.pi/agent/sessions`. Named stores are additive to the default `pi` agent in unified reports, use their own agent name in JSON and tables, and prefix models with `[name]` followed by a space. Store names must match `^[a-z][a-z0-9_-]{0,31}$`, must be unique, and cannot use a built-in agent name. Each store path can be one sessions directory or a comma-separated list; `~` is expanded for store paths, nonexistent paths are treated as empty, and resolved paths that overlap the default `pi` store or another named store — including one path nested inside another — are rejected. They do not create focused commands such as `ccusage omp daily`; `PI_AGENT_DIR`, `--pi-path`, and `pi.defaults.piPath` still affect only the default `pi` agent.
293293

@@ -297,10 +297,13 @@ For a source-focused command, or each source within a unified report, options ar
297297

298298
1. `defaults`
299299
2. `commands.<report>`
300-
3. `commands."<source>:<report>"`
301-
4. `<source>.defaults`
302-
5. `<source>.commands.<report>`
303-
6. Command-line arguments
300+
3. `commands."<source> <report>"`
301+
4. `commands."<source>:<report>"`
302+
5. `<source>.defaults`
303+
6. `<source>.commands.<report>`
304+
7. Command-line arguments
305+
306+
`commands."codex daily"` and `commands."codex:daily"` both override `commands.daily`; if both are set, the colon form wins.
304307

305308
## Command-Specific Options
306309

‎docs/guide/opencode/index.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,17 @@ OpenCode supports subagent sessions. The session report displays:
7070

7171
When OpenCode v2 forks a session, it copies the parent's history into the fork. ccusage counts only the usage the fork generates itself, so copied turns are not counted twice in session, daily, weekly, or monthly reports. If the fork's parent session or boundary message is no longer in the database, the fork keeps all of its rows.
7272

73+
## Claude Agent Provider
74+
75+
The `claude-agent` provider runs Claude Code under the hood, so each turn is also saved in Claude Code's own logs. In [unified reports](/guide/all-reports) such as `ccusage daily`, ccusage skips the OpenCode copy of turns the Claude source already counts, so they are priced from the Claude Code logs. OpenCode stores only a model alias such as `opus`, while Claude Code records the exact model, so its costs are accurate.
76+
77+
ccusage matches OpenCode rows to Claude usage by Claude Code session, not by individual turn:
78+
79+
- **Daily, weekly, and monthly reports** skip an OpenCode `claude-agent` row when the Claude source counted usage from the same Claude Code session on the row's date, in the Claude source's timezone. Rows still count when the Claude Code log is gone, holds no usage for that day, holds only subagent usage, or falls outside the Claude source's date range.
80+
- **Session reports** match whole Claude Code sessions, because a Claude session row holds all of its usage, including days outside the Claude source's date range. Resumed and forked transcripts repeat earlier turns, and ccusage keeps one copy of each repeated turn. The OpenCode rows of a session whose own main-thread turns survive are skipped when every transcript holding them is included. The rows of a session whose turns all survive under other sessions are skipped only when every transcript holding those copies is included. When all transcripts are included, which one keeps a repeated turn does not affect the total. When the Claude window includes only some of them, a repeated turn can be left out, if a session's rows are skipped while its kept copy is in an excluded transcript, or counted twice, if the turns that decide whether a session's rows are skipped (its own surviving main-thread turns, or its kept copies when it has none) span included and excluded transcripts, since its rows are then kept.
81+
82+
Because OpenCode dates a turn by when it started and Claude Code dates each model call, a turn that runs across midnight can be off in the daily family. It is counted twice when Claude has no usage from that session on the day the turn started. With `--until` on that day, the calls Claude logs after midnight are left out, even though OpenCode dates the whole turn on the earlier day. `ccusage opencode` always shows every `claude-agent` row.
83+
7384
## Environment Variables
7485

7586
| Variable | Description |

‎flake.lock‎

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/adapters/claude/src/daily.rs‎

Lines changed: 141 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ use crate::{
2020
};
2121

2222
use super::{
23-
DailySummaries, DedupeIndexVec, advisor_usages_from_line, chunk_file_indexes_by_size,
24-
deserialize_usage_line, is_anthropic_message_id, is_semver_prefix,
23+
DailySummaries, DedupeIndexVec, SessionDays, advisor_usages_from_line,
24+
chunk_file_indexes_by_size, deserialize_usage_line, is_anthropic_message_id, is_semver_prefix,
25+
main_thread_session_days,
2526
paths::{SinceFiles, claude_paths, extract_project, split_files_before_since, usage_files},
2627
push_deduped_index, push_deduped_session_alias, push_new_deduped_index,
2728
sidechain_entry_replay_dedupe_hash, sidechain_replay_dedupe_hash, usage_dedupe_hash,
@@ -31,6 +32,7 @@ pub(super) fn load_daily_summaries_inner(
3132
shared: &SharedArgs,
3233
project_filter: Option<&str>,
3334
group_by_project: bool,
35+
session_days: impl FnOnce(&DedupedDailyEntries) -> SessionDays,
3436
) -> Result<DailySummaries> {
3537
let paths = claude_paths()?;
3638
let SinceFiles { kept, pruned } =
@@ -39,6 +41,7 @@ pub(super) fn load_daily_summaries_inner(
3941
return Ok(DailySummaries {
4042
summaries: Vec::new(),
4143
detected: false,
44+
session_days: SessionDays::default(),
4245
});
4346
}
4447

@@ -52,14 +55,10 @@ pub(super) fn load_daily_summaries_inner(
5255
))
5356
};
5457
let tz = parse_tz(shared.timezone.as_deref());
55-
let summaries = summarize_daily_files(
56-
&kept,
57-
shared,
58-
project_filter,
59-
group_by_project,
60-
tz.as_ref(),
61-
pricing.as_ref(),
62-
);
58+
let deduped =
59+
load_deduped_daily_entries(&kept, shared, project_filter, tz.as_ref(), pricing.as_ref());
60+
let session_days = session_days(&deduped);
61+
let summaries = summarize_daily_entries(&deduped.entries, group_by_project);
6362
// Skipped sessions still hold Claude usage, so they keep Claude detected
6463
// exactly as an unbounded load would. The first file with an entry settles it.
6564
let detected = !summaries.is_empty()
@@ -72,19 +71,51 @@ pub(super) fn load_daily_summaries_inner(
7271
Ok(DailySummaries {
7372
summaries,
7473
detected,
74+
session_days,
7575
})
7676
}
7777

78-
fn summarize_daily_files(
78+
/// Deduplicated daily entries plus the sessions of main-thread copies dedup
79+
/// merged into them from other sessions, such as a resumed or forked
80+
/// transcript repeating a turn, as `(survivor index, copy session)` pairs.
81+
pub(super) struct DedupedDailyEntries {
82+
entries: Vec<DailyLoadedEntry>,
83+
copies: Vec<(usize, Arc<str>)>,
84+
}
85+
86+
/// Counts a copy's session on the day its survivor is counted: a tool wrapping
87+
/// Claude Code can link its row to the session it ran in even when dedup kept
88+
/// another session's copy.
89+
pub(super) fn session_days(deduped: &DedupedDailyEntries) -> SessionDays {
90+
main_thread_session_days(
91+
deduped
92+
.entries
93+
.iter()
94+
.map(|entry| (&entry.session_id, entry))
95+
.chain(
96+
deduped
97+
.copies
98+
.iter()
99+
.map(|(index, session_id)| (session_id, &deduped.entries[*index])),
100+
)
101+
.map(|(session_id, survivor)| {
102+
(session_id, survivor.date.as_str(), survivor.is_sidechain)
103+
}),
104+
)
105+
}
106+
107+
fn load_deduped_daily_entries(
79108
files: &[PathBuf],
80109
shared: &SharedArgs,
81110
project_filter: Option<&str>,
82-
group_by_project: bool,
83111
tz: Option<&JiffTimeZone>,
84112
pricing: Option<&PricingMap>,
85-
) -> Vec<UsageSummary> {
113+
) -> DedupedDailyEntries {
86114
if files.is_empty() {
87-
return Vec::new();
115+
return DedupedDailyEntries {
116+
entries: Vec::new(),
117+
copies: Vec::new(),
118+
};
88119
}
89120
let mode = shared.mode;
90121
let loaded_files = if shared.single_thread {
@@ -98,20 +129,36 @@ fn summarize_daily_files(
98129

99130
let mut deduped_indexes: FxHashMap<u64, DedupeIndexVec> = FxHashMap::default();
100131
let mut deduped = Vec::with_capacity(loaded_files.iter().map(|file| file.entries.len()).sum());
132+
let mut copies = Vec::new();
101133
for loaded_file in loaded_files {
102134
for entry in loaded_file.entries {
103135
if let Some(filter) = project_filter
104136
&& entry.project.as_ref() != filter
105137
{
106138
continue;
107139
}
108-
push_deduped_daily_entry(entry, &mut deduped_indexes, &mut deduped);
140+
if let Some((index, discarded)) =
141+
push_deduped_daily_entry(entry, &mut deduped_indexes, &mut deduped)
142+
&& discarded.session_id != deduped[index].session_id
143+
&& !is_sidechain_daily_entry(&discarded)
144+
{
145+
copies.push((index, discarded.session_id));
146+
}
109147
}
110148
}
149+
DedupedDailyEntries {
150+
entries: deduped,
151+
copies,
152+
}
153+
}
111154

155+
fn summarize_daily_entries(
156+
deduped: &[DailyLoadedEntry],
157+
group_by_project: bool,
158+
) -> Vec<UsageSummary> {
112159
if group_by_project {
113160
let mut groups = BTreeMap::<(String, Arc<str>), DailyAccumulator>::new();
114-
for entry in &deduped {
161+
for entry in deduped {
115162
groups
116163
.entry((entry.date.clone(), Arc::clone(&entry.project)))
117164
.or_default()
@@ -129,7 +176,7 @@ fn summarize_daily_files(
129176
}
130177

131178
let mut groups = BTreeMap::<String, DailyAccumulator>::new();
132-
for entry in &deduped {
179+
for entry in deduped {
133180
groups
134181
.entry(entry.date.clone())
135182
.or_default()
@@ -152,7 +199,7 @@ struct DailyLoadedFile {
152199
}
153200

154201
#[derive(Debug)]
155-
struct DailyLoadedEntry {
202+
pub(super) struct DailyLoadedEntry {
156203
timestamp: TimestampMs,
157204
date: String,
158205
project: Arc<str>,
@@ -454,7 +501,7 @@ fn push_deduped_daily_entry(
454501
entry: DailyLoadedEntry,
455502
deduped_indexes: &mut FxHashMap<u64, DedupeIndexVec>,
456503
deduped: &mut Vec<DailyLoadedEntry>,
457-
) {
504+
) -> Option<(usize, DailyLoadedEntry)> {
458505
let dedupe_lookup = entry.message_id.as_deref().map(|message_id| {
459506
let request_id = entry.request_id.as_deref();
460507
let exact_hash = usage_dedupe_hash(
@@ -519,7 +566,7 @@ fn push_deduped_daily_entry(
519566
}
520567
}
521568
}
522-
if should_replace_deduped_daily_entry(&entry, &deduped[index]) {
569+
let discarded = if should_replace_deduped_daily_entry(&entry, &deduped[index]) {
523570
let previous = std::mem::replace(&mut deduped[index], entry);
524571
// The survivor is already indexed under its previous keys. Only register the keys
525572
// that changed, so repeated same-timestamp rewrites do not rescan large buckets.
@@ -544,8 +591,11 @@ fn push_deduped_daily_entry(
544591
);
545592
}
546593
}
547-
}
548-
return;
594+
previous
595+
} else {
596+
entry
597+
};
598+
return Some((index, discarded));
549599
}
550600

551601
let index = deduped.len();
@@ -569,6 +619,7 @@ fn push_deduped_daily_entry(
569619
}
570620
}
571621
}
622+
None
572623
}
573624

574625
fn daily_entry_exact_hash(entry: &DailyLoadedEntry) -> Option<u64> {
@@ -677,9 +728,42 @@ impl DailyAccumulator {
677728
mod tests {
678729
use std::sync::Arc;
679730

680-
use super::{DailyLoadedEntry, push_deduped_daily_entry, read_daily_usage_file};
681-
use crate::{TimestampMs, TokenUsageRaw, cli::CostMode};
682-
use ccusage_test_support::fs_fixture;
731+
use super::{
732+
DailyLoadedEntry, load_daily_summaries_inner, push_deduped_daily_entry,
733+
read_daily_usage_file, session_days,
734+
};
735+
use crate::{
736+
TimestampMs, TokenUsageRaw,
737+
cli::{CostMode, SharedArgs},
738+
};
739+
use ccusage_test_support::{EnvVarsGuard, fs_fixture};
740+
741+
#[test]
742+
fn collects_session_days_of_counted_main_thread_usage_only() {
743+
let fixture = fs_fixture!({
744+
"projects/project-a/session-a.jsonl": r#"{"timestamp":"2026-01-02T10:00:00.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg-a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":100,"output_tokens":1}}}"#,
745+
"projects/project-a/session-empty.jsonl": r#"{"timestamp":"2026-01-02T10:00:00.000Z","sessionId":"session-empty","type":"user","message":{"role":"user","content":"hi"}}"#,
746+
"projects/project-a/session-sub/subagents/agent-1.jsonl": r#"{"timestamp":"2026-01-02T10:00:00.000Z","sessionId":"session-sub","isSidechain":true,"requestId":"req-sub","message":{"id":"msg-sub","model":"claude-sonnet-4-20250514","usage":{"input_tokens":30,"output_tokens":1}}}"#,
747+
});
748+
let _env = EnvVarsGuard::set_many([(
749+
"CLAUDE_CONFIG_DIR",
750+
Some(fixture.root().as_os_str().to_os_string()),
751+
)]);
752+
let shared = SharedArgs {
753+
mode: CostMode::Display,
754+
timezone: Some("UTC".to_string()),
755+
single_thread: true,
756+
..SharedArgs::default()
757+
};
758+
759+
let daily = load_daily_summaries_inner(&shared, None, false, session_days).unwrap();
760+
761+
assert_eq!(
762+
daily.session_days.into_iter().collect::<Vec<_>>(),
763+
[(Arc::from("session-a"), "2026-01-02".to_string())]
764+
);
765+
assert_eq!(daily.summaries[0].input_tokens, 130);
766+
}
683767

684768
#[test]
685769
fn keeps_parent_daily_usage_when_sidechain_replays_message_with_new_request_id() {
@@ -1066,6 +1150,38 @@ mod tests {
10661150
assert_eq!(deduped[0].usage.input_tokens, 200);
10671151
}
10681152

1153+
#[test]
1154+
fn returns_the_discarded_daily_copy_from_another_session() {
1155+
let fixture = fs_fixture!({
1156+
"projects/project-a/session-a/chat.jsonl": r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-shared","message":{"id":"msg-shared","model":"claude-sonnet-4-20250514","usage":{"input_tokens":100,"output_tokens":1}}}"#,
1157+
"projects/project-a/session-b/chat.jsonl": r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-b","requestId":"req-shared","message":{"id":"msg-shared","model":"claude-sonnet-4-20250514","usage":{"input_tokens":200,"output_tokens":1}}}"#,
1158+
"projects/project-a/session-c/chat.jsonl": r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-c","requestId":"req-shared","message":{"id":"msg-shared","model":"claude-sonnet-4-20250514","usage":{"input_tokens":50,"output_tokens":1}}}"#,
1159+
});
1160+
let mut deduped_indexes = Default::default();
1161+
let mut deduped = Vec::new();
1162+
1163+
let discarded = ["a", "b", "c"].map(|session| {
1164+
let path = fixture.path(format!("projects/project-a/session-{session}/chat.jsonl"));
1165+
let entry = read_daily_usage_file(&path, None, CostMode::Display, None)
1166+
.entries
1167+
.into_iter()
1168+
.next()
1169+
.unwrap();
1170+
push_deduped_daily_entry(entry, &mut deduped_indexes, &mut deduped)
1171+
.map(|(index, discarded)| (index, discarded.session_id.to_string()))
1172+
});
1173+
1174+
assert_eq!(
1175+
discarded,
1176+
[
1177+
None,
1178+
Some((0, "session-a".to_string())),
1179+
Some((0, "session-c".to_string())),
1180+
]
1181+
);
1182+
assert_eq!(deduped[0].session_id.as_ref(), "session-b");
1183+
}
1184+
10691185
#[test]
10701186
fn dedupes_daily_sidechain_replay_after_an_equal_copy_from_another_session() {
10711187
let mut deduped_indexes = Default::default();

0 commit comments

Comments
 (0)