diff --git a/ROADMAP.md b/ROADMAP.md index 01d3949..81bfe37 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -151,8 +151,11 @@ Root problem: full object JSON kept for every entity. /`DynamicRow` types; hidden `--discover[ --discover-resource X]` headless check; `scripts/scale/crds.sh` adds a sample CRD. Verified against lab: 68 resources incl. CRD `widgets.demo.krust.io`, listed + described 3 Widgets. 75 tests pass. - - [ ] **4.1a-2 UI** — `:api` discovery catalog overlay + interactive dynamic-browse overlay - (generic columns) + describe-on-select, wiring the `:` command fallback to the dynamic path. + - [x] **4.1a-2 UI** — `:api [filter]` shows the discovery catalog; `:` lists any + discovered resource/CRD's objects (generic columns) and `: ` describes one — all + via the proven `Overlay::Text` (command-driven, no new interactive overlay). Per-context + discovery cached. Unit test `dynamic_browse_catalog_list_and_describe`. 76 tests pass. + (Interactive selectable dynamic-list overlay deferred to 4.1c polish.) - [ ] **4.1b dynamic watches + KindId/ResourceKey refactor** (fold 24 typed watches into the dynamic path). - [ ] **4.1c navigation/UX** (discovered kinds in kind-cycle / resource picker, short names from discovery). - [ ] **4.2 Metrics integration** — `metrics.k8s.io` for real pod/node CPU+mem (top-style). diff --git a/src/ui/app.rs b/src/ui/app.rs index 0928fdd..916c32d 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -61,8 +61,8 @@ use super::search::{ use crate::{ cluster::{ - ActionError, ActionExecutor, PodLogEvent, PodLogRequest, PodLogStream, ResourceProvider, - WatchTarget, + ActionError, ActionExecutor, DiscoveredResource, PodLogEvent, PodLogRequest, PodLogStream, + ResourceProvider, WatchTarget, }, keymap::{Action, Keymap}, model::{ @@ -364,6 +364,8 @@ struct App { pending_detail_g: bool, needs_terminal_reset: bool, detail_cache: Option, + /// Per-context API discovery catalog (Phase 4.1), cached after first `:api`/dynamic browse. + discovery_cache: HashMap>, } /// On-demand full object for the active detail/describe/decode/edit view. Single-slot: holds the @@ -911,6 +913,7 @@ impl App { pending_detail_g: false, needs_terminal_reset: false, detail_cache: None, + discovery_cache: HashMap::new(), } } @@ -2034,6 +2037,23 @@ fn percent(numerator: u64, denominator: u64) -> String { format!("{pct:.0}%") } +/// Compact age (e.g. "3d", "5h", "12m") for dynamic-resource rows. +fn short_age(when: Option>) -> String { + let Some(when) = when else { + return "-".to_string(); + }; + let delta = chrono::Utc::now().signed_duration_since(when); + if delta.num_days() > 0 { + format!("{}d", delta.num_days()) + } else if delta.num_hours() > 0 { + format!("{}h", delta.num_hours()) + } else if delta.num_minutes() > 0 { + format!("{}m", delta.num_minutes()) + } else { + format!("{}s", delta.num_seconds().max(0)) + } +} + fn log_target_name(target: &LogTarget) -> String { if let Some(container) = &target.container { format!("{}/{}/{}", target.namespace, target.pod, container) @@ -2258,7 +2278,16 @@ mod tests { &self, _context: &str, ) -> anyhow::Result> { - Ok(Vec::new()) + let mut ar = kube::core::ApiResource::from_gvk(&kube::core::GroupVersionKind::gvk( + "demo.krust.io", + "v1", + "Widget", + )); + ar.plural = "widgets".to_string(); + Ok(vec![crate::cluster::DiscoveredResource { + api_resource: ar, + namespaced: true, + }]) } async fn list_dynamic( @@ -2267,7 +2296,20 @@ mod tests { _resource: &crate::cluster::DiscoveredResource, _namespace: Option<&str>, ) -> anyhow::Result> { - Ok(Vec::new()) + Ok(vec![ + crate::cluster::DynamicRow { + namespace: Some("ns-00".to_string()), + name: "widget-0".to_string(), + age: None, + status: "-".to_string(), + }, + crate::cluster::DynamicRow { + namespace: Some("ns-00".to_string()), + name: "widget-1".to_string(), + age: None, + status: "-".to_string(), + }, + ]) } async fn get_dynamic( @@ -2275,9 +2317,13 @@ mod tests { _context: &str, _resource: &crate::cluster::DiscoveredResource, _namespace: Option<&str>, - _name: &str, + name: &str, ) -> anyhow::Result { - Ok(serde_json::json!({})) + Ok(serde_json::json!({ + "apiVersion": "demo.krust.io/v1", + "kind": "Widget", + "metadata": { "name": name, "namespace": "ns-00" } + })) } } @@ -2419,6 +2465,8 @@ mod tests { "resources", "res", "aliases", + "api", + "apis", "clear", "clear-filter", "c", @@ -2788,6 +2836,38 @@ mod tests { assert!(snap.contains("[XX]")); } + #[tokio::test] + async fn dynamic_browse_catalog_list_and_describe() { + let mut app = test_app(); + + // :api catalog lists the discovered CRD. + app.show_api_catalog(None).await; + let catalog = app.current_view_text().expect("catalog overlay"); + assert!( + catalog.contains("widgets.demo.krust.io"), + "catalog: {catalog}" + ); + + // :widgets lists objects. + assert!(app.browse_dynamic("widgets", None).await); + let list = app.current_view_text().expect("list overlay"); + assert!( + list.contains("widget-0") && list.contains("widget-1"), + "list: {list}" + ); + + // :Widget (by kind) resolves too. + assert!(app.browse_dynamic("Widget", None).await); + + // :widgets widget-0 describes one object. + assert!(app.browse_dynamic("widgets", Some("widget-0")).await); + let described = app.current_view_text().expect("describe overlay"); + assert!(described.contains("kind: Widget"), "describe: {described}"); + + // Unknown token does not resolve. + assert!(!app.browse_dynamic("definitely-not-a-resource", None).await); + } + #[test] fn snapshot_describe_pane_has_viewer_state_line() { let mut app = test_app(); diff --git a/src/ui/app/command_mode.rs b/src/ui/app/command_mode.rs index e8a4f05..de06027 100644 --- a/src/ui/app/command_mode.rs +++ b/src/ui/app/command_mode.rs @@ -137,7 +137,7 @@ impl App { match cmd.as_str() { "q" | "quit" | "exit" => true, "help" | "?" => { - self.status_line = "Commands: :ctx [name] | :ns [name|all] | :kind | :fmt [yaml|json] | :c | :sources | :pause | :resume | :edit [yaml|json] | :tail | :copy | :dump | :resources | :clear | :quit | :all".to_string(); + self.status_line = "Commands: :ctx [name] | :ns [name|all] | :kind | :api [filter] | : [name] | :fmt [yaml|json] | :c | :sources | :pause | :resume | :edit [yaml|json] | :tail | :copy | :dump | :resources | :clear | :quit | :all".to_string(); false } "contexts" | "ctxs" => { @@ -283,6 +283,10 @@ impl App { self.dump_current_view(args); false } + "api" | "apis" => { + self.show_api_catalog(args.first().copied()).await; + false + } "pulse" | "pulses" | "pu" | "xray" | "popeye" | "pop" | "plugins" | "plugin" => { self.status_line = format!("Command ':{cmd}' is recognized but not implemented yet"); @@ -293,19 +297,178 @@ impl App { self.execute_resource_command(kind, args); false } - ResourceAlias::Unsupported(resource) => { - self.status_line = - format!("Resource '{resource}' is recognized but not implemented yet"); - false - } - ResourceAlias::Unknown => { - self.status_line = format!("Unknown command: :{raw}"); + // Not a curated kind — try the dynamic path (any discovered resource/CRD). + // `:` lists objects; `: ` describes one. + other => { + let name = args.first().copied(); + if self.browse_dynamic(&cmd, name).await { + return false; + } + self.status_line = match other { + ResourceAlias::Unsupported(resource) => format!( + "'{resource}' not found on this context (try the full plural, e.g. :customresourcedefinitions)" + ), + _ => format!("Unknown command or resource: :{raw}"), + }; false } }, } } + /// Discovered API resources for a context, cached after the first lookup (Phase 4.1). + pub(super) async fn discovery_for(&mut self, context: &str) -> Vec { + if let Some(cached) = self.discovery_cache.get(context) { + return cached.clone(); + } + let provider = self.resource_provider.clone(); + match provider.discover(context).await { + Ok(list) => { + self.discovery_cache + .insert(context.to_string(), list.clone()); + list + } + Err(err) => { + self.status_line = format!("API discovery failed: {err}"); + Vec::new() + } + } + } + + /// `:api [filter]` — show the discovered API resource catalog in a scrollable overlay. + pub(super) async fn show_api_catalog(&mut self, filter: Option<&str>) { + let context = self.current_tab().context.clone(); + let catalog = self.discovery_for(&context).await; + if catalog.is_empty() { + return; + } + let needle = filter.map(|f| f.to_ascii_lowercase()); + let mut lines = vec![ + format!("API resources on {context} ({} total)", catalog.len()), + String::new(), + format!("{:<46} {:<26} SCOPE", "NAME", "KIND"), + ]; + let mut shown = 0usize; + for r in &catalog { + if let Some(n) = &needle + && !r.full_name().to_ascii_lowercase().contains(n.as_str()) + && !r.kind().to_ascii_lowercase().contains(n.as_str()) + { + continue; + } + shown += 1; + lines.push(format!( + "{:<46} {:<26} {}", + r.full_name(), + r.kind(), + if r.namespaced { + "namespaced" + } else { + "cluster" + } + )); + } + lines.push(String::new()); + lines.push("Browse: : Describe: : ".to_string()); + self.overlay = Some(Overlay::Text { + title: "API Resources".to_string(), + lines, + scroll: 0, + hscroll: 0, + wrap: false, + }); + self.status_line = format!("API resources: {shown} shown / {} total", catalog.len()); + } + + /// Resolve `token` against discovery and either list its objects or, with `name`, describe one. + /// Returns false if the token doesn't match any discovered resource. + pub(super) async fn browse_dynamic(&mut self, token: &str, name: Option<&str>) -> bool { + let context = self.current_tab().context.clone(); + let tab_namespace = self.current_tab().namespace.clone(); + let catalog = self.discovery_for(&context).await; + let Some(resource) = catalog + .iter() + .find(|r| { + r.plural().eq_ignore_ascii_case(token) + || r.kind().eq_ignore_ascii_case(token) + || r.full_name().eq_ignore_ascii_case(token) + }) + .cloned() + else { + return false; + }; + + let namespace = if resource.namespaced { + tab_namespace + } else { + None + }; + let provider = self.resource_provider.clone(); + + if let Some(name) = name { + match provider + .get_dynamic(&context, &resource, namespace.as_deref(), name) + .await + { + Ok(obj) => { + let yaml = to_pretty_yaml(&obj); + self.overlay = Some(Overlay::Text { + title: format!("{} {}", resource.kind(), name), + lines: yaml.lines().map(str::to_string).collect(), + scroll: 0, + hscroll: 0, + wrap: false, + }); + self.status_line = format!("Describe {} {name}", resource.kind()); + } + Err(err) => { + self.status_line = format!("get {} {name} failed: {err}", resource.kind()) + } + } + return true; + } + + match provider + .list_dynamic(&context, &resource, namespace.as_deref()) + .await + { + Ok(rows) => { + let capped = if rows.len() >= 500 { ", capped" } else { "" }; + let mut lines = vec![ + format!( + "{} ({} shown{capped}) ns={}", + resource.full_name(), + rows.len(), + namespace.as_deref().unwrap_or("all") + ), + String::new(), + format!("{:<24} {:<50} {:<8} STATUS", "NAMESPACE", "NAME", "AGE"), + ]; + for row in &rows { + lines.push(format!( + "{:<24} {:<50} {:<8} {}", + row.namespace.as_deref().unwrap_or("-"), + row.name, + short_age(row.age), + row.status + )); + } + lines.push(String::new()); + lines.push(format!("Describe: :{token} ")); + self.overlay = Some(Overlay::Text { + title: format!("{} objects", resource.kind()), + lines, + scroll: 0, + hscroll: 0, + wrap: false, + }); + self.status_line = format!("{} {} object(s)", rows.len(), resource.kind()); + } + Err(err) => self.status_line = format!("list {} failed: {err}", resource.full_name()), + } + true + } + pub(super) fn autocomplete_command_input(&mut self) { let Some(input) = self.command_input.as_ref() else { return; diff --git a/src/ui/commands.rs b/src/ui/commands.rs index e1a6155..aba1a64 100644 --- a/src/ui/commands.rs +++ b/src/ui/commands.rs @@ -20,6 +20,8 @@ pub(crate) fn command_names() -> &'static [&'static str] { "resources", "res", "aliases", + "api", + "apis", "clear", "clear-filter", "fmt",