feat(ui): sort indicator and pods-table metric column redesign (#17)

Sort visibility:
- mark the active sort column in the table header with a direction arrow
  (Name ↑ / Status ↓) and add a [SORT] <col><dir> field to the top status bar
- add `:sort <name|namespace|status|age> [asc|desc]` command (with autocomplete)

Pods-table readability:
- reorder columns to Namespace | Name | Status | Age, then split the combined
  CPU/MEM right-sizing cell into six fixed-width, right-aligned, normalized
  columns: CPU CR CL | MEM MR ML (CR/CL = cpu %req/%lim, MR/ML = mem %req/%lim)
- per-cell severity coloring (a hot %limit reddens its own cell, not the row)
- column_spacing(2) and a flexible Name column so metrics stay aligned and
  always visible regardless of terminal width

Docs/roadmap: operator-guide updated for the new columns and :sort; ROADMAP
records the sort indicator and marks 4.4 (rendered describe) as skipped.

Tests: header-arrow render snapshot, :sort parsing, and updated pod usage
percentage assertions.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
ErfanandClaude Opus 4.8 authored and GitHub committed 2026-06-25 09:54:48 +02:00
1 parent 32e100d869
commit 75a72158fd
6 files changed
+225 -47

No files matched your search

+7 -1
View File
@@ -180,7 +180,9 @@ Root problem: full object JSON kept for every entity.
on-demand + cached per selected key (`events_cache`), like detail. Event-kind selections still show
the Event's own manifest. Hidden `--events <ns>/<name>` probe. **Verified against a real cluster
(correlated a live Warning/PolicyViolation event); unit-tested render.**
- [ ] **4.4 Rendered describe** — kubectl-style human `describe` output alongside YAML/JSON.
- [-] **4.4 Rendered describe** — SKIPPED. Prototype (kubectl-style human `describe` alongside
YAML/JSON) was implemented and rejected by the user; reverted in full. Raw YAML/JSON describe on
`d`/`v` stays the canonical detail view. Do not reintroduce without a new explicit ask.
- [~] **4.5 Filter parity** — table filter now parses k9s-style: `!term` inverse, and label
selectors `key=value`/`key==value`/`key!=value` (comma-separated, all must hold) matched against
entity labels — this also fixes `:<kind> -l app=foo`, which previously substring-matched the
@@ -209,6 +211,10 @@ Root problem: full object JSON kept for every entity.
detail-only `ctrl+d/u` paging or `gg`; added namespace/sort/reverse/events/help/close hints);
help is now **keymap-aware** (`Keymap::hint`, reflects remapped bindings); operator-guide +
README reconciled (incl. `:api`/dynamic browse). Tests: keymap hint + per-pane help accuracy.
**Sort indicator**: the active sort column is now marked in the table header with a direction
arrow (`Name ↑` / `Status ↓`), the top bar carries a `[SORT] <col><arrow>` field, and `:sort
<name|namespace|status|age> [asc|desc]` sets it explicitly (added to command autocomplete). Tests:
header-arrow render snapshot + `:sort` column/direction parsing.
Remaining: revisit when new views/commands land (e.g. interactive dynamic-list overlay).
- [ ] **5.3 Config defaults for large fleets** — review fps_limit / delta_channel_capacity /
warm_contexts / TTL defaults; document tuning.
+17 -6
View File
@@ -56,6 +56,10 @@ krust --all-contexts
- `d`: describe selected resource (toggles back to table)
- `v`: view YAML; `t`: back to table; `E`: events pane (this resource's events); `l`: logs
- `n`: cycle namespace; `s`: cycle sort column; `r`: reverse sort order
The active sort column is marked in the table header with a direction arrow (`Name ↑` ascending,
`Status ↓` descending), and the top status bar shows `[SORT] <col><arrow>`. You can also set sort
explicitly with `:sort <name|namespace|status|age> [asc|desc]`.
- `ctrl+d`: delete (guarded, table only); `ctrl+k`: kill (delete)
- `?`: toggle help (table) / search (detail panes)
- `esc`: clear filter (table) / close view (detail) / cancel pending action
@@ -70,12 +74,18 @@ like the Events section of `kubectl describe`. Selecting an Event resource itsel
## Metrics
If the cluster has a metrics-server (`metrics.k8s.io`), krust shows live usage and right-sizing:
- the **Pods table** **CPU** and **MEM** columns show `‹used› R‹%req› L‹%limit›` per pod — e.g.
`1.50c R150 L75` means using 1.5 cores, 150% of its request, 75% of its limit. `R%` is the
right-sizing signal (low = over-provisioned, ≥100 = under-requested); `L%` is the risk signal.
Cells turn yellow at ≥100% of request and red at ≥90% of limit (throttle/OOM risk).
- the **Cluster Pulse** panel shows a `[USE]` row: cluster cpu/mem used vs allocatable + util%.
If the cluster has a metrics-server (`metrics.k8s.io`), krust shows live usage and right-sizing.
The **Pods table** splits this into six right-aligned, fixed-width columns — `CPU CR CL` then
`MEM MR ML`:
- **CPU** / **MEM** — actual usage (e.g. `1.50c`, `256Mi`).
- **CR** / **MR** — usage as a percentage of the CPU/memory **request** (the right-sizing signal:
low = over-provisioned, ≥100 = under-requested). Turns yellow at ≥100%.
- **CL** / **ML** — usage as a percentage of the CPU/memory **limit** (the risk signal). Turns red
at ≥90% (throttle/OOM risk).
So a pod showing CPU `1.50c`, CR `150%`, CL `75%` is using 1.5 cores, 150% of its CPU request, and
75% of its CPU limit. Missing pieces (no request/limit, or no metrics) render as `-`. The **Cluster
Pulse** panel shows a `[USE]` row: cluster cpu/mem used vs allocatable + util%.
Without a metrics-server these degrade gracefully (columns show `-`, the table title notes
`metrics-server n/a`, and the pulse falls back to request/limit-based numbers).
@@ -116,6 +126,7 @@ Common command mode entries:
- `:<resource>` browse any discovered resource/CRD (e.g. `:endpoints`, `:widgets`); `:<resource> <name>` describes one
- `:fmt yaml|json`
- `:edit [yaml|json]`
- `:sort <name|namespace|status|age> [asc|desc]` set the table sort column/direction
## Detail Pane Behavior
+98 -24
View File
@@ -25,7 +25,7 @@ use crossterm::{
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
layout::{Alignment, Constraint, Direction, Layout},
text::{Line, Span, Text},
widgets::{Block, Borders, Cell, Padding, Paragraph, Row, Table, Wrap},
};
@@ -2180,32 +2180,52 @@ fn percent(numerator: u64, denominator: u64) -> String {
format!("{pct:.0}%")
}
/// Format a pod's per-resource usage cell as `‹used› R‹%req› L‹%limit›` and pick a severity:
/// red when usage is ≥90% of the limit (throttle/OOM risk), yellow when ≥100% of the request
/// (under-requested). A low `R%` shows over-provisioning. Missing pieces render as `R-`/`L-`,
/// and no usage at all renders as `-`.
fn pod_usage_cell(
/// A pod's per-resource usage broken into three independently-rendered, right-aligned columns:
/// actual `used`, usage as a percentage of the request (`req_pct`), and of the limit (`lim_pct`).
/// Each percentage carries its own severity: `lim` turns red at ≥90% (throttle/OOM risk), `req`
/// turns yellow at ≥100% (under-requested); a low `req_pct` flags over-provisioning. Missing
/// pieces render as `-`.
struct UsageCells {
used: String,
req_pct: String,
lim_pct: String,
req_sev: Severity,
lim_sev: Severity,
}
fn pod_usage_cells(
used: Option<u64>,
request: u64,
limit: u64,
render: fn(u64) -> String,
) -> (String, Severity) {
) -> UsageCells {
let Some(used) = used else {
return ("-".to_string(), Severity::Ok);
return UsageCells {
used: "-".to_string(),
req_pct: "-".to_string(),
lim_pct: "-".to_string(),
req_sev: Severity::Ok,
lim_sev: Severity::Ok,
};
};
let pct = |denom: u64| (denom > 0).then(|| used.saturating_mul(100) / denom);
let req_pct = pct(request);
let lim_pct = pct(limit);
let req_s = req_pct.map_or_else(|| "R-".to_string(), |v| format!("R{v}"));
let lim_s = lim_pct.map_or_else(|| "L-".to_string(), |v| format!("L{v}"));
let severity = if lim_pct.is_some_and(|v| v >= 90) {
Severity::Err
} else if req_pct.is_some_and(|v| v >= 100) {
Severity::Warn
} else {
Severity::Ok
};
(format!("{} {req_s} {lim_s}", render(used)), severity)
UsageCells {
used: render(used),
req_pct: req_pct.map_or_else(|| "-".to_string(), |v| format!("{v}%")),
lim_pct: lim_pct.map_or_else(|| "-".to_string(), |v| format!("{v}%")),
req_sev: if req_pct.is_some_and(|v| v >= 100) {
Severity::Warn
} else {
Severity::Ok
},
lim_sev: if lim_pct.is_some_and(|v| v >= 90) {
Severity::Err
} else {
Severity::Ok
},
}
}
/// Compact age (e.g. "3d", "5h", "12m") for dynamic-resource rows.
@@ -2419,7 +2439,7 @@ mod tests {
ResourceProvider, WatchTarget,
},
keymap::Keymap,
model::{Pane, ResourceEntity, ResourceKey, ResourceKind, StateDelta},
model::{Pane, ResourceEntity, ResourceKey, ResourceKind, SortColumn, StateDelta},
};
struct NoopProvider {
@@ -3042,17 +3062,44 @@ mod tests {
// actual usage
assert!(snap.contains("1.50c"), "cpu used: {snap}");
assert!(snap.contains("256Mi"), "mem used: {snap}");
// right-sizing vs request and limit
// right-sizing percentages vs request and limit, in their own columns
assert!(
snap.contains("R150") && snap.contains("L75"),
"cpu R/L: {snap}"
snap.contains("150%") && snap.contains("75%"),
"cpu %R/%L: {snap}"
); // 1500/1000, 1500/2000
assert!(
snap.contains("R200") && snap.contains("L50"),
"mem R/L: {snap}"
snap.contains("200%") && snap.contains("50%"),
"mem %R/%L: {snap}"
); // 256/128, 256/512
}
#[test]
fn table_header_marks_active_sort_column_and_direction() {
let mut app = test_app();
app.store.apply(StateDelta::Upsert(mk_entity(
"ctx-dev",
ResourceKind::Pods,
Some("default"),
"pod-a",
"Running",
)));
// Default sort is Name ascending: header shows "Name ↑" and the top bar [SORT] name↑.
app.current_tab_mut().sort = SortColumn::Name;
app.current_tab_mut().descending = false;
let snap = render_snapshot(&mut app, 160, 20);
assert!(snap.contains("Name ↑"), "name asc header: {snap}");
assert!(snap.contains("[SORT] name↑"), "sort top bar: {snap}");
// Switch to Status descending: arrow flips and moves to the Status column.
app.current_tab_mut().sort = SortColumn::Status;
app.current_tab_mut().descending = true;
let snap = render_snapshot(&mut app, 160, 20);
assert!(snap.contains("Status ↓"), "status desc header: {snap}");
assert!(!snap.contains("Name ↑"), "name no longer marked: {snap}");
assert!(snap.contains("[SORT] status↓"), "sort top bar: {snap}");
}
#[test]
fn events_pane_shows_correlated_events_for_a_pod() {
let mut app = test_app();
@@ -3169,6 +3216,33 @@ mod tests {
assert!(!app.browse_dynamic("definitely-not-a-resource", None).await);
}
#[tokio::test]
async fn sort_command_sets_column_and_direction() {
let mut app = test_app();
// Column + explicit direction.
app.execute_colon_command("sort age desc").await;
assert_eq!(app.current_tab().sort, SortColumn::Age);
assert!(app.current_tab().descending);
assert_eq!(app.status_line, "Sort: age desc");
// `ns` alias maps to Namespace; ascending.
app.execute_colon_command("sort ns asc").await;
assert_eq!(app.current_tab().sort, SortColumn::Namespace);
assert!(!app.current_tab().descending);
assert_eq!(app.status_line, "Sort: namespace asc");
// No args reports current state without changing it.
app.execute_colon_command("sort").await;
assert_eq!(app.current_tab().sort, SortColumn::Namespace);
assert_eq!(app.status_line, "Sort: namespace asc");
// Unknown column is rejected and leaves sort unchanged.
app.execute_colon_command("sort bogus").await;
assert_eq!(app.current_tab().sort, SortColumn::Namespace);
assert!(app.status_line.starts_with("Usage: :sort"));
}
#[test]
fn table_help_matches_actual_table_bindings() {
let app = test_app();
+33
View File
@@ -181,6 +181,39 @@ impl App {
self.status_line = "Namespace: all".to_string();
false
}
"sort" => {
if let Some(token) = args.first() {
let column = match token.to_ascii_lowercase().as_str() {
"name" => Some(SortColumn::Name),
"namespace" | "ns" => Some(SortColumn::Namespace),
"status" => Some(SortColumn::Status),
"age" => Some(SortColumn::Age),
_ => None,
};
let Some(column) = column else {
self.status_line =
"Usage: :sort name|namespace|status|age [asc|desc]".to_string();
return false;
};
let tab = self.current_tab_mut();
tab.sort = column;
match args.get(1).map(|d| d.to_ascii_lowercase()) {
Some(d) if d == "desc" => tab.descending = true,
Some(d) if d == "asc" => tab.descending = false,
_ => {}
}
}
let tab = self.current_tab();
let col = match tab.sort {
SortColumn::Name => "name",
SortColumn::Namespace => "namespace",
SortColumn::Status => "status",
SortColumn::Age => "age",
};
let dir = if tab.descending { "desc" } else { "asc" };
self.status_line = format!("Sort: {col} {dir}");
false
}
"kind" => {
let Some(token) = args.first() else {
self.status_line = "Usage: :kind <pods|deploy|svc|...>".to_string();
+69 -16
View File
@@ -36,8 +36,15 @@ impl App {
let selected_human = if visible_rows == 0 { 0 } else { selected + 1 };
let hb = activity_icon(revision);
let ctx_short = compact_context_name(&active.context);
let sort_col = match active.sort {
SortColumn::Name => "name",
SortColumn::Namespace => "ns",
SortColumn::Status => "status",
SortColumn::Age => "age",
};
let sort_arrow = if active.descending { "↓" } else { "↑" };
let mut top_line = format!(
"{} {} [CTX] {} ({}/{}) [NS] {} [K] {} [P] {} {} [CLR] {} [REV] +{} [STALE] {}s [SEL] {selected_human}/{} [VIS] {} [CACHE] {} [ERR] {}",
"{} {} [CTX] {} ({}/{}) [NS] {} [K] {} [P] {} {} [SORT] {sort_col}{sort_arrow} [CLR] {} [REV] +{} [STALE] {}s [SEL] {selected_human}/{} [VIS] {} [CACHE] {} [ERR] {}",
hb,
now,
ctx_short,
@@ -657,25 +664,34 @@ impl App {
let usage = self.pod_usage(key.namespace.as_deref(), &key.name);
let res =
self.store.get(key).and_then(|e| e.extracted.pod_resources);
let (cpu_str, cpu_sev) = pod_usage_cell(
let cpu = pod_usage_cells(
usage.map(|(c, _)| c),
res.map(|r| r.cpu_request_m).unwrap_or(0),
res.map(|r| r.cpu_limit_m).unwrap_or(0),
format_millicpu,
);
let (mem_str, mem_sev) = pod_usage_cell(
let mem = pod_usage_cells(
usage.map(|(_, m)| m),
res.map(|r| r.mem_request_b).unwrap_or(0),
res.map(|r| r.mem_limit_b).unwrap_or(0),
format_bytes,
);
// Right-aligned numeric cell, optionally severity-colored.
let num = |s: String, sev: Severity| {
Cell::from(Line::from(s).alignment(Alignment::Right))
.style(severity_style(&theme, sev))
};
vec![
Cell::from(row.namespace),
Cell::from(row.name),
Cell::from(status),
Cell::from(cpu_str).style(severity_style(&theme, cpu_sev)),
Cell::from(mem_str).style(severity_style(&theme, mem_sev)),
Cell::from(row.age),
num(cpu.used, Severity::Ok),
num(cpu.req_pct, cpu.req_sev),
num(cpu.lim_pct, cpu.lim_sev),
num(mem.used, Severity::Ok),
num(mem.req_pct, mem.req_sev),
num(mem.lim_pct, mem.lim_sev),
]
} else {
vec![
@@ -690,26 +706,62 @@ impl App {
})
.collect();
let (header, widths): (Vec<&str>, Vec<Constraint>) = if pods_view {
// Mark the active sort column in the header with a direction arrow.
let arrow = if active.descending { " ↓" } else { " ↑" };
// Left-aligned, sortable text header.
let mark = |label: &str, col: SortColumn| {
let text = if active.sort == col {
format!("{label}{arrow}")
} else {
label.to_string()
};
Cell::from(text)
};
// Right-aligned numeric header (matches the right-aligned numeric cells).
let num_head = |label: &str| {
Cell::from(Line::from(label.to_string()).alignment(Alignment::Right))
};
let (header, widths): (Vec<Cell>, Vec<Constraint>) = if pods_view {
(
vec!["Namespace", "Name", "Status", "CPU", "MEM", "Age"],
vec![
mark("Namespace", SortColumn::Namespace),
mark("Name", SortColumn::Name),
mark("Status", SortColumn::Status),
mark("Age", SortColumn::Age),
num_head("CPU"),
num_head("CR"),
num_head("CL"),
num_head("MEM"),
num_head("MR"),
num_head("ML"),
],
vec![
Constraint::Length(16),
Constraint::Min(18),
Constraint::Length(18),
Constraint::Length(17),
Constraint::Length(17),
Constraint::Min(20),
Constraint::Length(16),
Constraint::Length(6),
Constraint::Length(8),
Constraint::Length(6),
Constraint::Length(6),
Constraint::Length(9),
Constraint::Length(6),
Constraint::Length(6),
],
)
} else {
(
vec!["Namespace", "Name", "Status", "Age", "Summary"],
vec![
Constraint::Length(18),
Constraint::Length(38),
mark("Namespace", SortColumn::Namespace),
mark("Name", SortColumn::Name),
mark("Status", SortColumn::Status),
mark("Age", SortColumn::Age),
Cell::from("Summary"),
],
vec![
Constraint::Length(20),
Constraint::Length(10),
Constraint::Min(24),
Constraint::Length(18),
Constraint::Length(8),
Constraint::Min(10),
],
)
@@ -718,7 +770,7 @@ impl App {
let legend = if self.pod_metrics.is_empty() {
"CPU/MEM: metrics-server n/a"
} else {
"CPU/MEM = used R%req L%limit"
"CPU/MEM used · CR/CL = cpu %req/%lim · MR/ML = mem %req/%lim"
};
format!("[KIND] {} ({}) · {legend}", active.kind(), vm.len())
} else {
@@ -726,6 +778,7 @@ impl App {
};
let table = Table::new(rows, widths)
.header(Row::new(header).style(theme.table_header))
.column_spacing(2)
.block(Block::default().borders(Borders::ALL).title(title))
.row_highlight_style(theme.row_highlight);
+1
View File
@@ -16,6 +16,7 @@ pub(crate) fn command_names() -> &'static [&'static str] {
"namespace",
"all",
"0",
"sort",
"kind",
"resources",
"res",