Skip to content

refactor(fetcher)!: split system into system_{info,monitor}_* family - #227

Merged
unhappychoice merged 5 commits into
mainfrom
refactor/system-info-monitor-split
May 13, 2026
Merged

unhappychoice merged 5 commits into
mainfrom
refactor/system-info-monitor-split

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Restructures the system fetcher family around a fixed 3-segment naming pattern system_{info|monitor}_{subject} so siblings sort together and the role (static identifier vs live measurement) is visible at the fetcher name itself, not buried in opaque `kind` options.

Renames (BREAKING)

Before After
`system_cpu` `system_monitor_cpu`
`system_memory` `system_monitor_memory`
`system_uptime` `system_monitor_uptime`
`system_load` `system_monitor_load`
`system_processes` `system_monitor_processes`
`system_disk_usage` `system_monitor_disk`
`system_battery` `system_monitor_battery`

Split

`system` mixed static identity (Text+kind for terminal / os / hostname / ...) with a dynamic Entries rollup (uptime / load / cpu% / memory%). Replaced by two focused siblings:

  • `system_info_host` — Text-only, kind = terminal / os / os_version / hostname / shell / arch
  • `system_monitor_host` — Entries / TextBlock rollup

New `system_info_*` siblings

Absorb #225's 25 `system kind` extensions, prefix-stripped since the family already carries the subject:

Fetcher Kinds
`system_info_cpu` model / cores / frequency / vendor
`system_info_memory` total / swap_total
`system_info_kernel` name / version
`system_info_machine` model / vendor / serial / chassis (DMI)
`system_info_board` vendor / model (DMI)
`system_info_bios` vendor / version / date (DMI)
`system_info_locale` (no kind, single Text)
`system_info_timezone` (no kind, single Text)
`system_info_env` editor / visual / pager
`system_info_desktop` de / wm / init

Notes:

  • "host" / "machine" trade off vs the original meta: fetcher roadmap - Local / System #62 roadmap. Under this PR `system_info_host` is OS-side identity (terminal / shell / arch) and `system_info_machine` is DMI hardware (vendor / model / serial / chassis). The roadmap entry that called the DMI cluster `system_host` is now covered by `system_info_machine`.
  • The `SystemKind` enum reverts to its pre-feat(fetcher): extend system kind with CPU/memory/kernel/DMI/env identifiers #225 six-variant shape, scoped to `SystemInfoHost`. Per-fetcher `Options` / `Kind` enums own their own kind sets so each schema lists only the values that fetcher actually accepts.
  • DMI reads (`system_info_machine` / `_board` / `_bios`) stay Linux-only with `"n/a"` fallback on macOS / Windows.

Templates / examples / runtime / xtask

  • `src/templates/home_daily.toml` and `src/templates/home_splash.toml` updated to the split names
  • `examples/usecases/home_system_monitor.toml` updated across all 7 dynamic widgets
  • `src/runtime.rs` tests updated for `system_monitor_disk`
  • `xtask/src/snapshots.rs` representative-fetcher table updated for the Entries shape

Test plan

  • `cargo fmt --all -- --check`
  • `cargo clippy --all-targets -- -D warnings`
  • `cargo test` (2200 tests, all green)
  • Templates parse via `templates::tests::every_widget_fetcher_is_registered` / `every_template_renders_without_panic`

BREAKING CHANGE

Every existing `fetcher = "system*"` reference in a user's dashboard needs renaming. The new names follow a stable pattern `system_{info|monitor}_{subject}` so future additions slot in without further churn.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added many system info endpoints (BIOS, board, CPU, machine, kernel, locale, timezone, host, memory, desktop, env) and realtime monitors for battery, CPU, memory, disk, load, processes, and uptime — all with configurable/textual displays and sample outputs.
  • Refactor

    • Standardized example/template fetcher names to a consistent system_monitor_ / system_info_ scheme; registry now exposes the new info/monitor providers.
  • Documentation

    • Updated docs, examples, and renderer previews to use the new fetcher names.

Review Change Stack

Restructures the system fetcher family around a fixed 3-segment naming
pattern `system_{info|monitor}_{subject}` so siblings sort together and
the role (static identifier vs live measurement) is visible at the
fetcher name itself instead of via opaque `kind` options.

