-
-
Notifications
You must be signed in to change notification settings - Fork 317
feat(statusline): add costSource option to use Claude Code session cost #571
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- Update statuslineHookJsonSchema to support optional cost field from Claude Code - Add costSource argument with choices: 'auto' (default), 'ccusage', 'cc' - 'auto': prefer Claude Code cost if available, fallback to ccusage calculation - 'ccusage': always calculate using ccusage's token-based calculation - 'cc': always use Claude Code's provided cost (show N/A if unavailable) - Add comprehensive tests for the new cost field schema validation - Maintain backward compatibility with existing statusline input format
|
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. Caution Review failedThe pull request is closed. WalkthroughAdds a configurable costSource to the statusline command and config schema, extends the statusline hook schema with an optional cost object, and refactors statusline cost computation to select between Claude Code cost, calculated ccusage cost, or auto preference. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant CLI as statusline command
participant Hook as Hook Data
participant Usage as ccusage loader
User->>CLI: run statusline --cost-source {auto|cc|ccusage}
alt costSource == cc
CLI->>Hook: read cost.total_cost_usd
Note over CLI,Hook: Use Claude Code-reported cost
else costSource == ccusage
CLI->>Usage: loadSessionUsageById(mode: "auto")
Usage-->>CLI: { totalCost }
Note over CLI,Usage: Compute cost from usage
else costSource == auto
CLI->>Hook: read cost.total_cost_usd
alt cost available
Note over CLI,Hook: Prefer Claude Code cost
else no cost
CLI->>Usage: loadSessionUsageById(mode: "auto")
Usage-->>CLI: { totalCost }
Note over CLI,Usage: Fallback to ccusage
end
end
CLI-->>User: render statusline with session cost
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (3)
✨ 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/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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!
This pull request introduces a new costSource option for the statusline command, allowing users to specify how session costs are determined. It enables direct consumption of cost data provided by Claude Code's statusline hook, offering flexibility to prefer Claude Code's reported cost, always calculate using ccusage, or automatically fall back to ccusage if Claude Code's cost is unavailable.
Highlights
- Enhanced Cost Reporting: Introduced a costSource CLI option (auto, ccusage, cc) for the statusline command, providing granular control over how session costs are displayed.
- Schema Extension: The statuslineHookJsonSchema has been updated to include an optional cost field, allowing Claude Code to directly provide session cost details.
- Flexible Cost Calculation: Refactored the session cost retrieval logic to support the new costSource options, prioritizing Claude Code's data when available and configured, or falling back to ccusage calculations.
- Robust Validation: Added comprehensive tests to ensure the new cost field in the statusline hook schema is correctly parsed and validated, maintaining backward compatibility.
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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
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: |
- Update config-schema.json to include new costSource option - Remove unnecessary vitest import (globals are available)
Deploying with
|
| Status | Name | Latest Commit | Preview URL | Updated (UTC) |
|---|---|---|---|---|
| ✅ Deployment successful! View logs |
ccusage-guide | b51e0a0 | Commit Preview URL Branch Preview URL |
Aug 22 2025, 11:01 AM |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a costSource option for the statusline command, allowing users to choose between using the cost provided by Claude Code or calculating it via ccusage. The changes include updating the JSON schema to accept cost data from Claude Code, adding the new CLI option, and implementing the logic to handle different cost sources. The implementation is well-tested with new schema validation tests.
My main feedback is to refactor the session cost calculation logic in src/commands/statusline.ts to reduce code duplication and improve readability. By extracting the duplicated logic into a helper function and using a switch statement, the code becomes more maintainable and easier to understand.
Overall, this is a great feature addition that enhances the flexibility of the statusline.
| // Determine session cost based on cost source | ||
| const sessionCost = await (async (): Promise<number | undefined> => { | ||
| const costSource = ctx.values.costSource; | ||
|
|
||
| // If 'cc' mode and cost is available from Claude Code, use it | ||
| if (costSource === 'cc' && hookData.cost?.total_cost_usd != null) { | ||
| return hookData.cost.total_cost_usd; | ||
| } | ||
|
|
||
| // If 'ccusage' mode, always calculate using ccusage | ||
| if (costSource === 'ccusage') { | ||
| return Result.pipe( | ||
| Result.try({ | ||
| try: async () => loadSessionUsageById(sessionId, { | ||
| mode: 'auto', | ||
| offline: mergedOptions.offline, | ||
| }), | ||
| catch: error => error, | ||
| })(), | ||
| Result.map(sessionCost => sessionCost?.totalCost), | ||
| Result.inspectError(error => logger.error('Failed to load session data:', error)), | ||
| Result.unwrap(undefined), | ||
| ); | ||
| } | ||
|
|
||
| // If 'auto' mode (default), prefer Claude Code cost, fallback to ccusage | ||
| if (costSource === 'auto') { | ||
| if (hookData.cost?.total_cost_usd != null) { | ||
| return hookData.cost.total_cost_usd; | ||
| } | ||
| // Fallback to ccusage calculation | ||
| return Result.pipe( | ||
| Result.try({ | ||
| try: async () => loadSessionUsageById(sessionId, { | ||
| mode: 'auto', | ||
| offline: mergedOptions.offline, | ||
| }), | ||
| catch: error => error, | ||
| })(), | ||
| Result.map(sessionCost => sessionCost?.totalCost), | ||
| Result.inspectError(error => logger.error('Failed to load session data:', error)), | ||
| Result.unwrap(undefined), | ||
| ); | ||
| } | ||
|
|
||
| // If 'cc' mode but no cost available, return undefined (will show N/A) | ||
| return undefined; | ||
| })(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The logic for determining the session cost is a bit repetitive, especially the part that calculates the cost using ccusage. This logic is duplicated for the ccusage mode and as a fallback for the auto mode.
To improve maintainability and readability, you can refactor this by:
- Extracting the
ccusagecalculation into a separate helper function. - Using a
switchstatement to handle the differentcostSourceoptions. This makes the logic more declarative and easier to follow.
Here's a suggested refactoring:
// Helper to calculate cost using ccusage
const calculateCostFromCcusage = async (): Promise<number | undefined> => {
return Result.pipe(
Result.try({
try: async () => loadSessionUsageById(sessionId, {
mode: 'auto',
offline: mergedOptions.offline,
}),
catch: error => error,
})(),
Result.map(sessionCost => sessionCost?.totalCost),
Result.inspectError(error => logger.error('Failed to load session data:', error)),
Result.unwrap(undefined),
);
};
// Determine session cost based on cost source
const sessionCost = await (async (): Promise<number | undefined> => {
const { costSource } = ctx.values;
const ccCost = hookData.cost?.total_cost_usd;
switch (costSource) {
case 'cc':
return ccCost;
case 'ccusage':
return calculateCostFromCcusage();
case 'auto':
return ccCost ?? await calculateCostFromCcusage();
default:
// This case should be unreachable due to enum validation
return undefined;
}
})();Add comprehensive documentation for the new --cost-source option in statusline command: - Document all four cost source modes: auto, ccusage, cc, both - Add setup examples for settings.json configuration - Show output format differences for both mode - Explain when to use each mode with practical guidance - Update output format examples with both costs display References recent PRs: - feat(statusline): add costSource option to use Claude Code session cost (#571) - feat(statusline): add 'both' cost source option to display cc and ccusage costs (#574)
Add comprehensive documentation for the new --cost-source option in statusline command: - Document all four cost source modes: auto, ccusage, cc, both - Add setup examples for settings.json configuration - Show output format differences for both mode - Explain when to use each mode with practical guidance - Update output format examples with both costs display References recent PRs: - feat(statusline): add costSource option to use Claude Code session cost (#571) - feat(statusline): add 'both' cost source option to display cc and ccusage costs (#574)
Summary
costSourceCLI option with three modes:auto(default),ccusage, andcccostfield from Claude CodeChanges
Schema Updates
statuslineHookJsonSchemato include optionalcostfield withtotal_cost_usdand metadataCost Source Options
auto(default): Prefer Claude Code cost if available, fallback to ccusage calculationccusage: Always calculate using ccusage's token-based calculationcc: Always use Claude Code's provided cost (show N/A if unavailable)Implementation
Test Plan
Example Usage
Summary by CodeRabbit
New Features
Tests