Skip to content

feat(watch): add localized system stats to watch dashboard#160

Merged
utkarsh232005 merged 10 commits into
KDM-cli:mainfrom
utkarsh232005:feature/watch-system-usage-stats
Jun 11, 2026
Merged

feat(watch): add localized system stats to watch dashboard#160
utkarsh232005 merged 10 commits into
KDM-cli:mainfrom
utkarsh232005:feature/watch-system-usage-stats

Conversation

@utkarsh232005

@utkarsh232005 utkarsh232005 commented Jun 11, 2026

Copy link
Copy Markdown
Member

Closes #117

Description

This PR introduces system resource stats (CPU and Memory) directly into the kdm watch dashboard:

  • Docker Section: Aggregates CPU % and Memory usage dynamically across running containers, complying with cgroups v1 & v2.
  • Kubernetes Section: Queries metrics-server nodes/pods dynamically, with a fallback to native resource requests sum.
  • Includes thorough JSDoc documentation and unit testing coverage.

Summary by CodeRabbit

  • New Features

    • Dashboard now displays Kubernetes cluster-level CPU and memory statistics with source attribution (metrics-server, requests, or N/A).
    • Added Docker system resource stats including total CPU percentage and memory usage/limits visible on the dashboard.
    • Stats automatically refresh every 3 seconds for real-time updates.
  • Tests

    • Comprehensive test suite for stats utilities covering CPU/memory parsing, formatting, and aggregation scenarios.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@utkarsh232005, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 26 minutes and 30 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b1599bcf-ba52-4612-8238-8b72b45befd0

📥 Commits

Reviewing files that changed from the base of the PR and between 3a8ad70 and aa2a9eb.

📒 Files selected for processing (5)
  • src/__tests__/stats.test.ts
  • src/__tests__/watch-dashboard.test.tsx
  • src/docker/containers.ts
  • src/kubernetes/pods.ts
  • src/server/server.ts

Warning

.coderabbit.yaml has a parsing error

The CodeRabbit configuration file in this repository has a parsing error and default settings were used instead. Please fix the error(s) in the configuration file. You can initialize chat with CodeRabbit to get help with the configuration file.

💥 Parsing errors (2)
Validation error: Invalid input: expected string, received undefined at "reviews.path_instructions[3].path"; Invalid input: expected string, received undefined at "reviews.path_instructions[3].instructions"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • 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
📝 Walkthrough

Walkthrough

This PR adds system-level resource monitoring to kdm watch, collecting Docker aggregate stats via the Docker API and Kubernetes cluster stats via metrics-server (with native requests fallback), then displaying both in separate dashboard panels with 3-second polling intervals.

Changes

System Stats Dashboard Integration

Layer / File(s) Summary
Docker system stats aggregation
src/docker/containers.ts
DockerSystemStats interface and getDockerSystemStats() export aggregate CPU percentage and memory usage/limit across running containers, with byte formatter and per-container helpers to compute CPU deltas and memory net of cache.
Kubernetes cluster stats module
src/kubernetes/pods.ts
K8sClusterStats interface and getK8sClusterStats() export with parsing utilities for Kubernetes CPU/memory quantities. Aggregation prioritizes metrics-server node stats, falls back to pod stats, then native pod resource requests, and returns N/A when all sources fail.
Dashboard UI integration
src/ui/WatchDashboard.tsx
Component adds k8sStats and dockerStats state, imports both fetcher functions, extends polling loop to refresh stats every 3 seconds, and renders CPU/memory values in separate Kubernetes and Docker panels with null fallback.
Test suite
src/__tests__/stats.test.ts
Comprehensive Vitest suite mocks Docker and Kubernetes APIs and validates quantity parsing, byte formatting across binary and decimal units, Docker stats aggregation, and Kubernetes multi-source fallback behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Stats now bloom in kdm's display,
Docker and Kubernetes at play,
CPU, memory—watch them dance,
Three-second heartbeat; metrics prance,
No more jumping out to see the load!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding system stats display to the watch dashboard, which is the central objective across all file modifications.
Linked Issues check ✅ Passed The PR implements all core requirements from issue #117: Docker stats (CPU %, memory), Kubernetes stats (metrics-server with fallback to requests), graceful degradation, and reasonable update intervals (3 seconds).
Out of Scope Changes check ✅ Passed All changes are directly related to implementing system stats for Docker and Kubernetes sections as specified in issue #117; no unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.64865% with 21 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/docker/containers.ts 82.69% 1 Missing and 8 partials ⚠️
src/kubernetes/pods.ts 91.66% 0 Missing and 9 partials ⚠️
src/ui/WatchDashboard.tsx 85.71% 0 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/docker/containers.ts (1)

125-137: ⚡ Quick win