Renames:
- `system_cpu` -> `system_monitor_cpu`
- `system_memory` -> `system_monitor_memory`
- `system_uptime` -> `system_monitor_uptime`
- `system_load` -> `system_monitor_load`
- `system_processes` -> `system_monitor_processes`
- `system_disk_usage` -> `system_monitor_disk`
- `system_battery` -> `system_monitor_battery`

Split: `system` (Text+kind identity + Entries rollup) is replaced by two
focused siblings:
- `system_info_host` — Text+kind for terminal / os / os_version /
  hostname / shell / arch (the original 6 identity kinds)
- `system_monitor_host` — Entries / TextBlock rollup of os / host /
  uptime / load / cpu% / memory%

New `system_info_*` siblings absorb #225's 25 `system kind` extensions
(each prefix dropped because the family carries the subject):

- `system_info_cpu` — kind = model / cores / frequency / vendor
- `system_info_memory` — kind = total / swap_total
- `system_info_kernel` — kind = name / version
- `system_info_machine` — DMI host, kind = model / vendor / serial / chassis
- `system_info_board` — DMI motherboard, kind = vendor / model
- `system_info_bios` — DMI firmware, kind = vendor / version / date
- `system_info_locale` — single Text (no kind)
- `system_info_timezone` — single Text (no kind)
- `system_info_env` — kind = editor / visual / pager
- `system_info_desktop` — kind = de / wm / init

Note: "host" and "machine" trade off vs the original `#62` roadmap.
Under the new scheme, `system_info_host` is OS-side identity (terminal /
shell / arch) and `system_info_machine` is DMI hardware (vendor /
model / serial / chassis). The roadmap entry that called the DMI
cluster `system_host` is now covered by `system_info_machine`.

Templates / examples / runtime tests / xtask snapshots updated to the
new names. The `SystemKind` enum in `src/fetcher/system.rs` reverts to
its pre-#225 six-variant shape, scoped to `SystemInfoHost`.

BREAKING CHANGE: every existing `fetcher = "system*"` reference in a
user's dashboard needs renaming. The new names follow a stable pattern
`system_{info|monitor}_{subject}` so future additions slot in without
further churn.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Splits system fetchers into system_info_* (static identity) and system_monitor_* (live metrics); adds many new fetcher modules, shared helpers, a registry, tests, templates/snapshot updates, docs and render text edits, and removes the top-level system_dmi export.

Changes

System Fetcher Architecture Refactor

Layer / File(s) Summary
Templates, snapshots, runtime fixtures
examples/usecases/home_system_monitor.toml, src/templates/home_{splash,daily}.toml, xtask/src/snapshots.rs, src/runtime.rs
Example and template widgets, xtask preview expectations, and runtime test fixtures updated to reference system_monitor_* / system_info_* names.
Registry & shared helpers
src/fetcher/system/mod.rs
Implements fetcher registry (re-exports, realtime/cached factories), caching helpers, detection utilities, option parsing and placeholder payload helpers, and formatting utilities used across fetchers.
Static info fetchers (text)
src/fetcher/system/info_{host,cpu,memory,kernel,machine,board,bios,locale,timezone,env,desktop}.rs
Eleven new single-shape Text fetchers exposing host/machine/kernel/locale/timezone/env/desktop/cpu/memory/bios/board identity values with option schemas and sample bodies.
Realtime monitor fetchers
src/fetcher/system/monitor_{host,cpu,memory,disk,uptime,load,processes,battery}.rs
Eight new realtime metric fetchers providing Ratio/Text/Entries/Bars/Badge/TextBlock outputs as appropriate, with sample bodies and compute/fetch implementations.
Battery & processes details
src/fetcher/system/monitor_battery.rs, src/fetcher/system/monitor_processes.rs
Battery snapshot modeling, time/health/cycle optional fields, badge mapping, AC placeholders, and process top-N selection and formatting with tests.
Test helpers & centralized tests
src/fetcher/system/test_helpers.rs, src/fetcher/system/mod.rs tests
Adds EnvGuard and FetchContext helpers; expands and centralizes unit tests validating fetcher contracts, sample bodies, detection, formatting, and placeholder behavior.
Top-level fetcher edits & docs
src/fetcher/mod.rs, docs-site/..., src/render/gauge_battery.rs
Removes pub mod system_dmi;, updates inline comment example names, and updates docs and option schema text to reference system_info_*/system_monitor_*.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

"🐰 I hopped through code to split and sort,
Info whispers names while Monitors report;
New fetchers bloom, the registry hums,
Templates follow, tests beat drums;
Dashboards wake — a rabbit thumbs."

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.46% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: a refactoring that restructures the system fetcher family by splitting 'system' into 'system_{info,monitor}_*' with a specific naming pattern. The breaking change indicator (!) appropriately signals the impact.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/system-info-monitor-split

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.27320% with 340 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.67%. Comparing base (ea7a46c) to head (fa71bb3).

Files with missing lines Patch % Lines
src/fetcher/system/mod.rs 78.15% 173 Missing ⚠️
src/fetcher/system/monitor_battery.rs 84.45% 51 Missing ⚠️
src/fetcher/system/info_cpu.rs 62.50% 12 Missing ⚠️
src/fetcher/system/info_machine.rs 64.51% 11 Missing ⚠️
src/fetcher/system/info_bios.rs 66.66% 10 Missing ⚠️
src/fetcher/system/info_desktop.rs 66.66% 10 Missing ⚠️
src/fetcher/system/info_env.rs 66.66% 10 Missing ⚠️
src/fetcher/system/info_memory.rs 66.66% 10 Missing ⚠️
src/fetcher/system/info_board.rs 68.96% 9 Missing ⚠️
src/fetcher/system/info_kernel.rs 68.96% 9 Missing ⚠️
... and 9 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #227      +/-   ##
==========================================
- Coverage   95.16%   94.67%   -0.50%     
==========================================
  Files         161      181      +20     
  Lines       48131    48518     +387     
==========================================
+ Hits        45805    45932     +127     
- Misses       2326     2586     +260     
Files with missing lines Coverage Δ
src/fetcher/mod.rs 99.10% <ø> (ø)
src/fetcher/system/dmi.rs 17.07% <ø> (ø)
src/fetcher/system/monitor_cpu.rs 100.00% <100.00%> (ø)
src/fetcher/system/test_helpers.rs 100.00% <100.00%> (ø)
src/render/gauge_battery.rs 100.00% <ø> (ø)
src/runtime.rs 91.87% <100.00%> (ø)
src/fetcher/system/monitor_load.rs 97.72% <97.72%> (ø)
src/fetcher/system/monitor_uptime.rs 96.55% <96.55%> (ø)
src/fetcher/system/monitor_host.rs 97.36% <97.36%> (ø)
src/fetcher/system/monitor_processes.rs 96.96% <96.96%> (ø)
... and 15 more

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Splits `src/fetcher/system.rs` (~2900 lines) into a directory module with
one file per fetcher. The omnibus file held 19 fetchers plus shared
helpers, which makes navigation hard and pushes well past the project's
~100-line-per-file guideline.

Layout:
  src/fetcher/system/
    mod.rs              — shared helpers (cached caches, formatters,
                          env detection, payload constructors) + registration
                          entry points + test scaffolding
    dmi.rs              — DMI / SMBIOS reads (was system_dmi.rs)
    info_host.rs        — system_info_host (terminal / os / hostname / ...)
    info_cpu.rs         — system_info_cpu (model / cores / freq / vendor)
    info_memory.rs      — system_info_memory (total / swap_total)
    info_kernel.rs      — system_info_kernel (name / version)
    info_machine.rs     — system_info_machine (DMI host bundle)
    info_board.rs       — system_info_board (DMI motherboard)
    info_bios.rs        — system_info_bios (DMI firmware)
    info_locale.rs      — system_info_locale (single Text)
    info_timezone.rs    — system_info_timezone (single Text)
    info_env.rs         — system_info_env (editor / visual / pager)
    info_desktop.rs     — system_info_desktop (de / wm / init)
    monitor_host.rs     — system_monitor_host (Entries rollup)
    monitor_cpu.rs      — system_monitor_cpu (usage)
    monitor_memory.rs   — system_monitor_memory (usage)
    monitor_uptime.rs   — system_monitor_uptime
    monitor_load.rs     — system_monitor_load
    monitor_processes.rs— system_monitor_processes
    monitor_disk.rs     — system_monitor_disk (cached fetcher)
    monitor_battery.rs  — system_monitor_battery (+ battery helpers)

Each per-fetcher file owns its own `Options` / `Kind` enum / `OPTION_SCHEMAS`
constant; shared helpers (`cached_cpu_info`, `format_*`, `detect_*`,
`parse_options`, `payload`, `entry`, etc.) live in `mod.rs` and are
accessed via `super::*` from submodules. Internal helpers used by the
test module in `mod.rs` are exposed as `pub(crate)` where needed.

