Skip to content

Commit 72b8ad4

Browse files
ryoppippiigorovh
andauthored
fix(all): count OpenCode Claude Agent turns once in unified reports (#2007)
* fix(opencode): count Claude Agent sessions once in unified reports OpenCode's claude-agent provider runs Claude Code, which writes its own transcript, so unified reports counted every Claude Agent turn twice. OpenCode v2 rows record the Claude Code session as content[].native.sessionID. Unified reports now skip OpenCode rows whose native session has a Claude transcript on disk. The Claude transcript holds the same tokens plus the resolved model ID, while OpenCode stores only the `opus` alias, which ccusage priced as an older Opus. Skipped sessions still count as covered, so the cumulative session_v2 aggregate cannot bring the usage back. When the transcript is gone, the OpenCode rows are counted. `ccusage opencode` keeps every row. Refs #2004 * docs(opencode): explain Claude Agent sessions in unified reports Refs #2004 * fix(all): skip Claude Agent rows only where Claude counted them The first fix skipped an OpenCode claude-agent row whenever a Claude transcript file with the row's native session ID existed on disk. A file existing is not the same as Claude counting the usage: a transcript with no usage lines, one holding only subagent usage, an unreadable one, or one outside the Claude source's date range made the OpenCode rows disappear while Claude counted nothing, so unified reports lost usage. Claude's unified load now reports the (session ID, date) pairs of the main-thread entries it counts, after its date filter, and sends them to the OpenCode load over a channel. OpenCode loads in parallel, waits for that set, and drops a claude-agent row only when its native session was counted on the row's date in the Claude source's timezone. A failed Claude load sends nothing, which keeps every row. Sidechain entries are left out because OpenCode only records main-thread turns. This also removes the second walk of the Claude projects directories. OpenCode now returns rows paired with their native session instead of dropping them while loading. The rows stay message entries during the load, so the cumulative session_v2 aggregate stays suppressed for their sessions in every data directory, which the in-loader skip leaked when the aggregate sat in a second OPENCODE_DATA_DIR root. The native link is read in the same parse as the row and only for the claude-agent provider. The match is per session day, not per turn: OpenCode sets native.messageID to the transcript line uuid, not the API message id, and one OpenCode step sums several API calls, so rows do not map one-to-one to Claude entries. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): describe when unified reports skip Claude Agent rows The docs said OpenCode rows count only when the Claude Code log is gone. Rows now count unless the Claude source counted the same session on the same day, so describe that rule and the cases it keeps: a log with no usage for the day, subagent-only usage, and days outside the Claude source's date range. The adapter README records why the match is per session day rather than per turn, and the assumption it rests on: the Claude transcript holds every main-thread turn OpenCode records for that session. Refs #2004 Co-authored-by: igorovh <[email protected]> * refactor(all): carry Claude Agent links on each entry and share the main-thread rule The OpenCode loader kept each row's Claude Code session in a side map keyed by entry id and joined it back after the load, so the link could drift from its entry and needed extra clones and accumulators. Entries now travel as (entry, native session) pairs from the database read onward; legacy JSON and aggregate rows carry no link. The sidechain filter and (session, date) mapping existed twice, in the daily and session paths. One helper now owns the main-thread rule and dedups borrowed pairs before owning them, so a date string is cloned once per session day instead of once per entry. The daily loader takes the collector as a function instead of a boolean flag. The channel comment claimed a failed Claude load keeps every OpenCode row. It does not: the dropped sender only stops OpenCode from blocking, and the unified report still fails on the Claude error, as on main. Refs #2004 Co-authored-by: igorovh <[email protected]> * test(all): cover Claude Agent dedup across timezones and midnight Every unified test ran both sources in UTC, so dating an OpenCode row in the Claude source's timezone was untested. A Tokyo-configured Claude source must drop the row whose Tokyo date it counted and keep the row whose Tokyo date it did not, even though both share a UTC date with Claude usage. The midnight test pins the known limit of per-session-day matching: a row is dated by its turn's start, Claude dates each call, so a turn that starts before midnight and is logged after it is counted by both sources. Matching on the transcript uuid would not fix this: Claude's message-id dedup keeps one of several lines sharing an API message, which need not be the line whose uuid OpenCode recorded, and one OpenCode row sums several API calls. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): note the limits of Claude Agent dedup State that unified reports count Claude Agent turns under Claude only when Claude Code's own log has them, that a turn crossing midnight in the Claude source's timezone can be counted twice, and that only v2 session_message rows can carry the link, since OpenCode added the provider after moving to SQLite v2. Refs #2004 Co-authored-by: igorovh <[email protected]> * perf(opencode): read Claude Agent links only for claude-agent rows Every v2 row deserialized its whole content array through serde_json::Value, because the lenient helpers build a Value per field, so message text was materialized just to find content[].native.sessionID on the few rows that carry one. The link is now read in a second, typed pass that only claude-agent rows take, and derived structs skip every other field without building it. A malformed part leaves the row unlinked instead of dropping it. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(all): skip Claude Agent rows of every session Claude counted Claude dedups a turn repeated across sessions, such as a resumed or forked transcript, down to one surviving entry, so the counted set held only the survivor's session. An OpenCode row linked to the other copy's session was kept and its turn counted twice. The push functions now hand back the entry they discard, and the loaders keep main-thread copies from other sessions, so every session of a counted dedup group matches. Session reports matched per session day, but the Claude session row holds all of that session's usage, including days outside the Claude window. They now skip every row whose Claude session the report includes, which also covers turns that cross midnight; daily-family reports keep matching per day in the Claude source's timezone. load_entries is no longer used outside the OpenCode crate, which the hawk check flagged, so it is crate-private now. The pair type it returned is exported as LinkedEntry, which the unified loader names. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): qualify how unified reports match Claude Agent rows Matching is per Claude Code session, and per day in the daily family, so the docs no longer promise exactly-once counting. They spell out the session-report rule and the midnight cases: a turn that starts before midnight can be counted twice, and --until on its start day leaves out the calls Claude logs after midnight. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(claude): skip Claude Agent rows only for fully counted sessions Session reports marked a copy's session covered as soon as the session dedup kept was reported, without checking the copy's own session. Claude session reports keep or drop whole sessions by last activity, so a resumed or forked session running past --until was left out while the session it continues stayed in, and every OpenCode row linked to it, including its own turns, was dropped with nobody counting them. A session is now covered only when every session its main-thread usage lives under is reported. Daily-family reports were not affected, since their pairs are filtered by the date each usage is counted on. The daily loader kept each discarded cross-session copy whole, even for plain `ccusage claude daily`. It now keeps only the survivor index and the copy's session, and dates the copy on the day its survivor counts, which is when the turn's usage is reported. Both loaders now take the sidechain flag from the survivor, so copies and survivors follow one rule. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(opencode): keep Claude Agent links past malformed content parts The typed link pass failed as a whole when any content part, its native value, or sessionID had an unexpected shape, so one bad part unlinked a row that carried a valid link and its turn was counted twice. Lenient wrappers now read each part, native value, and sessionID on their own and skip any other shape through IgnoredAny, still without building a serde_json::Value. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): explain Claude Agent matching for resumed sessions Session reports now skip a resumed or forked session's OpenCode rows only when the session it continues is reported too, so the guide and adapter README say so. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(claude): let a session's own counted turns decide its coverage The round-3 rule left a session uncovered whenever any of its usage lived under an unreported session. Files are read in path order, so a parent's copy of an inherited turn often survives dedup; with a --since that leaves the parent out and keeps the fork, the fork landed in that set, OpenCode kept the fork's own rows, and Claude counted the same turns under the fork's session row, double counting them. A session's own surviving main-thread usage now decides: it is covered exactly when the report includes it. Only a session whose usage all survives under other sessions needs every one of those included. The remaining error is an undercount of a fork's rows for repeated turns when the fork is reported without its parent, which is smaller than double counting its own turns, since OpenCode already drops its own fork copies. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(opencode): skip non-string Claude Agent session IDs without unlinking The lenient link pass read sessionID as a String inside an object, so an object-valued ID failed the deserialize mid-object, which cannot be recovered, and the whole row lost a valid link from another part. A string-only lenient type now drains objects and arrays through IgnoredAny and reads them as absent. The lenient object, string, and array wrappers move to the shared jsonl module next to lenient_vec, since they are generic serde helpers rather than OpenCode parsing. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): state the resumed-session rule and its residual undercount Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): describe both directions of the resumed-session residual The docs said Claude's dedup often keeps a repeated turn under the parent and that the only residual error is an undercount. Among equal copies dedup keeps the first read, files are sorted by path, and transcripts are named by UUID, so which session keeps the turn is effectively arbitrary. With a Claude date window that includes one session but not the other, a repeated turn can be left out or counted twice, depending on where the kept copy lives and which session OpenCode logged it under. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(claude): match Claude Agent rows by the recorded session ID OpenCode links a claude-agent row to the session ID Claude Code records in the transcript, but the session-report coverage set used the path-derived session ID, which differs for a renamed or copied transcript, so the linked row was kept and counted twice. Session rows stay keyed by path, so the reported check still uses it, while the covered set and copy tracking now use the recorded ID, as the daily loader already does. Refs #2004 Co-authored-by: igorovh <[email protected]> * fix(opencode): tolerate repeated keys in Claude Agent links Derived structs reject a repeated field, so a content part with two sessionID or native keys, or a row with two content keys, failed the whole link pass and unlinked the row. A shared FirstField wrapper now reads the first usable value of one field, skips the rest and any other shape through IgnoredAny, and still builds no serde_json::Value. It replaces LenientObject, which nothing else used. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): tie session-report skips to counted main-thread usage A session report can include a Claude row with only subagent usage, which does not cover OpenCode rows, so the guide now says the session must have counted main-thread usage. It also says which session keeps a repeated turn only matters when one of them is left out, and links the unified reports guide. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): state the session-report rule in terms of transcripts The docs said a session with its own turns is skipped exactly when the report includes it. A resumed transcript repeats earlier turns under the original session ID, so one session's kept turns can span several transcripts, and the session is skipped only when every one of them is included. When a Claude window includes only some of them, the session's OpenCode rows are kept and the turns Claude counts in the included transcript are counted twice. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): state both branches of the session-report coverage rule The docs merged the two branches of main_thread_sessions into one rule and dropped the second from the README. A session whose own turns survive is decided only by the transcripts holding them; only a session with no surviving turns of its own falls back to the transcripts holding its kept copies. The docs also said dedup keeps the first copy read, though it prefers main-thread copies and more tokens first, and they promised a fork's own turns are never counted twice, which the split-transcript case contradicts. The left-out and counted-twice consequences now follow from the stated rule. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): complete the dedup tiebreaks and Claude Agent coverage wording The README listed only the main-thread and token tiebreaks, though both loaders then prefer a copy with speed metadata and the daily loader compares cost first. The guide said a session is skipped where it means the session's OpenCode rows, the copies-branch sentence missed that sidechain survivors do not count as a session's own, and the double count is now stated for both branches of the rule. Refs #2004 Co-authored-by: igorovh <[email protected]> * docs(opencode): spell out which turns decide a Claude Agent skip The double-count clause said "the kept turns a session is judged by", which was hard to parse. Name them: a session's own surviving main-thread turns, or its kept copies when it has none. Refs #2004 Co-authored-by: igorovh <[email protected]> --------- Co-authored-by: igorovh <[email protected]> Co-authored-by: igorovh <[email protected]>
1 parent 66e1857 commit 72b8ad4

11 files changed

Lines changed: 1618 additions & 111 deletions

File tree

‎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/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 |

‎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)