Skip to content

Conversation

@ekain-fr
Copy link

@ekain-fr ekain-fr commented Oct 10, 2025

Overview

This PR contains comprehensive enhancements to CCometixLine, adding dedicated usage tracking segments with sophisticated threshold-based styling and full TUI configurator support.

Linked issue #38: Propose 2 usage sections: 5-hours usage, weekly usage

Base: v1.0.8 (commit e826bef)
Changes: 10 commits adding new features and refinements
Fork: ekain-fr/CCometixLine


🎯 Major Features

1. Dedicated 5-Hour and 7-Day Usage Segments

NEW: Split the combined usage segment into two dedicated segments for better granularity.

Features:

  • Usage (5-hour): Tracks Claude API usage within the 5-hour rolling window
  • Usage (7-day): Tracks Claude API usage within the 7-day rolling window
  • Shared cache: Both segments use the same API cache for efficiency
  • Dynamic icons: Circle icons that change based on utilization percentage
  • Reset time display: Shows when each usage window resets (local timezone)

Implementation:

  • src/core/segments/usage_5hour.rs: New segment for 5-hour tracking
  • src/core/segments/usage_7day.rs: New segment for 7-day tracking
  • All theme presets updated to include both segments

2. Threshold-Based Warning Colors

NEW: Dynamic color changes based on API usage thresholds.

Features:

  • Configurable thresholds: Set warning (default: 60%) and critical (default: 80%) levels
  • Color overrides: Automatically change text color when thresholds are exceeded
  • Flexible palette: Support for 16-color, 256-color, and RGB color modes
  • Default colors: Light yellow (c16:11) for warning, light red (c16:9) for critical

Implementation:

  • Added get_color_for_utilization() method to both usage segments
  • Metadata-based override system (text_color_override)
  • Statusline renderer applies color overrides dynamically

3. Threshold-Based Bold Text

NEW: Make threshold warnings more prominent with optional bold styling.

Features:

  • Independent controls: Separate warning_bold and critical_bold options
  • Visual emphasis: Draw attention to high usage with bold text
  • Theme-specific defaults: Customize bold behavior per theme

Implementation:

  • Added should_be_bold() method to both usage segments
  • Metadata-based override system (text_bold_override)
  • Statusline renderer applies bold overrides dynamically

4. Full TUI Configurator Support

NEW: Interactive configuration for all threshold settings.

Features:

  • 13 fields for usage segments (vs 7 for standard segments)
  • Threshold editors:
    • Warning Threshold: Cycle through 40% / 50% / 60% / 70% / 80%
    • Critical Threshold: Cycle through 60% / 70% / 80% / 90% / 95%
  • Color pickers: Full color picker integration for warning/critical colors
  • Color swatches: Visual preview with colored blocks (██)
  • Bold toggles: Press Enter to toggle warning_bold and critical_bold
  • Real-time preview: See changes immediately in the preview panel
  • Status messages: Get feedback when settings change

Implementation:

  • Extended FieldSelection enum with 6 new field types
  • Conditional field display based on segment type
  • Dynamic navigation handling for 13 fields
  • Color swatch rendering with c16/c256/RGB support
CleanShot 2025-10-10 at 10 05 46@2x

📋 Detailed Changes by Commit

02cdcb2: feat: add dedicated 5-hour and 7-day usage segments

  • Created usage_5hour.rs and usage_7day.rs segment modules
  • Implemented shared cache loading from parent UsageSegment
  • Added time formatting functions (format_5hour_reset_time, format_7day_reset_time)
  • Registered new Usage5Hour and Usage7Day segment IDs
  • Updated all theme presets with new segment configurations
  • Updated segment name mappings across TUI components

c36feb3: refactor: use Unicode arrow (→) instead of ASCII arrow (->)

  • Changed arrow format from -> to in usage segment output
  • Applied to both 5-hour and 7-day segments
  • Improves visual consistency and appearance

278750a: refactor: use colon separator in 7-day usage reset time format

  • Changed date format from "Oct 9, 5am" to "Oct 9:5am"
  • Saves horizontal space in statusline
  • Maintains readability while being more compact

