Skip to content

Conversation

@ryoppippi
Copy link
Owner

@ryoppippi ryoppippi commented Aug 22, 2025

Summary

  • Add support for using session cost data directly from Claude Code's statusline hook input
  • Add costSource CLI option with three modes: auto (default), ccusage, and cc
  • Update statusline hook JSON schema to support optional cost field from Claude Code

Changes

Schema Updates

  • Extended statuslineHookJsonSchema to include optional cost field with total_cost_usd and metadata
  • Maintains backward compatibility with existing statusline input format

Cost Source Options

  • auto (default): 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)

Implementation

  • Refactored session cost calculation logic to support multiple cost sources
  • Added comprehensive tests for new cost field schema validation
  • All existing functionality preserved

Test Plan

  • Schema validation tests for cost field
  • Backward compatibility with existing input format
  • All existing tests pass
  • Code formatting and type checking passes

Example Usage

# Use auto mode (default - prefer CC cost, fallback to ccusage)
bun run start statusline --cost-source auto

# Always use ccusage calculation
bun run start statusline --cost-source ccusage

# Always use Claude Code cost
bun run start statusline --cost-source cc

Summary by CodeRabbit

  • New Features

    • Statusline now lets you choose the session cost source via a new costSource option/flag: auto (default, prefer Claude Code then fallback), ccusage (always calculate), or cc (always use Claude Code).
    • Added a costSource setting in configuration to set the default behavior for the statusline.
  • Tests

    • Expanded test coverage to validate cost data handling and ensure correct behavior across cost source options.

- 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
@coderabbitai
Copy link

coderabbitai bot commented Aug 22, 2025

Note

Other AI code review bot(s) detected

CodeRabbit 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 failed

The pull request is closed.

Walkthrough

Adds 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

Cohort / File(s) Summary
Config schema: costSource option
config-schema.json
Adds commands.blocks.statusline.properties.costSource with enum ["auto","ccusage","cc"], default "auto", plus descriptions.
Hook schema and tests
src/_types.ts
Extends statuslineHookJsonSchema with optional cost object (requires total_cost_usd; other fields optional). Adds Vitest tests validating parsing and constraints.
Statusline command: cost selection
src/commands/statusline.ts
Introduces costSource arg (enum ["auto","ccusage","cc"], default "auto"). Refactors session cost resolution: cc (hook cost), ccusage (compute via usage loader), auto (prefer cc then fallback to ccusage).

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I nibble bytes with whiskered grace,
Three paths to cost in one small place—
cc, ccusage, or let it flow,
“auto” decides which way to go.
Tapping logs with bunny glee,
Statuslines sing in harmony. 🐇💻

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 details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4c5f496 and b51e0a0.

📒 Files selected for processing (3)
  • config-schema.json (1 hunks)
  • src/_types.ts (2 hunks)
  • src/commands/statusline.ts (3 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-statusline-cost-source-option

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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

  1. 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.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 22, 2025

Open in StackBlitz

npm i https://pkg.pr.new/ryoppippi/ccusage@571

commit: b51e0a0

- Update config-schema.json to include new costSource option
- Remove unnecessary vitest import (globals are available)
@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Aug 22, 2025

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

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

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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.

Comment on lines 229 to 276
// 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;
})();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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:

  1. Extracting the ccusage calculation into a separate helper function.
  2. Using a switch statement to handle the different costSource options. 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;
						}
					})();

@ryoppippi ryoppippi merged commit 940990a into main Aug 22, 2025
19 of 21 checks passed
@ryoppippi ryoppippi deleted the add-statusline-cost-source-option branch August 22, 2025 11:02
ryoppippi added a commit that referenced this pull request Aug 22, 2025
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)
ryoppippi added a commit that referenced this pull request Aug 22, 2025
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants