Skip to content

Commit e7a7ee4

Browse files
authored
fix(all): keep sessions last active on the --until day (ccusage#2008)
* fix(all): keep sessions last active on the --until day Session reports in the unified loader and the qwen adapter bounded the window by comparing a session's `lastActivity` against `--since`/`--until` as text after stripping dashes. `lastActivity` is a full RFC 3339 timestamp, so `20260704T18:00:00.000Z` sorted after the `20260704` bound and every session whose last activity fell on the `--until` day dropped out of the report, while `--since` ignored `--timezone` because the comparison used the UTC date. Replace both copies with one `ccusage-adapter-common` helper that parses the timestamp, takes its calendar day in the report timezone the same way `LoadedEntry::date` does, and reuses `date_within_range`, so session reports treat the bounds as inclusive whole days like daily reports. * test(adapter): cover the session window edge cases from review Document `filter_session_summaries_by_last_activity` in the crate README, add `--since`-only and missing/unparseable `lastActivity` cases for the helper, and restore a fixture-backed Qwen session test that checks the `--until` day boundary in the report timezone through the JSON report. * test(qwen): cover the session --until boundary through the CLI The hand-rolled Qwen unit test replayed load, summarize, and filter itself, so it would keep passing if `qwen session` stopped applying the window. Replace it with an integration test that runs the real binary with `--since`/`--until` in America/Los_Angeles, asserts the JSON report, and snapshots the session table. * fix(rust): show Last Activity in the report timezone and keep TZDIR in the Qwen CLI test The Qwen CLI test clears the child environment, which drops the TZDIR that the sandboxed Nix test derivation sets so jiff can resolve named zones. The binary then rejected `--timezone America/Los_Angeles` on CI while passing locally, where the system zoneinfo is found without it. Forward TZDIR when it is set. The session table's Last Activity column truncated the RFC 3339 `lastActivity` to its UTC date, so a session selected for the 23rd in America/Los_Angeles rendered as the 24th. Format the date in the report timezone like every other date column; JSON output keeps the full timestamp, and existing table snapshots all report in UTC, so only the Qwen snapshot changes. * test(claude): check the session window drops the day after --until With a single session the unified session CLI test only caught sessions wrongly dropped on the `--until` day; it would still pass without any window filter. Add a second session last active just after local midnight so the asserted total also fails when the filter keeps too much. Also note in the session guide that the Last Activity table column shows the date in the report timezone while JSON keeps the RFC 3339 timestamp. * docs(session): link the Last Activity note to the JSON field reference The note now defines how the table column relates to the JSON `lastActivity` field, so point it at that field's description in the JSON output guide.
1 parent 7db7a30 commit e7a7ee4

10 files changed

Lines changed: 360 additions & 89 deletions

File tree

‎docs/guide/session-reports.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ Sessions are displayed using the last two segments of their full identifier:
9191
- **Input/Output Tokens**: Total tokens exchanged in the conversation
9292
- **Cache Tokens**: Cache creation and read tokens for context efficiency
9393
- **Cost**: Estimated USD cost for the usage shown; without a date filter, the entire conversation
94-
- **Last Activity**: Date of the most recent message included in the report
94+
- **Last Activity**: Date of the most recent message included in the report, shown in the report timezone (`--timezone`); JSON output keeps the full RFC 3339 [`lastActivity`](/guide/json-output#session-reports-1) timestamp
9595

9696
### Sorting
9797

‎rust/adapters/common/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ layers.
1313
so output does not depend on worker scheduling, and `--single-thread` collapses
1414
to a plain sequential read.
1515
- `filter_loaded_entries_by_date` — the shared `--since`/`--until` filter.
16+
- `filter_session_summaries_by_last_activity` — the same window applied to
17+
session summaries by the local day of their last activity.
1618
- `jsonl` — the streaming JSONL parsing helpers.
1719
- `report::print_table_for_agent` — the usage table for adapters whose rows are
1820
plain `UsageSummary` values, parameterized by agent name.
@@ -24,6 +26,7 @@ layers.
2426
- `collect_files_with_extension`
2527
- `collect_files_matching`
2628
- `filter_loaded_entries_by_date`
29+
- `filter_session_summaries_by_last_activity`
2730
- `chunk_file_indexes_by_size`
2831
- `read_files_parallel`
2932

‎rust/adapters/common/src/lib.rs‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ use std::{
44
thread,
55
};
66

7-
use ccusage_core::{LoadedEntry, cli::SharedArgs, date_within_range};
7+
use ccusage_core::{
8+
LoadedEntry, UsageSummary, cli::SharedArgs, date_within_range, format_date_tz,
9+
parse_ts_timestamp, parse_tz,
10+
};
811

912
pub mod jsonl;
1013
pub mod report;
@@ -58,6 +61,31 @@ pub fn filter_loaded_entries_by_date(entries: &mut Vec<LoadedEntry>, shared: &Sh
5861
});
5962
}
6063