1714ce2: feat: add threshold-based warning colors for usage segments

  • Implemented get_color_for_utilization() method
  • Added warning_threshold and critical_threshold options
  • Added warning_color and critical_color options
  • Implemented text_color_override metadata system
  • Updated statusline renderer to apply color overrides
  • Added threshold options to all theme presets

8b7b92a: feat(tui): add interactive threshold editing (Phase 2)

  • Extended FieldSelection enum with threshold fields
  • Added conditional field display for usage segments
  • Implemented threshold cycling (Enter key handler)
  • Integrated color picker for threshold colors
  • Updated navigation for 11 fields (usage segments)
  • Added apply_selected_color() support for threshold colors

2777109: fix(tui): update preview with threshold colors and new usage format

  • Updated preview mock data with threshold demonstrations
  • Added get_threshold_color() helper method
  • Applied correct arrow format (→) in preview
  • Applied correct date format (Oct 9:5am) in preview
  • Set mock utilization values to demonstrate thresholds (65%, 85%)

c2801f2: refactor: use 16-color palette for threshold defaults

  • Migrated from 256-color (c256:226, c256:196) to 16-color (c16:11, c16:9)
  • Updated all theme files (gruvbox, default, cometix)
  • Changed usage_7day default color from c16:11 to c16:12 (differentiation)
  • Improved terminal compatibility

85bae80: feat: add threshold-based bold text options for usage segments

  • Implemented should_be_bold() method
  • Added warning_bold and critical_bold boolean options
  • Implemented text_bold_override metadata system
  • Updated statusline renderer to apply bold overrides
  • Added bold options to all theme presets (with theme-specific defaults)

6004642: feat(tui): add warning/critical bold fields to usage segment configurator

  • Added WarningBold and CriticalBold to FieldSelection enum
  • Displayed bold toggle fields in settings panel with [✓] / [ ] indicators
  • Added color swatches (██) for warning/critical color fields
  • Updated navigation for 13 fields (usage segments)
  • Implemented toggle handlers for bold options
  • Real-time preview updates when bold options change

fbb7b46: docs: add instructions for running forked version

  • Added "Running a Forked Version" section to README
  • Included rebuild instructions (cargo build --release)
  • Documented installation paths for testing

⚙️ Configuration

Example TOML Configuration:

[[segments]]
id = "usage5_hour"
enabled = true

[segments.icon]
plain = "📊"
nerd_font = "󰪞"

[segments.colors.icon]
c16 = 14

[segments.colors.text]
c16 = 14

[segments.styles]
text_bold = true

[segments.options]
warning_threshold = 60
critical_threshold = 80
warning_color = { c16 = 11 }
critical_color = { c16 = 9 }
warning_bold = true
critical_bold = true

TUI Configuration:

  1. Run ccline -c to open configurator
  2. Select "Usage (5-hour)" or "Usage (7-day)"
  3. Press Tab to switch to Settings panel
  4. Navigate with arrow keys
  5. Press Enter on thresholds to cycle values
  6. Press Enter on colors to open color picker
  7. Press Enter on bold fields to toggle
  8. Press 's' to save configuration
CleanShot 2025-10-10 at 10 05 46@2x

🧪 Testing Checklist

  • ✅ New usage segments display correctly in statusline
  • ✅ Threshold colors apply based on utilization
  • ✅ Bold text applies based on utilization and settings
  • ✅ TUI displays all 13 fields for usage segments
  • ✅ TUI displays color swatches correctly
  • ✅ Threshold cycling works (Enter key)
  • ✅ Bold toggles work (Enter key)
  • ✅ Color picker integration works
  • ✅ Preview updates in real-time
  • ✅ All themes load correctly
  • ✅ Configuration persists across restarts
  • ✅ Shared cache works (no duplicate API calls)
  • ✅ Unicode arrow displays correctly
  • ✅ Compact date format displays correctly

💡 Architecture Highlights

Metadata Override System

The threshold styling uses a clean metadata-based override architecture:

  1. Segments decide: usage_5hour.rs and usage_7day.rs determine if overrides are needed
  2. Metadata passes data: Overrides stored as text_color_override and text_bold_override
  3. Renderer applies: statusline.rs checks metadata and applies overrides without knowing segment logic