`pub use` re-exports every `SystemMonitor*` / `SystemInfo*` struct so
external callers and the registration list see flat names.

Naming preserved from the previous commit on this branch: still
`system_{info|monitor}_{subject}` for every fetcher.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fetcher/system/mod.rs`:
- Around line 1155-1161: The ignored live test live_system_text_all_kinds() is
still invoked by a non-ignored test
(system_text_all_kinds_helper_runs_in_regular_suite), reintroducing
host-dependent behavior into the regular test suite; fix this by preventing the
helper from running in regular runs—either mark
system_text_all_kinds_helper_runs_in_regular_suite with #[ignore], make the
helper private/only callable from the ignored test, or remove the helper
entirely so live_system_text_all_kinds() is the sole invoker and remains
isolated; update references to the helper
(system_text_all_kinds_helper_runs_in_regular_suite and
live_system_text_all_kinds) accordingly.

In `@src/fetcher/system/monitor_battery.rs`:
- Around line 164-167: The read_snapshot function currently calls
self.manager.lock().expect(...), which will panic if the mutex is poisoned;
change that to handle the PoisonError and return None instead of panicking. In
read_snapshot, replace the expect-based lock with a match or if-let that does:
on Ok(guard) continue, on Err(_) immediately return None; then continue using
the guard (the same manager variable) as before when calling manager.as_ref()
and manager.batteries().

In `@src/fetcher/system/monitor_cpu.rs`:
- Line 55: The current code uses self.state.lock().expect("cpu state mutex
poisoned") which will panic on a poisoned Mutex; change it to recover from
poison by matching the Result and using PoisonError::into_inner() on Err to
obtain the inner guard instead of panicking (e.g. let mut sys = match
self.state.lock() { Ok(g) => g, Err(e) => { /* log a warning about poisoned
mutex */ e.into_inner() } }; ), so the fetcher continues running even if the
mutex was poisoned.

In `@src/fetcher/system/monitor_disk.rs`:
- Around line 48-61: The fallback for the Shape::Ratio path currently returns a
Body::Text payload when primary_disk(&disks) is None, which breaks consumers
expecting Body::Ratio; update the unwrap_or_else branch in the primary_disk
mapping to return payload(Body::Ratio(...)) with an appropriate empty or zero
RatioData (e.g., value 0.0 and label like Some("no disks") or None and
denominator None) instead of payload(Body::Text(...)); modify the code around
primary_disk(&disks).map(...).unwrap_or_else(...) so Shape::Ratio always yields
a Body::Ratio, referencing primary_disk, payload, Body::Ratio, RatioData and
disk_label as needed.

In `@src/fetcher/system/monitor_host.rs`:
- Line 77: The current code calls self.state.lock().expect(...), which will
panic on a poisoned mutex; replace this with proper PoisonError handling in the
realtime path by matching on self.state.lock() and either recovering the guard
via poison.into_inner() or returning a degraded/empty payload (or Err) instead
of aborting. Concretely, update the code that currently uses let mut sys =
self.state.lock().expect("system state mutex poisoned") to use match
self.state.lock() { Ok(g) => g, Err(poison) => { let g = poison.into_inner(); /*
optionally log warning about poisoned lock and return degraded payload or
continue with recovered g */ } } and ensure the surrounding function (the
realtime fetcher) returns a safe degraded result or logs the error rather than
panicking; reference the self.state mutex and the realtime fetcher function
where this lock is used.

In `@src/fetcher/system/monitor_memory.rs`:
- Line 60: The code currently calls self.state.lock().expect("memory state mutex
poisoned") which will panic on a poisoned mutex; change this to handle poisoning
gracefully by matching the lock result (e.g., match self.state.lock()) and on
Err(poisonErr) either log a warning (using your module's logger) and return
early from the sampling call or recover with poisonErr.into_inner() if it's safe
to continue; replace the expect call with that match/if-let flow so the sampler
degrades instead of crashing and keep the bound variable name (sys) used
downstream.

In `@src/fetcher/system/monitor_processes.rs`:
- Around line 67-69: The fetch loop currently panics on a poisoned mutex by
calling self.state.lock().expect(...); change this to handle PoisonError and
recover the inner guard via into_inner() so the process data is still read;
specifically replace the expect usage with a match (or map_err) that on Ok
returns the guard and on Err(poison) calls poison.into_inner() to get the mutex
data, then continue to call sys.refresh_processes and top_processes as before;
apply the same fix to the other system monitor fetchers (monitor_memory.rs,
monitor_host.rs, monitor_cpu.rs, monitor_battery.rs) wherever
self.state.lock().expect is used to ensure recovery instead of panicking.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 00ce4e3a-4429-4cb2-b188-fb0884ddf00f

📥 Commits

Reviewing files that changed from the base of the PR and between b23a8bd and e2cd69f.

📒 Files selected for processing (22)
  • src/fetcher/mod.rs
  • src/fetcher/system/dmi.rs
  • src/fetcher/system/info_bios.rs
  • src/fetcher/system/info_board.rs
  • src/fetcher/system/info_cpu.rs
  • src/fetcher/system/info_desktop.rs
  • src/fetcher/system/info_env.rs
  • src/fetcher/system/info_host.rs
  • src/fetcher/system/info_kernel.rs
  • src/fetcher/system/info_locale.rs
  • src/fetcher/system/info_machine.rs
  • src/fetcher/system/info_memory.rs
  • src/fetcher/system/info_timezone.rs
  • src/fetcher/system/mod.rs
  • src/fetcher/system/monitor_battery.rs
  • src/fetcher/system/monitor_cpu.rs
  • src/fetcher/system/monitor_disk.rs
  • src/fetcher/system/monitor_host.rs
  • src/fetcher/system/monitor_load.rs
  • src/fetcher/system/monitor_memory.rs
  • src/fetcher/system/monitor_processes.rs
  • src/fetcher/system/monitor_uptime.rs
💤 Files with no reviewable changes (1)
  • src/fetcher/mod.rs
✅ Files skipped from review due to trivial changes (1)
  • src/fetcher/system/info_host.rs

Comment thread src/fetcher/system/mod.rs Resolved
Comment thread src/fetcher/system/monitor_battery.rs Resolved
Comment thread src/fetcher/system/monitor_cpu.rs Resolved
Comment thread src/fetcher/system/monitor_disk.rs Resolved
Comment thread src/fetcher/system/monitor_host.rs Resolved
Comment thread src/fetcher/system/monitor_memory.rs Resolved
Comment thread src/fetcher/system/monitor_processes.rs Resolved
…review

Distributes fetcher-specific tests from the monolithic `system/mod.rs` test
block into `#[cfg(test)] mod tests` blocks colocated with each fetcher,
matching AGENTS.md's "tests live next to the code" rule. Cross-cutting
tests (registration list, shape/sample contract sweep, helper formatters,
env detection) stay in `mod.rs`.

