Skip to content

refactor: improve Result.pipe usage in statusline.ts - #495

Merged
ryoppippi merged 6 commits into
mainfrom
result
Aug 13, 2025
Merged

refactor: improve Result.pipe usage in statusline.ts#495
ryoppippi merged 6 commits into
mainfrom
result

Conversation

@ryoppippi

@ryoppippi ryoppippi commented Aug 13, 2025

Copy link
Copy Markdown
Member

Summary

  • Inline Result.unwrap() calls in all Result.pipe chains to eliminate intermediate variables
  • Improve contextInfo handling with cleaner display logic and N/A fallback pattern
  • Apply consistent functional programming pipeline pattern throughout statusline command

Changes

  • sessionCost: Move Result.unwrap(undefined) into pipeline, remove sessionCostResult variable
  • todayCost: Move Result.unwrap(0) into pipeline, remove todayCostResult variable
  • blockInfo/burnRateInfo: Move Result.unwrap() into pipeline, remove blockDataResult variable
  • contextInfo: Refactor display logic into pipeline with proper N/A fallback

Test plan

  • Code builds and lints without errors
  • Statusline command functionality remains unchanged
  • All Result.pipe chains follow consistent pattern
  • Error handling and fallback values work correctly

Summary by CodeRabbit

  • New Features
    • Refreshed status line layout with segmented display, including context info (🧠) with “N/A” fallback, clearer session and today’s cost, and color‑coded burn rate.
  • Refactor
    • Unified error handling across data loading for more consistent behavior and logging.
  • Bug Fixes
    • Improved resilience: missing or invalid data now falls back to safe defaults, reducing misreports.
  • Chores
    • Updated a dependency to the latest patch version.

- Move Result.unwrap() into Result.pipe() chains to eliminate intermediate variables

- Apply same pattern used for sessionCost to todayCost, blockInfo/burnRateInfo, and contextInfo

- Improves code consistency and follows functional programming pipeline pattern
- Move display logic back into Result.pipe for better consistency

- Return formatted string directly from pipeline instead of raw data

- Simplify status line construction with cleaner contextInfo display

- Use N/A fallback pattern similar to sessionDisplay
@coderabbitai

coderabbitai Bot commented Aug 13, 2025

Copy link
Copy Markdown

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

Refactors src/commands/statusline.ts to use @praha/byethrow’s Result-based pipelines for data loading, error handling, and formatting of the status line. Updates package.json to bump @praha/byethrow from ^0.6.2 to ^0.6.3. No public API or export signature changes.

Changes

Cohort / File(s) Summary
Dependency bump
package.json
Update @praha/byethrow version from ^0.6.2 to ^0.6.3 in dependencies and devDependencies.
Statusline Result refactor
src/commands/statusline.ts
Replace try/catch with Result.pipe flows; compute sessionCost, today’s total cost, block info and burn-rate, and context tokens via Result; add logging via Result.inspectError; adjust status line formatting and null/undefined handling; import Result.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant StatuslineCmd
  participant Session as SessionData
  participant Usage as DailyUsage
  participant Blocks as BlockManager
  participant Context as ContextAnalyzer
  participant Result as Result.pipe
  participant Log as Logger
  participant UI as Renderer

  User->>StatuslineCmd: run
  StatuslineCmd->>Result: pipe(Session.load)
  Result-->>Log: inspectError(err)
  Result-->>StatuslineCmd: sessionCost | undefined

  StatuslineCmd->>Result: pipe(Usage.loadToday -> sum)
  Result-->>Log: inspectError(err)
  Result-->>StatuslineCmd: totalCost (default 0)

  StatuslineCmd->>Result: pipe(Blocks.active -> compute info)
  Result-->>Log: inspectError(err)
  Result-->>StatuslineCmd: {blockInfo, burnRateInfo}

  StatuslineCmd->>Result: pipe(Context.measure -> format)
  Result-->>Log: inspectError(debug)
  Result-->>StatuslineCmd: contextInfo | undefined

  StatuslineCmd->>UI: render status line
  UI-->>User: status output
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

