fix(statusline): correct session ID handling for accurate cost tracking - #451
fix(statusline): correct session ID handling for accurate cost tracking#451ryoppippi wants to merge 2 commits into
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Warning Rate limit exceeded@ryoppippi has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 55 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📥 CommitsReviewing files that changed from the base of the PR and between 6f2a249795aeb6f6c8066131977617e29b2c2039 and af19670. 📒 Files selected for processing (3)
WalkthroughThe changes refine session ID handling in the Claude Code usage data analysis tool. Documentation is updated to clarify two distinct session ID sources. The code now tracks both the derived and logged session IDs, adjusts data loading and filtering, and improves output formatting in the status line command. No functional or architectural changes were made. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant StatuslineCommand
participant DataLoader
User->>StatuslineCommand: Invoke statusline
StatuslineCommand->>DataLoader: loadSessionData()
DataLoader-->>StatuslineCommand: Return session data with sessionId and sessionIdInLog
StatuslineCommand->>StatuslineCommand: Filter and process session data
StatuslineCommand-->>User: Display status line with session info and cost
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @ryoppippi, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
I've addressed a critical bug where the statusline command was failing to display accurate session costs. Previously, the system incorrectly derived session IDs from file paths, leading to a mismatch with the actual session IDs logged in the JSONL data. My changes ensure that the correct session_id from the hook data is used for cost tracking, introducing a new sessionIdInLog field to properly align session data and provide accurate cost visibility.
Highlights
- Corrected Session ID Extraction: The statusline command now directly uses hookData.session_id for identifying sessions, eliminating the previous erroneous path-based extraction.
- Introduced sessionIdInLog: A new field, sessionIdInLog, has been added to distinguish the session ID as recorded in the JSONL data from the path-derived sessionId, ensuring accurate matching for cost calculation.
- Updated Session Matching Logic: The loadSessionData function and subsequent session matching in statusline.ts now correctly utilize sessionIdInLog to retrieve the associated session costs.
- Improved Daily Cost Calculation: The daily usage data loading in statusline.ts has been refined to first load all relevant daily data and then filter for the current day, improving robustness.
- Enhanced Documentation: The CLAUDE.md file has been updated to clarify the distinction and purpose of sessionId (path-derived) and sessionIdInLog (JSONL-logged).
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
commit: |
Deploying with
|
| Status | Name | Latest Commit | Preview URL | Updated (UTC) |
|---|---|---|---|---|
| ✅ Deployment successful! View logs |
ccusage-guide | af19670 | Commit Preview URL Branch Preview URL |
Aug 09 2025, 01:53 AM |
There was a problem hiding this comment.
Code Review
This pull request correctly fixes an issue where session costs were not being tracked accurately in the statusline. The change to use hookData.session_id directly and match it against the new sessionIdInLog field from the JSONL data is a solid improvement. The related schema and data loading changes are also well-implemented. I've identified one high-severity performance issue in src/commands/statusline.ts where all daily usage data is loaded into memory to filter for the current day's cost, and I've provided a more efficient solution.
There was a problem hiding this comment.
While this change correctly filters for today's data (fixing a previous bug where the date format was incorrect for filtering), it is inefficient to load all historical daily data into memory first. The previous approach of using since and until filters in loadDailyUsageData is more performant as it reduces the amount of data processed.
A better solution is to use the filters with the correctly formatted date string (YYYYMMDD) to fetch only today's data.
| const allDailyData = await loadDailyUsageData({ | |
| mode: 'auto', | |
| }); | |
| if (dailyData.length > 0) { | |
| const totals = calculateTotals(dailyData); | |
| // Filter for today's data only | |
| const todayData = allDailyData.filter(d => d.date === todayStr); | |
| const todayFilterStr = todayStr.replace(/-/g, ''); | |
| const todayData = await loadDailyUsageData({ | |
| since: todayFilterStr, | |
| until: todayFilterStr, | |
| mode: 'auto', | |
| }); |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/data-loader.ts (2)
161-162: Misleading inline comment forcwdfield
cwdis documented as “Claude Code version”, but a separateversionfield already exists two lines below.
Ifcwdstores the process working directory, please update the comment accordingly; otherwise rename the field to avoid confusion.
1064-1067: TODO & typo need follow-upThere is a TODO with a typo (“
seessionId”) that hints at renaming the path-derivedsessionId.
Either address the rename now or open an issue; leaving stale TODOs quickly gets forgotten.src/commands/statusline.ts (1)
81-89: Cheaper daily-cost lookupInstead of loading every day’s data and filtering in memory, call
loadDailyUsageData({ since: todayYYYMMDD, until: todayYYYMMDD }).
This avoids unnecessary cost calculations on historical data and speeds up the status-line render.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 6f1449c and efc3d67509ca0753d8b901bbcd411a7ebff023b2.
📒 Files selected for processing (3)
CLAUDE.md(1 hunks)src/commands/statusline.ts(3 hunks)src/data-loader.ts(5 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (CLAUDE.md)
**/*.{js,jsx,ts,tsx}: Lint code using ESLint MCP server (available via Claude Code tools)
Format code with ESLint (writes changes) usingbun run format
No console.log allowed except where explicitly disabled with eslint-disable
Do not use console.log. Use logger.ts instead.
Files:
src/commands/statusline.tssrc/data-loader.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (CLAUDE.md)
Type check with TypeScript using
bun typecheck
Files:
src/commands/statusline.tssrc/data-loader.ts
**/*.ts
📄 CodeRabbit Inference Engine (CLAUDE.md)
**/*.ts: File paths always use Node.js path utilities for cross-platform compatibility
Use.tsextensions for local file imports (e.g.,import { foo } from './utils.ts')
Prefer @praha/byethrow Result type over traditional try-catch for functional error handling
UseResult.try()for wrapping operations that may throw (JSON parsing, etc.)
UseResult.isFailure()for checking errors (more readable than!Result.isSuccess())
Use early return pattern (if (Result.isFailure(result)) continue;) instead of ternary operators
For async operations: create wrapper function withResult.try()then call it
Keep traditional try-catch only for: file I/O with complex error handling, legacy code that's hard to refactor
Always useResult.isFailure()andResult.isSuccess()type guards for better code clarity
Variables: start with lowercase (camelCase) - e.g.,usageDataSchema,modelBreakdownSchema
Types: start with uppercase (PascalCase) - e.g.,UsageData,ModelBreakdown
Constants: can use UPPER_SNAKE_CASE - e.g.,DEFAULT_CLAUDE_CODE_PATH
Only export constants, functions, and types that are actually used by other modules
Internal/private constants that are only used within the same file should NOT be exported
Always check if a constant is used elsewhere before making itexport constvs justconst
All test files must use current Claude 4 models, not outdated Claude 3 models
Test coverage should include both Sonnet and Opus models for comprehensive validation
Model names in tests must exactly match LiteLLM's pricing database entries
When adding new model tests, verify the model exists in LiteLLM before implementation
Tests depend on real pricing data from LiteLLM - failures may indicate model availability issues
Dynamic imports usingawait import()should only be used within test blocks to avoid tree-shaking issues
Mock data is created usingfs-fixturewithcreateFixture()for Claude data directory simulation
In-source testing pattern: Tests are written...
Files:
src/commands/statusline.tssrc/data-loader.ts
🧠 Learnings (5)
📚 Learning: 2025-07-19T10:58:04.397Z
Learnt from: CR
PR: ryoppippi/ccusage#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-19T10:58:04.397Z
Learning: Applies to **/*.ts : File paths always use Node.js path utilities for cross-platform compatibility
Applied to files:
src/commands/statusline.ts
📚 Learning: 2025-07-19T10:58:04.397Z
Learnt from: CR
PR: ryoppippi/ccusage#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-19T10:58:04.397Z
Learning: Applies to **/*.ts : Variables: start with lowercase (camelCase) - e.g., `usageDataSchema`, `modelBreakdownSchema`
Applied to files:
src/data-loader.ts
📚 Learning: 2025-07-19T10:58:04.397Z
Learnt from: CR
PR: ryoppippi/ccusage#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-19T10:58:04.397Z
Learning: Applies to **/*.ts : Mock data is created using `fs-fixture` with `createFixture()` for Claude data directory simulation
Applied to files:
src/data-loader.ts
📚 Learning: 2025-07-19T10:58:04.397Z
Learnt from: CR
PR: ryoppippi/ccusage#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-19T10:58:04.397Z
Learning: Applies to **/*.ts : Cost calculations require exact model name matches with LiteLLM's database
Applied to files:
src/data-loader.ts
📚 Learning: 2025-07-19T10:58:04.397Z
Learnt from: CR
PR: ryoppippi/ccusage#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-19T10:58:04.397Z
Learning: Applies to **/*.ts : Tests depend on real pricing data from LiteLLM - failures may indicate model availability issues
Applied to files:
src/data-loader.ts
🧬 Code Graph Analysis (1)
src/data-loader.ts (1)
src/_types.ts (1)
sessionIdSchema(13-15)
🪛 ESLint
src/commands/statusline.ts
[error] 59-59: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 59-59: Unsafe member access .session_id on an error typed value.
(ts/no-unsafe-member-access)
[error] 65-65: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 65-65: Unsafe member access .sessionIdInLog on an error typed value.
(ts/no-unsafe-member-access)
[error] 86-86: Unsafe member access .date on an error typed value.
(ts/no-unsafe-member-access)
src/data-loader.ts
[error] 161-161: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 161-161: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 161-161: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 161-161: Unsafe member access .string on an error typed value.
(ts/no-unsafe-member-access)
[error] 161-161: Unsafe member access .optional on an error typed value.
(ts/no-unsafe-member-access)
[error] 162-162: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 162-162: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 162-162: Unsafe member access .optional on an error typed value.
(ts/no-unsafe-member-access)
[error] 230-230: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 230-230: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 230-230: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 230-230: Unsafe member access .string on an error typed value.
(ts/no-unsafe-member-access)
[error] 230-230: Unsafe member access .optional on an error typed value.
(ts/no-unsafe-member-access)
[error] 1066-1066: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 1066-1066: Unsafe member access .sessionId on an error typed value.
(ts/no-unsafe-member-access)
[error] 1123-1123: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 1123-1123: Unsafe member access .sessionIdInLog on an error typed value.
(ts/no-unsafe-member-access)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Workers Builds: ccusage-guide
🔇 Additional comments (3)
src/data-loader.ts (1)
1121-1124: Naming divergence may confuse downstream usersAggregated objects expose both
sessionId(path-derived) andsessionIdInLog(log-derived). Ensure downstream callers always pick the intended one; otherwise consider deprecating the path-derived ID in a minor release.src/commands/statusline.ts (1)
165-166: Zero cost vs. “N/A” distinctionWith the new logic, a legitimate zero-cost session (
sessionCost === 0) is formatted as “$0.00”, but an unavailable session shows “N/A”.
This is correct and removes prior ambiguity—nice.CLAUDE.md (1)
90-93: Documentation LGTMClear distinction between the two session-ID concepts. Thanks for addressing the confusion.
There was a problem hiding this comment.
🛠️ Refactor suggestion
Guard against missing session_id and reduce I/O
hookData.session_id is assumed to exist, yet the schema marks it optional.
This can silently pass undefined to the filter and trigger a full (and expensive) scan of all sessions.
-const sessionId = hookData.session_id;
+const sessionId = hookData.session_id;
+if (sessionId == null) {
+ // No session available – skip per-session lookup
+}Additionally, loadSessionData() without a date filter re-parses every JSONL file on each status-line refresh.
Consider passing { since: todayStr.replace(/-/g, ''), until: todayStr.replace(/-/g, '') } to cap the search window to “today”.
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 ESLint
[error] 59-59: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 59-59: Unsafe member access .session_id on an error typed value.
(ts/no-unsafe-member-access)
[error] 65-65: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 65-65: Unsafe member access .sessionIdInLog on an error typed value.
(ts/no-unsafe-member-access)
🤖 Prompt for AI Agents
In src/commands/statusline.ts around lines 59 to 66, add a guard to check if
hookData.session_id is defined before using it to filter sessions to prevent
passing undefined and triggering a full scan. Also, modify the call to
loadSessionData() to include a date filter with since and until set to today's
date string without dashes to limit the search to today's sessions and reduce
I/O overhead.
There was a problem hiding this comment.
🛠️ Refactor suggestion
Stronger validation for sessionIdInLog is advisable
sessionIdInLog is currently a bare z.string().optional().
Re-using the existing sessionIdSchema (and making it optional) gives the same flexibility while retaining the non-empty constraint and brand.
-sessionIdInLog: z.string().optional(), // Session ID as logged in the JSONL file
+sessionIdInLog: sessionIdSchema.optional(), // Session ID as logged in the JSONL file📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const sessionUsageSchema = z.object({ | |
| sessionId: sessionIdSchema, | |
| sessionIdInLog: z.string().optional(), // Session ID as logged in the JSONL file | |
| projectPath: projectPathSchema, | |
| export const sessionUsageSchema = z.object({ | |
| sessionId: sessionIdSchema, | |
| sessionIdInLog: sessionIdSchema.optional(), // Session ID as logged in the JSONL file | |
| projectPath: projectPathSchema, |
🧰 Tools
🪛 ESLint
[error] 228-241: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 228-228: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 228-228: Unsafe member access .object on an error typed value.
(ts/no-unsafe-member-access)
[error] 229-229: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 230-230: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
[error] 230-230: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 230-230: Unsafe call of a(n) error type typed value.
(ts/no-unsafe-call)
[error] 230-230: Unsafe member access .string on an error typed value.
(ts/no-unsafe-member-access)
[error] 230-230: Unsafe member access .optional on an error typed value.
(ts/no-unsafe-member-access)
[error] 231-231: Unsafe assignment of an error typed value.
(ts/no-unsafe-assignment)
🤖 Prompt for AI Agents
In src/data-loader.ts around lines 228 to 231, the sessionUsageSchema defines
sessionIdInLog as an optional plain string, which lacks the non-empty and
branded validation of sessionIdSchema. To fix this, replace
z.string().optional() with sessionIdSchema.optional() for sessionIdInLog to
enforce the same validation rules while keeping it optional.
efc3d67 to
6f2a249
Compare
Previously, statusline was trying to extract session IDs from transcript paths, but should use the session_id field directly from hook data. Changes: - Add loadSessionUsageById() function to find and load specific session JSONL files - Update statusline command to use session_id from hook data to find the correct JSONL file - Remove path parsing logic and use direct session ID lookup - Add comprehensive tests with vitest environment mocking and afterEach cleanup - Update CLAUDE.md to clarify the naming confusion between project directories and actual sessions
6f2a249 to
af19670
Compare
Summary
Problem
The statusline command was incorrectly extracting session IDs from the transcript path, which didn't match the actual session IDs stored in JSONL data. This caused session costs to always show as 0 or N/A.
Solution
Test Plan
Summary by CodeRabbit
New Features
Bug Fixes
Documentation