- New `system/test_helpers.rs` (cfg-gated) shares `ctx_text`,
  `ctx_with_shape`, `EnvGuard`, and `detect_terminal_with` across all
  per-fetcher test modules. Submodules import via
  `super::super::test_helpers::*`.

- Per-fetcher test placement:
  - `monitor_cpu::tests` — load defaults / text shape (2 tests)
  - `monitor_memory::tests` — ratio default / entries / text formatting (3 tests)
  - `monitor_uptime::tests` — text emission (1 test)
  - `monitor_load::tests` — text default / entries shape (2 tests)
  - `monitor_processes::tests` — count cap / textblock formatting (2 tests)
  - `monitor_disk::tests` — sample body / fetch defaults / bars (3 tests)
  - `monitor_host::tests` — rollup row count / textblock format (2 tests)
  - `monitor_battery::tests` — 14 tests covering text format, badge status,
    state mapping, AC fallbacks, panic-free coverage; uses
    `pub(crate)`-elevated internals (`BatterySnapshot`, `BatteryState`,
    `format_battery_text`, etc.) which are now reachable only from
    within `system_*` test modules.
  - `info_host::tests` — terminal kind default / arch / placeholder
    on unknown kind (3 tests)

Address CodeRabbit review on #227:

- Drop `system_text_all_kinds_helper_runs_in_regular_suite`: it called
  the `#[ignore]`-d `live_system_text_all_kinds` from a regular test,
  defeating the ignore boundary and reintroducing host-dependent
  behaviour into `cargo test`.

- `SystemMonitorBattery::read_snapshot` no longer panics on a poisoned
  manager mutex. `lock().unwrap_or_else(|e| e.into_inner())` matches
  the recovery pattern used elsewhere in the codebase and keeps battery
  reads working after any prior panic while holding the mutex.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