A twitch of whiskers, a tap on the key,
I piped all results, set the try/catch free.
Costs hop in order, blocks burn in line,
Context nibble counts now render fine.
With byethrow’s charm and ears held high,
The status sings—so crisp, so spry! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 375d218 and 6c6d463.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • package.json (1 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 result

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.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 13, 2025

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

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

Status Name Latest Commit Updated (UTC)
❌ Deployment failed
View logs
ccusage-guide 6c6d463 Aug 13 2025, 12:05 PM

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

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 refactors the statusline command to enhance its functional programming paradigm by consistently utilizing the Result.pipe pattern. The primary goal is to improve code clarity, error handling, and maintainability by inlining Result.unwrap() calls and eliminating intermediate variables. This change applies to various data calculations within the command, such as session costs, daily usage, block information, and context token processing, ensuring a more streamlined and robust data flow with proper fallback mechanisms.

Highlights

  • Consistent Functional Pipeline Adoption: The core logic for calculating sessionCost, todayCost, blockInfo, burnRateInfo, and contextInfo has been rewritten to leverage the Result.pipe pattern. This streamlines error handling and data transformation by chaining operations, making the code more readable and robust.
  • Reduced Boilerplate and Inlined Unwrapping: Intermediate variables previously used to store results before unwrapping them have been eliminated. Result.unwrap() calls are now directly integrated into the Result.pipe chains, reducing boilerplate and improving conciseness.
  • Improved Context Information Display and Fallback: The handling and display of contextInfo have been refined. The logic now explicitly includes a 'N/A' fallback for cases where context data is unavailable, ensuring a consistent user experience.
  • Dependency Update: The @praha/byethrow library, which provides the Result type and pipe method, has been updated to version 0.6.3. This update supports the refactoring changes and ensures 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

pkg-pr-new Bot commented Aug 13, 2025

Copy link
Copy Markdown

Open in StackBlitz

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

commit: 6b6df49

@socket-security

socket-security Bot commented Aug 13, 2025

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License

View full report

@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 successfully refactors the statusline.ts command to consistently use the Result.pipe functional pattern, which is a great improvement for readability and error handling. The logic for calculating session cost, daily cost, block info, and context info has been cleanly migrated from try...catch blocks to functional pipelines. I have a few minor suggestions to further enhance the conciseness of the new code. Overall, this is a solid refactoring.

Comment on lines +75 to +77
Result.map((sessionCost) => {
return sessionCost?.totalCost;
}),

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

This mapping function can be simplified to a concise arrow function for better readability.

            Result.map(sessionCost => sessionCost?.totalCost),

Comment on lines +96 to +102
Result.map((dailyData) => {
if (dailyData.length > 0) {
const totals = calculateTotals(dailyData);
return totals.totalCost;
}
return 0;
}),

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

This mapping logic can be expressed more concisely using a ternary operator, which simplifies the code and aligns well with the functional pipeline style.

            Result.map(dailyData => (dailyData.length > 0 ? calculateTotals(dailyData).totalCost : 0)),

Comment on lines +143 to +157
const burnRateInfo = burnRate != null
? (() => {
const costPerHour = burnRate.costPerHour;
const costPerHourStr = `${formatCurrency(costPerHour)}/hr`;

// Apply color based on burn rate (tokens per minute non-cache)
const coloredBurnRate = burnRate.tokensPerMinuteForIndicator < 2000
? pc.green(costPerHourStr) // Normal
: burnRate.tokensPerMinuteForIndicator < 5000
? pc.yellow(costPerHourStr) // Moderate
: pc.red(costPerHourStr); // High

return ` | 🔥 ${coloredBurnRate}`;
})()
: '';

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 nested ternary operator inside the IIFE for burnRateInfo can be simplified for better readability. Using an if check at the beginning of the IIFE makes the logic clearer and flatter.

                    const burnRateInfo = (() => {
                        if (burnRate == null) {
                            return '';
                        }
                        const costPerHourStr = `${formatCurrency(burnRate.costPerHour)}/hr`;
                        const color = burnRate.tokensPerMinuteForIndicator < 2000
                            ? pc.green
                            : burnRate.tokensPerMinuteForIndicator < 5000
                                ? pc.yellow
                                : pc.red;
                        return ` | 🔥 ${color(costPerHourStr)}`;
                    })();

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.

1 participant