Skip to content

feat: Debug Features and Cost Calculation Modes types to log function - #5

Merged
ryoppippi merged 21 commits into
mainfrom
alpha
Jun 3, 2025
Merged

ryoppippi merged 21 commits into
mainfrom
alpha

Conversation

@ryoppippi

@ryoppippi ryoppippi commented Jun 3, 2025 •

Copy link
Copy Markdown
Member

fixes: #4 #3
This pull request introduces significant enhancements to the cost calculation functionality, updates to the schema for usage data, and improvements to testing and debugging capabilities. The most important changes include adding support for cost calculation modes, integrating LiteLLM pricing data, expanding the schema for usage data, and refining session data handling.

Cost Calculation Enhancements:

  • Added three cost calculation modes (auto, calculate, display) to control how costs are computed based on token counts or pre-calculated costUSD values. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-6ebdb617a8104a7756d0cf36578ab01103dc9f07e4dc6feb751296b9c402faf7R22-R30), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R116-R120), [[3]](https://github.com/ccusage/ccusage/pull/5/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R141-R145), [[4]](https://github.com/ccusage/ccusage/pull/5/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R156-R165))
  • Implemented logic to calculate costs dynamically using LiteLLM pricing data when the mode is set to calculate or fallback to auto mode. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcR91-R93), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcL108-R155), [[3]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcL153-R200), [[4]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcR238-R287))

LiteLLM Integration:

  • Integrated LiteLLM's pricing database to fetch model-specific pricing data for cost calculations. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-6ebdb617a8104a7756d0cf36578ab01103dc9f07e4dc6feb751296b9c402faf7R53), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcR91-R93), [[3]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcL108-R155))
  • Added validation to ensure model names in tests match LiteLLM's database entries to prevent failures caused by unsupported models. ([CLAUDE.mdR63-R86](https://github.com/ccusage/ccusage/pull/5/files#diff-6ebdb617a8104a7756d0cf36578ab01103dc9f07e4dc6feb751296b9c402faf7R63-R86))

Schema Updates:

  • Expanded the UsageDataSchema and SessionUsageSchema to include optional fields for model names and versions, enabling more detailed tracking of usage data. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcR7-R29), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcR54))
  • Enhanced session data handling to include unique versions used within a session and sort results by last activity instead of total cost. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcL153-R200), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-9ef087b6a8799e1e3852522a758149979ace890a62c820a6d12a36e3eb7cc5fcL215-R303))