64+
/// Keeps the sessions whose last activity falls on a day inside the
65+
/// `--since`/`--until` window, with the day taken in the report timezone the
66+
/// same way `LoadedEntry::date` is.
67+
pub fn filter_session_summaries_by_last_activity(
68+
rows: &mut Vec<UsageSummary>,
69+
shared: &SharedArgs,
70+
) {
71+
if shared.since.is_none() && shared.until.is_none() {
72+
return;
73+
}
74+
let timezone = parse_tz(shared.timezone.as_deref());
75+
rows.retain(|row| {
76+
row.last_activity
77+
.as_deref()
78+
.and_then(parse_ts_timestamp)
79+
.is_some_and(|timestamp| {
80+
date_within_range(
81+
&format_date_tz(timestamp, timezone.as_ref()),
82+
shared.since.as_deref(),
83+
shared.until.as_deref(),
84+
)
85+
})
86+
});
87+
}
88+
6189
pub fn chunk_file_indexes_by_size(files: &[PathBuf], chunk_count: usize) -> Vec<Vec<usize>> {
6290
// Callers derive the count from available_parallelism, which can be 0 for a
6391
// caller that clamps against an empty file list; one chunk still returns
@@ -139,9 +167,128 @@ where
139167

140168
#[cfg(test)]
141169
mod tests {
142-
use super::{chunk_file_indexes_by_size, collect_files_matching, read_files_parallel};
170+
use ccusage_core::{UsageSummary, cli::SharedArgs};
143171
use ccusage_test_support::Fixture;
144172

173+
use super::{
174+
chunk_file_indexes_by_size, collect_files_matching,
175+
filter_session_summaries_by_last_activity, read_files_parallel,
176+
};
177+
178+
fn session_summary(session_id: &str, last_activity: &str) -> UsageSummary {
179+
UsageSummary {
180+
date: None,
181+
month: None,
182+
week: None,
183+
session_id: Some(session_id.to_string()),
184+
project_path: None,
185+
last_activity: Some(last_activity.to_string()),
186+
first_activity: None,
187+
input_tokens: 0,
188+
output_tokens: 0,
189+
cache_creation_tokens: 0,
190+
cache_read_tokens: 0,
191+
extra_total_tokens: 0,
192+
total_cost: 0.0,
193+
credits: None,
194+
message_count: None,
195+
models_used: Vec::new(),
196+
model_breakdowns: Vec::new(),
197+
project: None,
198+
versions: None,
199+
}
200+
}
201+
202+
fn filtered_session_ids(shared: &SharedArgs) -> Vec<String> {
203+
let mut rows = vec![
204+
session_summary("before", "2026-02-22T23:59:59.000Z"),
205+
session_summary("start-of-day", "2026-02-23T00:00:00.000Z"),
206+
session_summary("end-of-day", "2026-02-23T23:59:59.999Z"),
207+
session_summary("after", "2026-02-24T00:00:00.000Z"),
208+
];
209+
filter_session_summaries_by_last_activity(&mut rows, shared);
210+
rows.into_iter().filter_map(|row| row.session_id).collect()
211+
}
212+
213+
#[test]
214+
fn session_window_bounds_are_inclusive_of_the_whole_day() {
215+
let shared = SharedArgs {
216+
since: Some("20260223".to_string()),
217+
until: Some("20260223".to_string()),
218+
timezone: Some("UTC".to_string()),
219+
..SharedArgs::default()
220+
};
221+
222+
assert_eq!(
223+
filtered_session_ids(&shared),
224+
["start-of-day", "end-of-day"]
225+
);
226+
}
227+
228+
#[test]
229+
fn session_window_takes_the_day_in_the_report_timezone() {
230+
// Asia/Tokyo is UTC+9, so the window shifts nine hours earlier in UTC.
231+
let shared = SharedArgs {
232+
since: Some("20260223".to_string()),
233+
until: Some("20260223".to_string()),
234+
timezone: Some("Asia/Tokyo".to_string()),
235+
..SharedArgs::default()
236+
};
237+
238+
assert_eq!(filtered_session_ids(&shared), ["before", "start-of-day"]);
239+
}
240+
241+
#[test]
242+
fn session_window_with_only_until_keeps_everything_through_that_day() {
243+
let shared = SharedArgs {
244+
until: Some("20260223".to_string()),
245+
timezone: Some("UTC".to_string()),
246+
..SharedArgs::default()
247+
};
248+
249+
assert_eq!(
250+
filtered_session_ids(&shared),
251+
["before", "start-of-day", "end-of-day"]
252+
);
253+
}
254+
255+
#[test]
256+
fn session_window_with_only_since_keeps_everything_from_that_day() {
257+
let shared = SharedArgs {
258+
since: Some("20260223".to_string()),
259+
timezone: Some("UTC".to_string()),
260+
..SharedArgs::default()
261+
};
262+
263+
assert_eq!(
264+
filtered_session_ids(&shared),
265+
["start-of-day", "end-of-day", "after"]
266+
);
267+
}
268+
269+
#[test]
270+
fn session_window_drops_rows_without_a_parseable_last_activity() {
271+
let missing = UsageSummary {
272+
last_activity: None,
273+
..session_summary("missing", "")
274+
};
275+
let unparsable = session_summary("unparsable", "2026-02-23");
276+
for shared in [
277+
SharedArgs {
278+
since: Some("20260101".to_string()),
279+
..SharedArgs::default()
280+
},
281+
SharedArgs {
282+
until: Some("20991231".to_string()),
283+
..SharedArgs::default()
284+
},
285+
] {
286+
let mut rows = vec![missing.clone(), unparsable.clone()];
287+
filter_session_summaries_by_last_activity(&mut rows, &shared);
288+
assert!(rows.is_empty(), "{:?}/{:?}", shared.since, shared.until);
289+
}
290+
}
291+
145292
#[test]
146293
fn collects_nested_files_accepted_by_the_predicate() {
147294
let fixture = Fixture::new();

‎rust/adapters/qwen/src/lib.rs‎

Lines changed: 4 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use ccusage_adapter_common::{
2-
collect_files_with_extension, filter_loaded_entries_by_date, read_files_parallel,
2+
collect_files_with_extension, filter_loaded_entries_by_date,
3+
filter_session_summaries_by_last_activity, read_files_parallel,
34
};
45
use ccusage_core::*;
56

@@ -10,7 +11,7 @@ mod report;
1011

1112
use crate::{
1213
Result,
13-
cli::{AgentCommandArgs, AgentReportKind, SharedArgs},
14+
cli::{AgentCommandArgs, AgentReportKind},
1415
print_json_or_jq, print_usage_table, sort_summaries, wants_json,
1516
};
1617

@@ -27,7 +28,7 @@ pub fn run(args: AgentCommandArgs) -> Result<()> {
2728
summarize_entries(&entries, args.kind)?
2829
};
2930
if args.kind == AgentReportKind::Session {
30-
filter_session_summaries(&mut rows, &args.shared);
31+
filter_session_summaries_by_last_activity(&mut rows, &args.shared);
3132
}
3233
sort_summaries(&mut rows, &args.shared.order, |row| {
3334
ccusage_core::summary_period(row)
@@ -50,22 +51,6 @@ pub fn run(args: AgentCommandArgs) -> Result<()> {
5051
Ok(())
5152
}
5253

53-
fn filter_session_summaries(rows: &mut Vec<crate::UsageSummary>, shared: &SharedArgs) {
54-
if shared.since.is_some() || shared.until.is_some() {
55-
let since = shared.since.as_deref().map(|value| value.replace('-', ""));
56-
let until = shared.until.as_deref().map(|value| value.replace('-', ""));
57-
rows.retain(|row| {
58-
let date = row
59-
.last_activity
60-
.as_deref()
61-
.unwrap_or_default()
62-
.replace('-', "");
63-
since.as_ref().is_none_or(|bound| &date >= bound)
64-
&& until.as_ref().is_none_or(|bound| &date <= bound)
65-
});
66-
}
67-
}
68-
6954
pub fn has_data() -> bool {
7055
paths::discover_chat_files().is_ok_and(|files| !files.is_empty())
7156
}
@@ -76,7 +61,6 @@ mod tests {
7661
use serde_json::json;
7762

7863
use super::*;
79-
use crate::UsageSummary;
8064
use crate::cli::{CostMode, SharedArgs};
8165

8266
#[test]
@@ -144,47 +128,4 @@ mod tests {
144128
}])
145129
);
146130
}
147-
148-
#[test]
149-
fn filters_session_summaries_with_iso_date_bounds() {
150-
let mut rows = vec![
151-
usage_summary("before", "2026-02-22"),
152-
usage_summary("inside", "2026-02-23"),
153-
usage_summary("after", "2026-02-24"),
154-
];
155-
let shared = SharedArgs {
156-
since: Some("2026-02-23".to_string()),
157-
until: Some("2026-02-23".to_string()),
158-
..SharedArgs::default()
159-
};
160-
161-
filter_session_summaries(&mut rows, &shared);
162-
163-
assert_eq!(rows.len(), 1);
164-
assert_eq!(rows[0].session_id.as_deref(), Some("inside"));
165-
}
166-
167-
fn usage_summary(session_id: &str, last_activity: &str) -> UsageSummary {
168-
UsageSummary {
169-
date: None,
170-
month: None,
171-
week: None,
172-
session_id: Some(session_id.to_string()),
173-
project_path: None,
174-
last_activity: Some(last_activity.to_string()),
175-
first_activity: None,
176-
input_tokens: 0,
177-
output_tokens: 0,
178-
cache_creation_tokens: 0,
179-
cache_read_tokens: 0,
180-
extra_total_tokens: 0,
181-
total_cost: 0.0,
182-
credits: None,
183-
message_count: None,
184-
models_used: Vec::new(),
185-
model_breakdowns: Vec::new(),
186-
project: None,
187-
versions: None,
188-
}
189-
}
190131
}

‎rust/crates/ccusage-adapter-all/src/lib.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ mod types;
55
use ccusage_adapter_codex::CodexGroup;
66
#[cfg(test)]
77
use ccusage_adapter_codex::CodexModelUsage;
8-
use ccusage_adapter_common::filter_loaded_entries_by_date;
8+
use ccusage_adapter_common::{
9+
filter_loaded_entries_by_date, filter_session_summaries_by_last_activity,
10+
};
911
use ccusage_core::*;
1012

1113
mod adapter {

0 commit comments

Comments
 (0)