src/fetcher/system/monitor_memory.rs (1)

60-60: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid hard panic on poisoned memory-state mutex (Line 60).

expect(...) turns a recoverable poisoned lock into a hard failure on the fetch path. Recovering with into_inner() keeps the monitor path resilient.

Suggested fix
-        let mut sys = self.state.lock().expect("memory state mutex poisoned");
+        let mut sys = self
+            .state
+            .lock()
+            .unwrap_or_else(|poisoned| poisoned.into_inner());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/system/monitor_memory.rs` at line 60, The code currently panics
on a poisoned mutex via self.state.lock().expect(...); change this to recover
from a poisoned lock by matching the Result from self.state.lock() (or using
unwrap_or_else/unwrap_or) and calling into_inner() on the PoisonError to obtain
the inner guard, so the monitor remains resilient; update the lock acquisition
at the site referencing self.state.lock() to handle Err(poison) ->
poison.into_inner() and continue using the guard (e.g., bind to mut sys) instead
of calling expect().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@src/fetcher/system/monitor_memory.rs`:
- Line 60: The code currently panics on a poisoned mutex via
self.state.lock().expect(...); change this to recover from a poisoned lock by
matching the Result from self.state.lock() (or using unwrap_or_else/unwrap_or)
and calling into_inner() on the PoisonError to obtain the inner guard, so the
monitor remains resilient; update the lock acquisition at the site referencing
self.state.lock() to handle Err(poison) -> poison.into_inner() and continue
using the guard (e.g., bind to mut sys) instead of calling expect().

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b5d7eb1-3302-48e4-87e6-05d933981a3e

📥 Commits

Reviewing files that changed from the base of the PR and between e2cd69f and a17e2f7.

📒 Files selected for processing (11)
  • src/fetcher/system/info_host.rs
  • src/fetcher/system/mod.rs
  • src/fetcher/system/monitor_battery.rs
  • src/fetcher/system/monitor_cpu.rs
  • src/fetcher/system/monitor_disk.rs
  • src/fetcher/system/monitor_host.rs
  • src/fetcher/system/monitor_load.rs
  • src/fetcher/system/monitor_memory.rs
  • src/fetcher/system/monitor_processes.rs
  • src/fetcher/system/monitor_uptime.rs
  • src/fetcher/system/test_helpers.rs
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/fetcher/system/monitor_host.rs
  • src/fetcher/system/monitor_load.rs
  • src/fetcher/system/monitor_processes.rs
  • src/fetcher/system/info_host.rs
  • src/fetcher/system/monitor_disk.rs
  • src/fetcher/system/monitor_cpu.rs
  • src/fetcher/system/monitor_battery.rs

unhappychoice and others added 2 commits May 13, 2026 12:08
Sweep up stale references to the pre-rename `system` / `system_cpu` /
`system_memory` / `system_disk_usage` fetcher names that survived in
hand-written docs and inline doc comments. The auto-generated
`docs-site/src/content/docs/reference/` tree is gitignored and
regenerates from source on the next `cargo xtask`, so it's left out
of the commit.

- `src/fetcher/mod.rs`: shape-mismatch placeholder doc example
- `src/render/gauge_battery.rs`: `tone = "drain"` description
- `docs-site/src/content/docs/guides/concepts/shape.md`: Ratio fetcher list
- `docs-site/src/content/docs/guides/concepts/renderer.md`: animated_postfx example widget
- `docs-site/src/content/docs/guides/concepts/widget.md`: Realtime widget ASCII diagram

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply CodeRabbit's poison-mutex feedback consistently across the new
`system_monitor_*` family and tidy a `monitor_disk` shape-fallback path:

- `monitor_cpu` / `monitor_memory` / `monitor_host` / `monitor_processes`:
  replace `state.lock().expect("... mutex poisoned")` with
  `unwrap_or_else(|e| e.into_inner())` so a prior panic in any other
  fetcher path doesn't cascade into a hard crash on the next frame.
  Matches the recovery pattern already used by `monitor_battery`.

- `monitor_disk`: when no disks are visible, the `Shape::Ratio` (and
  default) branch now returns a `Body::Ratio { value: 0.0, label: "no
  disks" }` payload instead of falling through to `Body::Text`. Keeps
  the body type consistent with the requested shape so shape-specific
  renderers don't crash on the empty-disk edge case.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/fetcher/system/monitor_host.rs (1)