Consider logging errors for debugging visibility.

The catch block silently swallows errors when fetching container stats. While returning zero values is appropriate for graceful degradation, logging the error (at least at debug level) would help diagnose issues when containers fail to report stats.

🔍 Proposed enhancement
   } catch {
+    logger.debug(`Failed to fetch stats for container ${containerId}`);
     return { cpuPercent: 0, memoryUsage: 0, limit: 0 };
   }
🤖 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/docker/containers.ts` around lines 125 - 137, The fetchContainerStats
function swallows errors silently; update the catch to capture the error (catch
(err)) and log it for visibility before returning zeros—use the module logger if
available (e.g., processLogger.debug or logger.debug), otherwise fall back to
console.debug/console.error; keep the existing return { cpuPercent: 0,
memoryUsage: 0, limit: 0 } for graceful degradation.
🤖 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/docker/containers.ts`:
- Around line 143-180: getDockerSystemStats currently uses the maximum
per-container limit (computed from results of fetchContainerStats) as
memoryLimit which misrepresents aggregate host capacity; change it to always
call docker.info() to obtain MemTotal and use that as memoryLimit (with a safe
fallback like 0) regardless of container limits, remove the maxLimit logic that
picks the largest container limit, and ensure the docker.info() call is awaited
and error-handled before returning the final { cpu, memoryUsage, memoryLimit }
in getDockerSystemStats.

In `@src/kubernetes/pods.ts`:
- Around line 78-97: The function parseK8sCpuQuantity currently treats any
unknown non-empty suffix as cores; update it so only the known suffixes
('n','u','m','' for cores) map to conversions and all other suffixes return 0.
In practice, modify the switch in parseK8sCpuQuantity to keep cases
'n','u','m','' as-is and change the default branch to return 0 (i.e., do not
multiply unknown suffixes by 1000), so malformed inputs like '100x' yield 0
instead of being treated as cores.
- Around line 211-223: The sumPodRequests function incorrectly adds init
container requests to app container requests; change it to only sum requests
from pod.spec?.containers (exclude pod.spec?.initContainers) so
sumPodRequests(pod) uses getContainerRequests only for app containers, leaving
init containers out of the native-fallback estimate (this keeps Running pods
correct and is conservative for Pending pods).
- Around line 104-135: In parseK8sMemoryQuantity, currently unknown suffixes
fall through to being treated as raw bytes; change the logic to return 0 when a
non-empty, unrecognized suffix is present. Specifically, inside function
parseK8sMemoryQuantity after extracting suffix, allow empty suffixes to be
treated as bytes (return val), handle known binaryPower (Ki/Mi/...) and
decimalPower (k/M/...) as before, and if suffix is non-empty and not found in
either map return 0; update references to suffix and the
binaryPower/decimalPower checks accordingly.

---

Nitpick comments:
In `@src/docker/containers.ts`:
- Around line 125-137: The fetchContainerStats function swallows errors
silently; update the catch to capture the error (catch (err)) and log it for
visibility before returning zeros—use the module logger if available (e.g.,
processLogger.debug or logger.debug), otherwise fall back to
console.debug/console.error; keep the existing return { cpuPercent: 0,
memoryUsage: 0, limit: 0 } for graceful degradation.
🪄 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 Plus

Run ID: 61b8acc2-08e3-42ec-bf00-1fa5ee0f2289

📥 Commits

Reviewing files that changed from the base of the PR and between 48898f3 and 3a8ad70.

📒 Files selected for processing (4)
  • src/__tests__/stats.test.ts
  • src/docker/containers.ts
  • src/kubernetes/pods.ts
  • src/ui/WatchDashboard.tsx

Comment thread src/docker/containers.ts
Comment thread src/kubernetes/pods.ts
Comment thread src/kubernetes/pods.ts
Comment thread src/kubernetes/pods.ts
codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

…ed suffix fallbacks, and exclude initContainers
codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@utkarsh232005 utkarsh232005 force-pushed the feature/watch-system-usage-stats branch from 82545b1 to 6e9cccd Compare June 11, 2026 20:28
codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@codescene-delta-analysis codescene-delta-analysis 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.

Code Health Improved (1 files improve in Code Health)

Our agent can fix these. Install it.

Gates Passed
3 Quality Gates Passed

View Improvements
File Code Health Impact Categories Improved
WatchDashboard.tsx 9.55 → 10.00 Complex Method

Quality Gate Profile: The Bare Minimum
Install CodeScene MCP: safeguard and uplift AI-generated code. Catch issues early with our IDE extension and CLI tool.

@utkarsh232005 utkarsh232005 merged commit 196eaba into KDM-cli:main Jun 11, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Add system usage stats on kdm watch for individual sections k8s and docker

1 participant