This keeps segment logic isolated and makes the statusline renderer flexible.

Shared Cache Pattern

Both usage segments share the same API cache:

let cache = UsageSegment::load_usage_cache()?;
let five_hour_util = cache.five_hour_utilization;
let seven_day_util = cache.seven_day_utilization;

This ensures:

  • Only one API call per cache duration
  • Consistent data across both segments
  • Better performance

Dynamic TUI Fields

The TUI settings panel adapts based on segment type:

let is_usage_segment = matches!(
    segment.id,
    SegmentId::Usage5Hour | SegmentId::Usage7Day
);

let field_count = if is_usage_segment { 13 } else { 7 };

This allows usage segments to have 6 additional threshold-specific fields without affecting other segments.


🔄 Breaking Changes

None. All changes are backward compatible:

  • Existing configs without threshold options use sensible defaults
  • Segments work perfectly fine without threshold configuration
  • TUI gracefully handles missing options
  • Old configs continue to work unchanged

📊 Statistics

  • 10 commits spanning usage segment enhancements
  • 15+ files modified across core segments, UI components, and themes
  • 500+ lines added for threshold logic and TUI support
  • 6 new TUI fields for interactive threshold configuration
  • 3 color override pathways (c16, c256, RGB)
  • 2 new dedicated segments with full feature parity

🤖 Credits

All enhancements developed and tested using Claude Code.

Co-Authored-By: Claude [email protected]


🔗 Related

Summary by Sourcery

Introduce dedicated 5-hour and 7-day usage segments with threshold-based color and bold styling and full TUI configuration support

New Features:

  • Add separate Usage (5-hour) and Usage (7-day) segments sharing a common cache and displaying dynamic icons and reset times
  • Implement configurable warning and critical thresholds with automatic text color overrides in usage segments
  • Enable optional threshold-based bold styling for usage segments
  • Provide full TUI configurator support for editing thresholds, warning/critical colors, and bold toggles with real-time preview

Enhancements:

  • Refactor UsageSegment API cache loader and split reset time formatting into public helpers
  • Switch to Unicode arrow and compact date formatting in statusline output
  • Extend statusline renderer and metadata override system to apply dynamic color and bold settings
  • Update all built-in theme presets to include new usage segments with default threshold options
  • Enhance TUI components and navigation to conditionally display and handle 13 fields for usage segments

Build:

  • Bump package version to 1.0.9

Documentation:

  • Add README instructions for running a forked version and document new usage segments and threshold-based color configuration
  • Update CHANGELOG with 1.0.9 release notes detailing new features and changes

ekain-fr and others added 10 commits October 9, 2025 15:00
Add two new usage segments for enhanced API usage monitoring:
- Usage5Hour: Displays 5-hour usage with reset time (24% -> 11am)
- Usage7Day: Displays 7-day usage with reset datetime (12% -> Oct 9, 5am)

Features:
- Efficient shared API cache to minimize redundant calls
- Dynamic circle icons based on utilization level
- Automatic UTC to local timezone conversion
- Both segments disabled by default (opt-in)

Technical changes:
- Updated API cache structure with separate reset time fields
- Added time formatting functions for 5-hour and 7-day displays
- Updated all 9 built-in themes to include new segments
- Enhanced UI components with new segment name mappings
- Made ApiUsageCache public for cross-module access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add comprehensive documentation for developers running a forked version
of CCometixLine, including:
- How to rebuild after pulling updates
- Installation options (local vs system-wide)
- Steps to clear old theme cache when new segments are added
- Note about binary naming (ccometixline -> ccline)

Also includes version bump to 1.0.9 in Cargo.lock.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…segments

Replace ASCII arrow (->) with Unicode rightwards arrow (→) for cleaner
display in the 5-hour and 7-day usage segments.

Changes:
- usage_5hour.rs: Format now shows "24% → 11am"
- usage_7day.rs: Format now shows "12% → Oct 9, 5am"
- README.md: Updated documentation examples to reflect new format

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Change 7-day usage segment format from "Oct 9, 5am" to "Oct 9:5am"
for more compact display by replacing comma-space with colon.