76-95: ⚡ Quick win

Split compute into smaller single-purpose helpers.

compute currently refreshes state, builds rows, and renders shape output in one function. Extracting row collection/rendering keeps it within the project’s function-size and single-responsibility target.

Refactor sketch
 impl RealtimeFetcher for SystemMonitorHost {
@@
     fn compute(&self, ctx: &FetchContext) -> Payload {
         let mut sys = self.state.lock().unwrap_or_else(|e| e.into_inner());
         sys.refresh_cpu_usage();
         sys.refresh_memory();
-        let rows = [
+        let rows = [
             ("os", self.os.clone()),
             ("host", self.host.clone()),
             ("uptime", format_uptime(System::uptime())),
             ("load", format!("{:.2}", System::load_average().one)),
             ("cpu", format!("{:.0}%", sys.global_cpu_usage())),
             ("memory", format!("{:.0}%", memory_ratio(&sys) * 100.0)),
         ];
-        match ctx.shape.unwrap_or(Shape::Entries) {
-            Shape::TextBlock => payload(Body::TextBlock(TextBlockData {
-                lines: rows.iter().map(|(k, v)| format!("{k}: {v}")).collect(),
-            })),
-            _ => payload(Body::Entries(EntriesData {
-                items: rows.iter().map(|(k, v)| entry(k, v)).collect(),
-            })),
-        }
+        render_rows(ctx.shape.unwrap_or(Shape::Entries), &rows)
     }
 }
+
+fn render_rows(shape: Shape, rows: &[(&str, String)]) -> Payload {
+    match shape {
+        Shape::TextBlock => payload(Body::TextBlock(TextBlockData {
+            lines: rows.iter().map(|(k, v)| format!("{k}: {v}")).collect(),
+        })),
+        _ => payload(Body::Entries(EntriesData {
+            items: rows.iter().map(|(k, v)| entry(k, v)).collect(),
+        })),
+    }
+}

As per coding guidelines, "Keep functions small with single responsibility, aiming for ~10–15 lines per function".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/system/monitor_host.rs` around lines 76 - 95, The compute method
in monitor_host.rs is doing three responsibilities (state refresh, building
rows, rendering by Shape); split it into small helpers: move the row
construction into a new fn build_rows(&self, sys: &System) ->
Vec<(String,String)> or build_rows(&self) -> Vec<(String,String)> and create two
render helpers like render_textblock(rows: &[(String,String)]) -> Payload and
render_entries(rows: &[(String,String)]) -> Payload; keep compute minimal by
acquiring and refreshing sys, calling build_rows, then selecting between
render_textblock and render_entries based on ctx.shape (using Shape::Entries
default) and returning that Payload. Reference compute, build_rows,
render_textblock, render_entries, rows, FetchContext, Payload, and Shape in your
changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/fetcher/system/monitor_host.rs`:
- Around line 76-95: The compute method in monitor_host.rs is doing three
responsibilities (state refresh, building rows, rendering by Shape); split it
into small helpers: move the row construction into a new fn build_rows(&self,
sys: &System) -> Vec<(String,String)> or build_rows(&self) ->
Vec<(String,String)> and create two render helpers like render_textblock(rows:
&[(String,String)]) -> Payload and render_entries(rows: &[(String,String)]) ->
Payload; keep compute minimal by acquiring and refreshing sys, calling
build_rows, then selecting between render_textblock and render_entries based on
ctx.shape (using Shape::Entries default) and returning that Payload. Reference
compute, build_rows, render_textblock, render_entries, rows, FetchContext,
Payload, and Shape in your changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7c58ae1d-5cbd-49b7-8e29-838f53a49234

📥 Commits

Reviewing files that changed from the base of the PR and between 61722d3 and fa71bb3.

📒 Files selected for processing (5)
  • src/fetcher/system/monitor_cpu.rs
  • src/fetcher/system/monitor_disk.rs
  • src/fetcher/system/monitor_host.rs
  • src/fetcher/system/monitor_memory.rs
  • src/fetcher/system/monitor_processes.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/fetcher/system/monitor_memory.rs
  • src/fetcher/system/monitor_processes.rs
  • src/fetcher/system/monitor_cpu.rs
  • src/fetcher/system/monitor_disk.rs

@unhappychoice
unhappychoice merged commit 3500134 into main May 13, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the refactor/system-info-monitor-split branch May 13, 2026 04:03
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