Debugging and Testing Improvements:

  • Added debugging utilities (detectMismatches, printMismatchReport) to identify discrepancies in data and provide detailed reports. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-a22e1a0044d16770257ddea66c38e5d9a02b67ee541793687e483fce477e5835R11-R26), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-a22e1a0044d16770257ddea66c38e5d9a02b67ee541793687e483fce477e5835R42-R47), [[3]](https://github.com/ccusage/ccusage/pull/5/files#diff-6f9669bd0d0825f4042a8b411bc063f5a8df5d557c7421b91ffb72c5ceb75c26R11-R26), [[4]](https://github.com/ccusage/ccusage/pull/5/files#diff-6f9669bd0d0825f4042a8b411bc063f5a8df5d557c7421b91ffb72c5ceb75c26R42-R47))
  • Updated testing guidelines to ensure comprehensive coverage for supported Claude 4 models and compatibility with LiteLLM pricing data. ([[1]](https://github.com/ccusage/ccusage/pull/5/files#diff-6ebdb617a8104a7756d0cf36578ab01103dc9f07e4dc6feb751296b9c402faf7R63-R86), [[2]](https://github.com/ccusage/ccusage/pull/5/files#diff-8154d3524d88625e7af075f901b613ca1232ec13895d54b8c0fd3c0796f1aeccR49), [[3]](https://github.com/ccusage/ccusage/pull/5/files#diff-8154d3524d88625e7af075f901b613ca1232ec13895d54b8c0fd3c0796f1aeccR60))

@ryoppippi
ryoppippi requested a review from Copilot June 3, 2025 14:37

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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!

Summary of Changes

As Gemini, I've reviewed this pull request which focuses on enhancing the cost calculation and debugging capabilities of the tool. The primary goals are to provide flexible cost reporting based on different calculation modes, integrate real-time model pricing data from LiteLLM, update the data schema to support more detailed usage information (like model and version), and introduce debugging utilities to identify discrepancies in cost reporting. Significant effort has also gone into improving the test suite, particularly around data loading and cost calculation accuracy.

Highlights

  • Cost Calculation Modes: Introduced three distinct modes (auto, calculate, display) via a new --mode CLI option to control how costs are determined: using pre-calculated costUSD, calculating from tokens using LiteLLM pricing, or a combination.
  • LiteLLM Pricing Integration: Integrated LiteLLM's model pricing database to enable dynamic cost calculation based on token usage when the calculate or auto modes are active. This fetches pricing data externally and caches it.
  • Schema Updates: The internal data schema (UsageDataSchema, SessionUsageSchema) has been updated to include optional fields for version and message.model, and costUSD is now optional, accommodating different data sources and enabling more detailed session reporting.
  • Session Data Improvements: Session data processing now tracks unique versions used within a session and the default sorting for session reports has been changed from total cost to last activity.
  • Debugging Utilities: Added new debug functionality (detectMismatches, printMismatchReport) accessible via a --debug flag to compare pre-calculated costUSD values with costs calculated from tokens using LiteLLM pricing, helping identify potential data inconsistencies.
  • Testing Enhancements: Refactored data loading tests to use fs-fixture for better isolation and added comprehensive tests covering the new cost calculation modes, LiteLLM integration, and schema changes, including handling of cache tokens and unknown models.

Changelog

Click here to see the changelog
  • CLAUDE.md
    • Added documentation for the new --mode flag for daily and session reports (lines 22-23).
    • Documented the three cost calculation modes (auto, calculate, display) (lines 26-29).
    • Added a note about LiteLLM integration for cost calculations (line 53).
    • Added a new section on Claude Models and Testing, including supported Claude 4 models, naming conventions, and testing guidelines related to LiteLLM pricing compatibility (lines 63-86).
  • README.md
    • Added examples for using the new --mode flag with the daily command (lines 117-120).
    • Added examples for using the new --mode flag with the session command (lines 142-145).
    • Added the -m, --mode option description to the shared options list (line 156).
    • Added a detailed description of the three Cost Calculation Modes (auto, calculate, display) (lines 160-164).
  • bun.lock
    • Added fs-fixture dependency (lines 14, 210).
  • calculate-cost.test.ts
    • Updated mock session data to include the new versions field (lines 49, 60).
  • commands/daily.ts
    • Imported detectMismatches, printMismatchReport from ./debug.ts and CostMode from ./types.ts (lines 11, 14).
    • Updated command definition to use sharedCommandConfig instead of sharedArgs (line 20).
    • Passed the mode option from context values to loadUsageData (line 26).
    • Added logic to call detectMismatches and printMismatchReport if the --debug flag is set (lines 42-46).
  • commands/session.ts
    • Imported detectMismatches, printMismatchReport from ./debug.ts and CostMode from ./types.ts (lines 11, 14).
    • Updated command definition to use sharedCommandConfig instead of sharedArgs (line 20).
    • Passed the mode option from context values to loadSessionData (line 26).
    • Added logic to call detectMismatches and printMismatchReport if the --debug flag is set (lines 42-46).
  • data-loader.test.ts
    • Removed old mocks for readFile, glob, homedir and added import for createFixture from fs-fixture (lines 1-10).
    • Added import for clearPricingCache (line 10).
    • Updated formatDate tests to use different date formats (lines 16, 20-22).
    • Refactored loadUsageData tests to use fs-fixture for creating test file structures (lines 33-35, 61-72, 97-105, 132-140, 172-180, 198-206, 226-234).
    • Added tests for loadUsageData covering cost calculation with real pricing, mixed schemas, cache tokens, and sorting (lines 41-242).
    • Refactored loadSessionData tests to use fs-fixture (lines 247-249, 262-275, 316-324, 362-370, 406-415, 452-460).
    • Added tests for loadSessionData covering tracking versions and sorting by last activity (lines 340-376, 378-422).
    • Added extensive tests for cost calculation modes (auto, calculate, display) with both loadUsageData and loadSessionData (lines 474-947).
  • data-loader.ts
    • Imported pricing fetcher utilities and CostMode type (lines 7-13).
    • Updated UsageDataSchema to make costUSD optional and add optional version and message.model fields (lines 19, 27, 29).
    • Updated SessionUsageSchema to add an optional versions array (line 54).
    • Added mode to LoadOptions interface (line 74).
    • Fetched model pricing data in loadUsageData (line 92).
    • Implemented cost calculation logic in loadUsageData based on the selected mode (auto, calculate, display), using costUSD or calculating from tokens via getModelPricing and calculateCostFromTokens (lines 129-155).
    • Fetched model pricing data in loadSessionData (line 195).
    • Implemented cost calculation logic in loadSessionData based on the selected mode (lines 249-275).
    • Added logic to collect unique versions in a Set during session data aggregation (lines 284-286).
    • Converted the temporary versionSet to a sorted array and removed the temporary property when converting the session map to an array (lines 296-302).
    • Changed session sorting from totalCost to lastActivity (line 315).
  • debug.test.ts
    • New file adding tests for detectMismatches and printMismatchReport (lines 1-330).
    • Tests cover detecting matches and mismatches, handling missing data, skipping synthetic models, skipping invalid JSON, and tracking statistics per model and version.
    • Uses fs-fixture for creating test data files.
  • debug.ts
    • New file containing detectMismatches and printMismatchReport functions (lines 1-267).
    • detectMismatches reads usage data, compares costUSD with calculated costs using LiteLLM pricing, and collects statistics and discrepancies.
    • printMismatchReport formats and prints the collected statistics and sample discrepancies.
  • logger.ts
    • Updated the log function to use logger.log instead of console.log for consistent logging (line 7).
  • package.json
    • Added fs-fixture to devDependencies (line 53).
  • pricing-fetcher.test.ts
    • New file adding tests for fetchModelPricing, getModelPricing, and calculateCostFromTokens (lines 1-239).
    • Tests cover fetching and caching pricing data, model lookup logic (exact, partial, variations), and cost calculation including cache tokens and handling missing pricing fields.
  • pricing-fetcher.ts
    • New file containing functions for fetching LiteLLM pricing data, caching it, looking up pricing by model name, and calculating cost from token usage (lines 1-138).
  • shared-args.ts
    • Imported CostModes from ./types (line 4).
    • Added --mode, --debug, and --debugSamples arguments to sharedArgs (lines 39-57).
    • Created sharedCommandConfig object combining sharedArgs and toKebab (lines 60-63).
  • types.ts
    • Defined the CostModes union type (auto, calculate, display) and the CostMode type alias (lines 60-61).
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 is currently in preview and 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 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.


Code logs flow like streams,
Counting tokens, chasing dreams.
Costs calculated,
Or data stated,
Debug finds the hidden gleams.

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

pkg-pr-new Bot commented Jun 3, 2025 •

Copy link
Copy Markdown

Open in StackBlitz

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

commit: 75dff67

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances cost calculation by adding selectable modes, integrates LiteLLM pricing data for dynamic cost computation, expands usage/session schemas with model/version metadata, and introduces debugging utilities with mismatch reporting.

  • Added CostMode enum and CLI arg to select between auto, calculate, and display modes
  • Integrated LiteLLM pricing fetcher, model matching, and token‐based cost calculations
  • Extended schemas and session handling to capture version metadata and sorting by last activity
  • Introduced detectMismatches/printMismatchReport for debugging and enriched tests

Reviewed Changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
types.ts Defines CostModes and CostMode enum for cost modes
shared-args.ts Adds CLI args (mode, debug, debugSamples)
pricing-fetcher.ts New module fetching/parsing LiteLLM pricing data
pricing-fetcher.test.ts Tests for fetching, caching, and pricing lookup
logger.ts Updates log helper to use logger.log
debug.ts Implements mismatch detection and reporting utilities
debug.test.ts Tests for mismatch detection/reporting
data-loader.ts Updates loadUsageData/loadSessionData to handle modes, versions
commands/session.ts Integrates mode flags and debug output into session cmd
commands/daily.ts Integrates mode flags and debug output into daily cmd
calculate-cost.test.ts Updates tests to include versions in session data
README.md & CLAUDE.md Documentation for cost modes and LiteLLM integration
package.json Adds fs-fixture dependency for tests
Comments suppressed due to low confidence (1)

calculate-cost.test.ts:60

  • You added the versions field to session data but there’s no test verifying its sorted order or uniqueness. Add a test case that asserts versions is correctly deduplicated and sorted.
versions: ["1.0.3", "1.0.4"],

Comment thread shared-args.ts
description: "Output in JSON format",
default: false,
},
mode: {

Copilot AI Jun 3, 2025

Copy link

Choose a reason for hiding this comment

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

The mode argument accepts only specific values (auto, calculate, display) but lacks validation. Consider adding a choices: CostModes property or custom validator so invalid modes are rejected early.

Copilot uses AI. Check for mistakes.
Comment thread pricing-fetcher.test.ts
});

describe("fetchModelPricing", () => {
it("should fetch and parse pricing data from LiteLLM", async () => {

Copilot AI Jun 3, 2025

Copy link

Choose a reason for hiding this comment

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

This test relies on real network requests to LiteLLM's GitHub URL, which can lead to flaky or slow tests. It would be more reliable to mock fetchModelPricing or stub fetch to return fixture data.

Copilot uses AI. Check for mistakes.
Comment thread data-loader.ts Outdated
Comment on lines +91 to +92
// Fetch pricing data for cost calculation
const modelPricing = await fetchModelPricing();

Copilot AI Jun 3, 2025

Copy link

Choose a reason for hiding this comment

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

The pricing data is fetched unconditionally even in display mode where it's not used. Consider deferring or conditionalizing the fetchModelPricing() call based on the selected mode to avoid unnecessary network requests.

Suggested change
// Fetch pricing data for cost calculation
const modelPricing = await fetchModelPricing();
// Fetch pricing data for cost calculation if mode requires it
let modelPricing: ModelPricing | undefined;
if (options?.mode === "cost") {
modelPricing = await fetchModelPricing();
}

Copilot uses AI. Check for mistakes.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

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 significant enhancements to cost calculation, schema updates, and debugging capabilities. The integration with LiteLLM for pricing data and the addition of cost calculation modes are valuable features. The refactoring of tests to use fs-fixture is a notable improvement for test reliability and maintainability. The new debugging utilities will also be very helpful.

Overall, the code is well-structured, and the changes are thoughtfully implemented with good test coverage and documentation updates. I've identified a couple of areas for potential improvement to enhance robustness and consistency.

Summary of Findings

  • CLI Argument Validation: The --mode CLI argument could benefit from explicit validation against the allowed CostModes to provide clearer feedback for invalid user input, rather than silently falling back to 'auto' mode.
  • Path Consistency in Debug Tooling: The detectMismatches function appears to scan a different default directory scope for JSONL files compared to the main data loading functions, which could lead to inconsistencies if not handled carefully. Aligning the path logic would improve robustness.

Merge Readiness

The PR introduces valuable features and significant improvements. The core logic appears solid and is well-tested. However, I've raised two medium severity issues concerning argument validation and path consistency in the debug tooling. It would be beneficial to address these points to further enhance the robustness and clarity of the application. As a reviewer, I am not authorized to approve pull requests. Please ensure these changes are reviewed and approved by authorized team members after addressing the feedback.

Comment thread commands/daily.ts Outdated
since: ctx.values.since,
until: ctx.values.until,
claudePath: ctx.values.path,
mode: ctx.values.mode as CostMode,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The mode option is typed as CostMode using a type assertion (as CostMode). While gunshi sets a default value which is valid, if a user provides an invalid mode string via the CLI (e.g., --mode invalid), this assertion would be unsafe, and the invalid string would be passed to loadUsageData.

Currently, loadUsageData handles unknown modes by defaulting to "auto" behavior. This is a safe fallback, but it might be more user-friendly and robust to validate the mode value explicitly when it's parsed.

Could we consider adding a custom parser for the mode argument in shared-args.ts (similar to parseDateArg) to validate that the provided value is one of the allowed CostModes? This would provide earlier and clearer error feedback to the user for invalid modes.

Comment thread debug.ts
Comment on lines +58 to +62
const claudeDir = claudePath || path.join(homedir(), ".claude", "projects");
const files = await glob(["**/*.jsonl"], {
cwd: claudeDir,
absolute: true,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

There seems to be a slight inconsistency in how claudePath is handled here compared to data-loader.ts.

In data-loader.ts (loadUsageData/loadSessionData):

  • claudePath defaults to ~/.claude.
  • claudeDir (used for glob) is constructed as path.join(claudePath, "projects").
    This means glob operates on ~/.claude/projects/... by default.

In detectMismatches (this file):

  • claudeDir is claudePath || path.join(homedir(), ".claude", "projects").
  • If detectMismatches is called with the default ctx.values.path (which is ~/.claude), then claudeDir here becomes ~/.claude.
  • glob then operates on ~/.claude/....

This means detectMismatches scans a broader directory (~/.claude) by default, while the data loaders scan a more specific one (~/.claude/projects).

For consistency, should detectMismatches also target the projects subdirectory by default, similar to the data loaders? For example, by adjusting claudeDir initialization here:

const baseClaudePath = claudePath || getDefaultClaudePath(); // Assuming getDefaultClaudePath() returns ~/.claude
const claudeDir = path.join(baseClaudePath, "projects");

Or, if claudePath is intended to be the direct path to projects for this function, it might be good to clarify that in the parameter's JSDoc or by renaming it (e.g., projectsPath).

const baseClaudePath = claudePath || getDefaultClaudePath();
const claudeDir = path.join(baseClaudePath, "projects");

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds cost calculation modes, integrates LiteLLM pricing, extends usage/session schemas, and introduces debugging utilities for pricing mismatches.

  • Introduces CostMode enum and command-line flags (mode, debug, debugSamples)
  • Creates pricing-fetcher.ts to load and query LiteLLM pricing, and updates data-loader.ts to apply mode-based cost logic and track session versions
  • Adds debug.ts utilities (detectMismatches, printMismatchReport) and updates commands and tests accordingly

Reviewed Changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
types.ts Added CostModes and CostMode type
shared-args.ts Added mode, debug, and debugSamples arguments
pricing-fetcher.ts New module for fetching/parsing LiteLLM model pricing
data-loader.ts Enhanced loaders with cost-mode logic, session versions, sorting
debug.ts New mismatch detection and reporting utilities
commands/session.ts Integrated mode/debug flags into session command
commands/daily.ts Integrated mode/debug flags into daily command
package.json Added fs-fixture dependency for test fixtures
Comments suppressed due to low confidence (3)

commands/session.ts:11

  • [nitpick] The log import isn't used in this file; removing it will keep the imports clean and avoid linter warnings.
import { log, logger } from "../logger.ts";

commands/daily.ts:11

  • [nitpick] The log import isn't used in this file; removing it will keep the imports clean and avoid linter warnings.
import { log, logger } from "../logger.ts";

debug.test.ts:13

  • [nitpick] The await using resource-disposal syntax may not be supported in all environments; consider using a standard const fixture = await createFixture(...) pattern and manually cleaning up if needed.
await using fixture = await createFixture({

Comment thread package.json
"cli-table3": "^0.6.5",
"consola": "^3.4.2",
"fast-sort": "^3.4.1",
"fs-fixture": "^2.7.1",

Copilot AI Jun 3, 2025

Copy link

Choose a reason for hiding this comment

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

The fs-fixture package is only used in tests and should be moved to devDependencies to avoid bloating production dependencies.

Copilot uses AI. Check for mistakes.
Comment thread data-loader.ts Outdated
let cost = 0;
const mode = options?.mode || "auto";

if (mode === "display") {

Copilot AI Jun 3, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] The cost calculation logic is duplicated in both loadUsageData and loadSessionData. Consider extracting it into a shared helper function to improve maintainability.

Copilot uses AI. Check for mistakes.
Comment thread debug.ts Outdated
Comment thread shared-args.ts
ryoppippi and others added 2 commits June 3, 2025 15:49
⏺ Summary

  I've successfully optimized the data loading logic to prevent
unnecessary data fetching when the mode doesn't require it. Here's what
I accomplished:

  Key Changes:
  1. Conditional Pricing Fetch: Modified both loadUsageData and
loadSessionData functions in data-loader.ts:92,196 to only fetch pricing
data when needed:
    - mode === "display": Uses empty object {} instead of fetching
pricing data
    - mode === "calculate" or mode === "auto": Fetches pricing data as
before
  2. Removed Duplicate Code: Eliminated redundant mode variable
assignments that were happening inside the processing loops.

  Performance Benefits:
  - When using --mode display, the tool now skips the network request to
fetch LiteLLM pricing data
  - This makes the display mode faster and allows it to work without
internet connectivity
  - Only pre-calculated costUSD values are used in display mode, which
is the intended behavior

  Tests Added:
  - Comprehensive tests to verify the optimization works correctly
  - Tests ensure display mode doesn't require network access
  - Tests verify that calculate and auto modes still fetch pricing data
when needed
  - All existing functionality remains intact
ryoppippi added 3 commits June 3, 2025 16:01
I have successfully completed both tasks:

  ✅ Task 1: Extract duplicated cost calculation logic

  - Identified duplication: The cost calculation logic was duplicated in
both loadUsageData and loadSessionData functions in data-loader.ts
  - Created shared helper: Extracted the logic into a new
calculateCostForEntry function
  - Maintained functionality: All existing tests continue to pass,
ensuring the behavior is identical
  - Improved maintainability: Cost calculation logic is now centralized
in one place

  ✅ Task 2: Write comprehensive tests for the new function

  - Added 16 comprehensive tests covering all three cost calculation
modes (display, calculate, auto)
  - Test coverage includes:
    - Display mode: Uses costUSD when available, returns 0 when
undefined
    - Calculate mode: Always calculates from tokens, ignores costUSD,
handles missing models/pricing
    - Auto mode: Prefers costUSD but falls back to calculation when
unavailable
    - Edge cases: Zero token counts, zero/negative costs, missing cache
tokens
  - Uses real pricing data from LiteLLM for authentic testing
  - All tests pass and follow the existing codebase patterns

  Code Quality

  - All 90 tests pass (including existing and new tests)
  - Linting is clean (fixed delete operator usage per Biome
recommendations)
  - TypeScript compilation succeeds with no errors
  - Function is exported for testability while maintaining encapsulation

  The refactoring successfully eliminates code duplication while
improving test coverage and maintainability.
@ryoppippi
ryoppippi merged commit d12ef89 into main Jun 3, 2025
@ryoppippi
ryoppippi deleted the alpha branch June 3, 2025 15:15
ryoppippi added a commit that referenced this pull request Jun 22, 2025
feat: Debug Features and Cost Calculation Modes types to log function
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.

Claude Code 1.0.9 no longer reports the costUSD field

2 participants