Changes:
- usage.rs: Updated format_7day_reset_time() to use colon separator
- README.md: Updated documentation example to show "Oct 9:5am"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add dynamic color changing for Usage5Hour and Usage7Day segments based on
utilization thresholds. This provides visual warnings when API usage
approaches limits.

Features:
- Configurable warning threshold (default: 60%)
- Configurable critical threshold (default: 80%)
- Custom colors for warning and critical states
- Independent configuration per segment
- Supports c16, c256, and RGB color formats

Changes:
- theme_*.rs: Added threshold options to usage segment definitions
  - warning_threshold: 60
  - critical_threshold: 80
  - warning_color: c256 226 (yellow)
  - critical_color: c256 196 (red)
- usage_5hour.rs: Implemented get_color_for_utilization() to determine
  threshold-based colors and add text_color_override to metadata
- usage_7day.rs: Same threshold logic as usage_5hour
- statusline.rs: Check for text_color_override in metadata and apply
  instead of default segment colors
- README.md: Added comprehensive documentation for threshold configuration

Usage example:
```toml
[[segments]]
id = "usage_5hour"
[segments.options]
warning_threshold = 60
critical_threshold = 80
warning_color.c256 = 226  # Yellow
critical_color.c256 = 196  # Red
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Implement full TUI support for threshold-based warning colors. Users can
now interactively configure warning/critical thresholds and colors directly
in the TUI configurator without editing config files.

Features:
- New threshold fields shown for Usage5Hour and Usage7Day segments
- Interactive threshold editing (cycle through 40/50/60/70/80/90/95%)
- Color picker integration for warning/critical colors
- Dynamic field navigation based on segment type
- Real-time preview updates

Changes:
- segment_list.rs: Extended FieldSelection enum with:
  - WarningThreshold
  - CriticalThreshold
  - WarningColor
  - CriticalColor

- settings.rs: Conditional display of threshold fields
  - Show threshold fields only for usage segments
  - Extract and display current threshold values from options
  - Display warning/critical colors with proper formatting

- app.rs: Full editing support
  - Dynamic field count (11 for usage segments, 7 for others)
  - Navigation logic updated for threshold fields
  - Threshold cycling (Enter to cycle through common values)
  - Color picker opens for WarningColor/CriticalColor
  - apply_selected_color stores colors in segment options

Usage:
1. Open TUI: ccline -c
2. Navigate to Usage5Hour or Usage7Day segment
3. Use Up/Down to select threshold fields
4. Press Enter to cycle threshold values or open color picker
5. Press [S] to save configuration

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Update TUI preview component to reflect the latest changes to usage segments:

Changes:
- Use Unicode arrow (→) instead of ASCII (->)
- Update 7-day format: "Oct 9:5am" instead of "Oct 9, 5am"
- Add get_threshold_color() method to apply threshold-based color overrides
- Update mock utilization values to demonstrate threshold states:
  - Usage5Hour: 65% (triggers warning color - yellow)
  - Usage7Day: 85% (triggers critical color - red)
- Update dynamic icons to match utilization levels

The preview now accurately shows threshold-based coloring in real-time,
allowing users to see how their threshold settings affect the display
before saving the configuration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Update default threshold colors to use 16-color ANSI palette (c16)
instead of 256-color palette (c256) for better terminal compatibility
and consistency with the TUI display.

Changes:
- theme_default.rs: Changed warning_color from c256:226 to c16:11,
  critical_color from c256:196 to c16:9
- theme_gruvbox.rs: Same color updates for both usage segments
- theme_cometix.rs: Same color updates for both usage segments
- All themes: Updated usage_7day default icon/text color from c16:11
  (yellow) to c16:12 (light blue) for visual differentiation
- README.md: Updated documentation to show c16 defaults

Color mappings:
- Warning: c16:11 (Yellow) - equivalent to c256:226
- Critical: c16:9 (Light Red) - equivalent to c256:196

Benefits:
- Better compatibility with terminals that don't support 256 colors
- Matches TUI configurator display format (16:11, 16:9)
- More consistent with other segment color definitions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add warning_bold and critical_bold options to usage segments, allowing text
to become bold when usage exceeds warning or critical thresholds. This provides
additional visual prominence for high usage states.

Features:
- New options: warning_bold (default: false), critical_bold (default: true)
- Automatic bold text when thresholds are exceeded
- Independent control for warning and critical states
- Works alongside threshold color changes

Default behavior:
- Default/Gruvbox themes: warning=normal, critical=bold
- Cometix theme: warning=bold, critical=bold (matches theme style)

Changes:
- usage_5hour.rs: Added should_be_bold() method to check bold options
  and apply text_bold_override to metadata
- usage_7day.rs: Same should_be_bold() logic for 7-day segment
- statusline.rs: Check for text_bold_override in metadata and apply
  instead of default text_bold style
- theme_*.rs: Added warning_bold and critical_bold options to all themes

Usage example:
```toml
[[segments]]
id = "usage_5hour"
[segments.options]
warning_bold = true   # Make text bold at 60% usage
critical_bold = true  # Make text bold at 80% usage
```

Result: Critical usage now displays in bold red text for maximum visibility!

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…ator

Add full TUI support for configuring warning_bold and critical_bold options in Usage (5-hour) and Usage (7-day) segments.

Changes:
- Add WarningBold and CriticalBold to FieldSelection enum
- Display bold toggle fields in settings panel with [✓]/[ ] indicators
- Add color swatches (██) for warning/critical color fields
- Update navigation to handle 13 fields for usage segments (was 11)
- Add Enter key handlers to toggle bold options
- Show status messages when bold settings are changed
- Update preview in real-time when bold options are toggled

Users can now press Enter on "Warning Bold" or "Critical Bold" fields to toggle them on/off, making it easy to configure threshold-based bold text styling without manual TOML editing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@sourcery-ai
Copy link

sourcery-ai bot commented Oct 10, 2025

Reviewer's Guide

This PR extends the CCometixLine statusline by splitting usage tracking into dedicated 5-hour and 7-day segments, layering in threshold-based color and bold styling, updating the shared cache and reset-time formatting in the core, and adding full TUI configurator support along with theme and doc updates.

File-Level Changes

Change Details Files
Dedicated 5-Hour and 7-Day usage segments
  • Created Usage5Hour and Usage7Day segment modules using shared API cache
  • Exposed load_usage_cache and separate reset-time fields in ApiUsageCache
  • Registered new SegmentId variants and updated segment exports
src/core/segments/usage_5hour.rs
src/core/segments/usage_7day.rs
src/config/types.rs
src/core/segments/mod.rs
Threshold-based styling for usage segments
  • Added get_color_for_utilization and should_be_bold methods to both segments
  • Serialized text_color_override and text_bold_override metadata
  • Extended statusline renderer to apply dynamic color and bold overrides
src/core/segments/usage_5hour.rs
src/core/segments/usage_7day.rs
src/core/statusline.rs
TUI configurator enhancements for thresholds
  • Extended FieldSelection to include warning/critical fields and adjusted field counts
  • Rendered threshold lines, color swatches (██), and bold toggles in settings
  • Implemented navigation and handlers for cycling thresholds, opening color picker, and toggling bold
src/ui/components/settings.rs
src/ui/app.rs
src/ui/components/segment_list.rs
src/ui/components/preview.rs
Core usage segment cache and reset-time formatting
  • Refactored UsageSegment to expose load_usage_cache publicly
  • Updated ApiUsageCache to store five_hour_resets_at and seven_day_resets_at separately
  • Added format_5hour_reset_time and format_7day_reset_time utilities
src/core/segments/usage.rs
Theme and documentation updates
  • Added usage_5hour and usage_7day presets in all theme modules and presets list
  • Bumped version, updated README with fork instructions and threshold docs
  • Added CHANGELOG entries for v1.0.9
src/ui/themes/*.rs
src/ui/themes/presets.rs
README.md
CHANGELOG.md
Cargo.toml

Possibly linked issues

  • #Propose 2 usage sections: 5-hours usage, weekly usage: The PR implements dedicated 5-hour and 7-day usage segments, fulfilling the issue's request for displaying usage percentages and reset times for these periods.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • The manual field index mapping in App and SettingsComponent is repetitive and brittle—consider driving the list of fields from a single declarative configuration to avoid mismatches when adding/removing fields.
  • There’s a lot of duplicated logic mapping 16-color codes to ratatui::Color in multiple places; extracting that into a shared helper would simplify the code and reduce the risk of inconsistencies.
  • Both Usage5Hour and Usage7Day segments call Config::load() on every collect() invocation; consider passing the parsed config into segment collection or caching it once to avoid redundant file reads and potential errors.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The manual field index mapping in App and SettingsComponent is repetitive and brittle—consider driving the list of fields from a single declarative configuration to avoid mismatches when adding/removing fields.
- There’s a lot of duplicated logic mapping 16-color codes to ratatui::Color in multiple places; extracting that into a shared helper would simplify the code and reduce the risk of inconsistencies.
- Both Usage5Hour and Usage7Day segments call Config::load() on every collect() invocation; consider passing the parsed config into segment collection or caching it once to avoid redundant file reads and potential errors.

## Individual Comments

### Comment 1
<location> `src/core/segments/usage_5hour.rs:114` </location>
<code_context>
+        let reset_time = UsageSegment::format_5hour_reset_time(cache.five_hour_resets_at.as_deref());
+
+        // Use the same circle icon logic based on utilization
+        let dynamic_icon = UsageSegment::get_circle_icon(five_hour_util / 100.0);
+
+        let five_hour_percent = five_hour_util.round() as u8;
</code_context>

<issue_to_address>
**question:** The utilization value is divided by 100.0 before passing to get_circle_icon, which expects a value between 0.0 and 1.0.

Please verify that five_hour_util is always a percentage and not already normalized, to ensure correct icon selection.
</issue_to_address>

### Comment 2
<location> `src/core/segments/usage_7day.rs:114` </location>
<code_context>
+        let reset_time = UsageSegment::format_7day_reset_time(cache.seven_day_resets_at.as_deref());
+
+        // Use the same circle icon logic based on utilization
+        let dynamic_icon = UsageSegment::get_circle_icon(seven_day_util / 100.0);
+
+        let seven_day_percent = seven_day_util.round() as u8;
</code_context>

<issue_to_address>
**question:** Dividing seven_day_util by 100.0 before passing to get_circle_icon may be unnecessary if the value is already normalized.

Verify that seven_day_util is consistently a percentage. If it's already normalized, dividing by 100.0 will cause incorrect icon selection.
</issue_to_address>

### Comment 3
<location> `src/core/segments/usage_5hour.rs:125` </location>
<code_context>
+        metadata.insert("five_hour_utilization".to_string(), five_hour_util.to_string());
+
+        // Check if we need to apply threshold-based color override
+        if let Some(color) = self.get_color_for_utilization(five_hour_util) {
+            // Serialize the color to JSON for metadata
+            let color_json = match color {
</code_context>

<issue_to_address>
**suggestion:** Color serialization logic is duplicated in both usage_5hour.rs and usage_7day.rs.

Refactor the color serialization into a shared helper to avoid duplication and simplify future changes.

Suggested implementation:

```rust
        // Check if we need to apply threshold-based color override
        if let Some(color) = self.get_color_for_utilization(five_hour_util) {
            // Serialize the color to JSON for metadata using shared helper
            let color_json = crate::core::segments::color_utils::serialize_ansi_color_to_json(&color);

```

1. Create a new file `src/core/segments/color_utils.rs` (or use an existing shared module) and implement the following helper function:

```rust
use crate::core::segments::AnsiColor;
use serde_json::json;

pub fn serialize_ansi_color_to_json(color: &AnsiColor) -> String {
    match color {
        AnsiColor::Color256 { c256 } => {
            json!({"c256": c256}).to_string()
        }
        AnsiColor::Color16 { c16 } => {
            json!({"c16": c16}).to_string()
        }
        AnsiColor::Rgb { r, g, b } => {
            json!({"r": r, "g": g, "b": b}).to_string()
        }
    }
}
```

2. Add `mod color_utils;` to the appropriate place in your module tree (e.g., in `src/core/segments/mod.rs`).

3. Update `usage_7day.rs` to use the same helper function for color serialization.

4. Ensure all references to color serialization in your codebase use this helper for consistency.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Address code review comments by introducing shared helper functions and
clarifying utilization value format:

**New shared utilities (color_utils.rs):**
- serialize_ansi_color_to_json(): Eliminates duplicated color serialization
- c16_to_ratatui_color(): Centralizes 16-color ANSI to ratatui::Color mapping
- ansi_color_to_ratatui(): Handles all color formats (c16, c256, RGB)

**Refactored files:**
- usage_5hour.rs: Use serialize_ansi_color_to_json(), clarify utilization format
- usage_7day.rs: Use serialize_ansi_color_to_json(), clarify utilization format
- settings.rs: Replace 6 duplicated color mappings with color_utils helpers
- app.rs: Use serialize_ansi_color_to_json() for warning/critical colors
- mod.rs: Export new color_utils module

**Documentation improvements:**
- Added comments clarifying utilization values are percentages (0-100)
- Added comments explaining division by 100 converts to normalized values (0-1)
- This addresses reviewer questions about get_circle_icon expectations

**Code quality improvements:**
- Reduced duplication: ~100 lines of repeated color mapping code eliminated
- Single source of truth: Color conversion logic now centralized
- Maintainability: Future color format changes only require updating one place
- Consistency: All color conversions now use the same helper functions

Addresses review comments from PR code review.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@ekain-fr ekain-fr closed this Oct 10, 2025
@ekain-fr ekain-fr deleted the feat/enhanced-usage-segments branch October 10, 2025 12:38
@ekain-fr ekain-fr restored the feat/enhanced-usage-segments branch October 10, 2025 14:39
Add missing warning/critical threshold configurations to usage 5-hour and
7-day segments in minimal, nord, and all powerline themes. These themes were
missing the threshold options that were already present in default, gruvbox,
and cometix themes.

Adds the following threshold options to usage segments:
- warning_threshold: 60% (triggers yellow color)
- critical_threshold: 80% (triggers red color with bold text)
- warning_color: yellow (ANSI c16: 11)
- critical_color: red (ANSI c16: 9)
- warning_bold: false
- critical_bold: true

This ensures all themes have consistent threshold-based visual feedback for
usage tracking segments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@ekain-fr ekain-fr reopened this Oct 10, 2025
ekain-fr added a commit to ekain-fr/CCometixLine that referenced this pull request Oct 10, 2025
Extend threshold-based color and bold text support to the context window segment,
matching the implementation from usage segments (5-hour/7-day). This provides
visual feedback when context usage exceeds configurable warning (60%) and critical
(80%) thresholds.

**Implementation:**
- context_window.rs: Add get_color_for_utilization() and should_be_bold() methods
  - Uses color_utils::serialize_ansi_color_to_json() from PR Haleclipse#41
  - Checks utilization against warning_threshold (default 60%) and critical_threshold (default 80%)
  - Returns appropriate color/bold overrides based on threshold levels
- app.rs, settings.rs: Include ContextWindow in threshold segment checks for TUI
  - Enables threshold configuration UI for context window segment
  - Adds 6 threshold fields (thresholds, colors, bold flags) to segment settings
- All 9 themes: Add threshold options to context_window_segment() functions
  - warning_threshold: 60%, critical_threshold: 80%
  - warning_color: c16=11 (yellow), critical_color: c16=9 (red)
  - Cometix/Gruvbox: Both thresholds use bold (warning_bold/critical_bold: true)
  - Default/Minimal/Nord/Powerline themes: Only critical uses bold

**Dependencies:**
- Requires color_utils module from PR Haleclipse#41 (enhanced-usage-segments)
- This PR should not be merged until PR Haleclipse#41 is merged

**Default behavior:**
- Warning: 60% utilization → yellow text, normal weight (bold in Cometix/Gruvbox)
- Critical: 80% utilization → red text, bold weight
- Below warning: Uses default segment colors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@durandom
Copy link

would love to get that in. what's missing here?

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