From 1eb91d4cef2d80b87290221918399412f559a2ff Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Fri, 4 Dec 2026 12:53:02 -0800 Subject: [PATCH] feat(services): add live 2x2 container resource charts to Docker Dashboard (#8123) The container Dashboard's Resource Usage rows showed only the last 3-second docker stats reading, so spikes, memory growth and I/O bursts were invisible. They are replaced by a live, synchronized 2x2 grid of CPU, memory, disk I/O and network I/O charts fed by a new docker_container_stats_stream command (Engine API stats stream, falling back to streaming docker stats). A toolbar picks the 1/5/15-minute window, rate or total I/O, auto or limit memory scaling, and pauses or clears; hovering or the arrow keys move one crosshair across all four charts, and the last session's history stays visible after the container stops. Adds the --chart-series-secondary token. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-docker/src/engine.rs | 209 ++++- crates/ide-docker/src/lib.rs | 69 ++ crates/ide-docker/src/model.rs | 463 ++++++++++ crates/ide-host/src/ops/docker.rs | 25 +- docs/en/plugins/guides/themes.mdx | 7 +- docs/zh/plugins/guides/themes.mdx | 7 +- e2e/services.spec.ts | 152 ++++ .../themes/harbor-night.theme.json | 1 + plugins/themes.md | 3 +- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 33 + .../services/ContainerStatsCharts.test.tsx | 234 +++++ .../services/ContainerStatsCharts.tsx | 819 ++++++++++++++++++ src/features/services/Services.module.css | 259 ++++++ src/features/services/containerResources.tsx | 298 +++---- src/features/services/containerStats.test.ts | 199 +++++ src/features/services/containerStats.ts | 615 +++++++++++++ src/features/services/dashboard.tsx | 21 +- src/features/services/dashboardStats.test.tsx | 2 + src/platform/locales/text/en.json | 25 + src/platform/locales/text/zh.json | 24 + src/styles/tokens.css | 4 + 22 files changed, 3254 insertions(+), 216 deletions(-) create mode 100644 src/features/services/ContainerStatsCharts.test.tsx create mode 100644 src/features/services/ContainerStatsCharts.tsx create mode 100644 src/features/services/containerStats.test.ts create mode 100644 src/features/services/containerStats.ts diff --git a/crates/ide-docker/src/engine.rs b/crates/ide-docker/src/engine.rs index 38561dc475..2336cda904 100644 --- a/crates/ide-docker/src/engine.rs +++ b/crates/ide-docker/src/engine.rs @@ -7,8 +7,9 @@ use crate::{ COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer, - DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, - DockerProcessList, DockerSnapshot, DockerVolume, parse_info, split_csv, + DockerContainerStatsSample, DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine, + DockerNetwork, DockerObject, DockerProcessList, DockerSnapshot, DockerVolume, EngineStatsState, + parse_engine_stats_frame, parse_info, split_csv, }; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::Deserialize; @@ -66,17 +67,25 @@ pub(crate) fn address(ep: &DockerEndpoint) -> Option
{ } } +/// Parses a daemon host URL (`unix:///path`, `tcp://host:port`, `http://host:port`) +/// into a direct Engine API address when no TLS or Windows named pipe is required. +pub(crate) fn address_from_url(url: &str) -> Option
{ + let host = url.trim(); + if host.is_empty() { + return None; + } + match host.split_once("://") { + Some(("unix", rest)) if !cfg!(windows) && !rest.is_empty() => Some(Address::UnixSocket(rest.to_owned())), + Some(("tcp", rest)) | Some(("http", rest)) => host_port(rest).map(|(host, port)| Address::Tcp { host, port }), + _ => None, + } +} + /// The default endpoint's daemon: `DOCKER_HOST` when it is a plain socket or /// TCP address, else the unix socket (Windows named pipes need the CLI). fn default_address(docker_host: Option<&str>) -> Option
{ if let Some(host) = docker_host.map(str::trim).filter(|h| !h.is_empty()) { - return match host.split_once("://") { - Some(("unix", rest)) if !cfg!(windows) && !rest.is_empty() => Some(Address::UnixSocket(rest.to_owned())), - Some(("tcp", rest)) | Some(("http", rest)) => { - host_port(rest).map(|(host, port)| Address::Tcp { host, port }) - } - _ => None, - }; + return address_from_url(host); } if cfg!(unix) { Some(Address::UnixSocket("/var/run/docker.sock".into())) } else { None } } @@ -623,9 +632,77 @@ fn unix_now() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) } -/// How often a log stream that has nothing to read checks for cancellation. +fn unix_now_ms() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) +} + +/// How often a log or stats stream that has nothing to read checks for cancellation. const LOG_POLL: Duration = Duration::from_millis(200); +/// Streams live resource samples for running container `id` directly from the Docker +/// Engine HTTP API (`GET /containers/{id}/stats?stream=true`) until the container stops +/// or `cancel` fires. +pub(crate) fn container_stats_stream( + addr: &Address, + id: &str, + timeout: Duration, + cancel: &CancellationToken, + on_sample: &dyn Fn(DockerContainerStatsSample), +) -> IdeResult<()> { + let path = format!("/containers/{}/stats?stream=true", path_segment(id)); + let mut conn = Conn::connect(addr, timeout)?; + conn.write_all( + format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n").as_bytes(), + )?; + let head = read_head(&mut conn)?; + if !(200..300).contains(&head.status) { + let body = read_body(&mut conn, &head)?; + check(Response { status: head.status, body })?; + } + conn.set_timeouts(LOG_POLL); + let mut framing = BodyFraming::from_head(&head); + let mut partial = Vec::new(); + let mut payload = Vec::new(); + let mut state = EngineStatsState::default(); + let mut buf = [0u8; 8192]; + while !framing.done() { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + match conn.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + payload.clear(); + framing.decode(&buf[..n], &mut payload)?; + for &b in &payload { + if b == b'\n' { + let line = line_text(&partial); + partial.clear(); + if let Some(sample) = parse_engine_stats_frame(&line, &mut state, unix_now_ms()) { + on_sample(sample); + } + } else { + partial.push(b); + } + } + } + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted + ) => {} + Err(e) => return Err(e.into()), + } + } + if !partial.is_empty() { + let line = line_text(&partial); + if let Some(sample) = parse_engine_stats_frame(&line, &mut state, unix_now_ms()) { + on_sample(sample); + } + } + Ok(()) +} + #[derive(Deserialize, Default)] #[serde(rename_all = "PascalCase", default)] struct ApiContainerInspect { @@ -723,32 +800,30 @@ enum ChunkState { Done, } -impl LogDecoder { - fn new(head: &Head, tty: bool) -> Self { - let body = if head.chunked { - BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() } +impl BodyFraming { + fn from_head(head: &Head) -> Self { + if head.chunked { + Self::Chunked { state: ChunkState::Size, line: Vec::new() } } else if let Some(n) = head.length { - BodyFraming::Length(n) + Self::Length(n) } else { - BodyFraming::Close - }; - Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] } + Self::Close + } } fn done(&self) -> bool { - matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0)) + matches!(self, Self::Chunked { state: ChunkState::Done, .. } | Self::Length(0)) } - fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> { - let mut payload = Vec::new(); - match &mut self.body { - BodyFraming::Close => payload.extend_from_slice(bytes), - BodyFraming::Length(left) => { + fn decode(&mut self, mut bytes: &[u8], payload: &mut Vec) -> IdeResult<()> { + match self { + Self::Close => payload.extend_from_slice(bytes), + Self::Length(left) => { let take = (*left).min(bytes.len()); payload.extend_from_slice(&bytes[..take]); *left -= take; } - BodyFraming::Chunked { state, line } => { + Self::Chunked { state, line } => { while !bytes.is_empty() { match *state { ChunkState::Done => break, @@ -791,6 +866,29 @@ impl LogDecoder { } } } + Ok(()) + } +} + +impl LogDecoder { + fn new(head: &Head, tty: bool) -> Self { + Self { + body: BodyFraming::from_head(head), + tty, + header: Vec::new(), + frame_left: 0, + frame_stderr: false, + partial: [Vec::new(), Vec::new()], + } + } + + fn done(&self) -> bool { + self.body.done() + } + + fn feed(&mut self, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> { + let mut payload = Vec::new(); + self.body.decode(bytes, &mut payload)?; self.frames(&payload, emit); Ok(()) } @@ -1443,4 +1541,65 @@ mod tests { assert_eq!(path_segment("a/b"), "a%2Fb"); assert_eq!(path_segment(" sha256:ab "), "sha256%3Aab"); } + + #[test] + fn engine_stats_stream_reads_chunked_ndjson_samples() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let (mut sock, _) = listener.accept().unwrap(); + let mut req_buf = [0u8; 512]; + let n = sock.read(&mut req_buf).unwrap(); + let req = String::from_utf8_lossy(&req_buf[..n]); + assert!(req.starts_with("GET /containers/c1/stats?stream=true HTTP/1.1\r\n")); + let f1 = concat!( + r#"{"read":"2026-12-04T18:12:06Z","pids_stats":{"current":3},"#, + r#""cpu_stats":{"cpu_usage":{"total_usage":200},"system_cpu_usage":1000,"online_cpus":2},"#, + r#""precpu_stats":{"cpu_usage":{"total_usage":100},"system_cpu_usage":500,"online_cpus":2},"#, + r#""memory_stats":{"usage":52428800,"limit":104857600},"#, + r#""networks":{"eth0":{"rx_bytes":1000,"tx_bytes":500}},"#, + r#""blkio_stats":{"io_service_bytes_recursive":[{"op":"Read","value":4096},{"op":"Write","value":8192}]}}"#, + "\n", + ); + let f2 = concat!( + r#"{"read":"2026-12-04T18:12:07Z","pids_stats":{"current":4},"#, + r#""cpu_stats":{"cpu_usage":{"total_usage":250},"system_cpu_usage":1500,"online_cpus":2},"#, + r#""memory_stats":{"usage":62914560,"limit":104857600},"#, + r#""networks":{"eth0":{"rx_bytes":2500,"tx_bytes":900}},"#, + r#""blkio_stats":{"io_service_bytes_recursive":[{"op":"Read","value":4096},{"op":"Write","value":16384}]}}"#, + "\n", + ); + let mut resp = + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec(); + for chunk in [f1.as_bytes(), f2.as_bytes()] { + resp.extend(format!("{:x}\r\n", chunk.len()).as_bytes()); + resp.extend(chunk); + resp.extend(b"\r\n"); + } + resp.extend(b"0\r\n\r\n"); + sock.write_all(&resp).unwrap(); + }); + + let samples = std::sync::Mutex::new(Vec::new()); + let cancel = CancellationToken::new(); + container_stats_stream( + &Address::Tcp { host: "127.0.0.1".into(), port }, + "c1", + Duration::from_secs(5), + &cancel, + &|s| samples.lock().unwrap().push(s), + ) + .unwrap(); + server.join().unwrap(); + + let samples = samples.into_inner().unwrap(); + assert_eq!(samples.len(), 2); + assert!((samples[0].cpu_percent - 40.0).abs() < 1e-6); + assert_eq!(samples[0].mem_used_bytes, 52_428_800); + assert_eq!(samples[0].disk_write_bytes, 8192); + // Second frame lacked precpu_stats and used saved EngineStatsState: (50/500)*2*100 = 20%. + assert!((samples[1].cpu_percent - 20.0).abs() < 1e-6); + assert_eq!(samples[1].net_rx_bytes, 2500); + assert_eq!(samples[1].pids, 4); + } } diff --git a/crates/ide-docker/src/lib.rs b/crates/ide-docker/src/lib.rs index 98dd815c1a..4972326615 100644 --- a/crates/ide-docker/src/lib.rs +++ b/crates/ide-docker/src/lib.rs @@ -343,6 +343,75 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) +} + +/// Resolves `ep` to a direct Docker Engine API socket/TCP address when reachable +/// without TLS or named pipes, including `Default`/`Context` daemons such as +/// Docker Desktop (`desktop-linux`), OrbStack, or Colima. +fn resolve_engine_address(ep: &DockerEndpoint) -> Option { + if std::env::var_os("OPENIDEA_DOCKER").is_some() { + return None; + } + match ep { + DockerEndpoint::Socket { .. } | DockerEndpoint::Tcp { .. } => engine::address(ep), + DockerEndpoint::Default => { + if docker_executable().is_none() { + return engine::address(ep); + } + let url = default_daemon_url( + ide_core::process::host_var_os("DOCKER_CONTEXT").as_deref().and_then(|v| v.to_str()), + ide_core::process::host_var_os("DOCKER_HOST").as_deref().and_then(|v| v.to_str()), + |name| context_host(&DockerEndpoint::Default, name), + ) + .ok()?; + engine::address_from_url(&url).or_else(|| engine::address(ep)) + } + DockerEndpoint::Context { name } => { + let url = context_host(&DockerEndpoint::Default, Some(name.trim())).ok()?; + engine::address_from_url(&url) + } + DockerEndpoint::Ssh { .. } => None, + } +} + +/// Streams live resource samples for running container `id` until it stops or `cancel` fires. +/// Prefers the direct Engine HTTP API (`GET /containers/{id}/stats?stream=true`) for exact +/// byte counters with zero CLI process overhead; falls back to streaming `docker stats`. +pub fn stream_container_stats( + ep: &DockerEndpoint, + id: &str, + cancel: &CancellationToken, + on_sample: &dyn Fn(DockerContainerStatsSample), +) -> IdeResult<()> { + let id = check_id(id)?; + if let Some(addr) = resolve_engine_address(ep) { + let emitted = std::cell::Cell::new(false); + let res = engine::container_stats_stream(&addr, id, QUICK, cancel, &|sample| { + emitted.set(true); + on_sample(sample); + }); + match res { + Ok(()) => return Ok(()), + // If cancelled, or samples already streamed, or CLI is absent, propagate directly. + Err(e) if cancel.is_cancelled() || emitted.get() || docker_executable().is_none() => return Err(e), + Err(e) => { + tracing::debug!("direct Docker stats stream unavailable, falling back to CLI: {}", e.message); + } + } + } + let args = ["stats", "--no-trunc", "--format", "{{json .}}", id]; + let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, line| { + if stream == Stream::Stdout + && let Some(sample) = parse_cli_stats_sample(&line, unix_now_ms()) + { + on_sample(sample); + } + })?; + if ok { Ok(()) } else { Err(failure(&args, &stderr.join("\n"), "")) } +} + /// CPU and memory capacity of the Docker daemon / VM (`docker info`). pub fn host_resources(ep: &DockerEndpoint) -> IdeResult { if docker_executable().is_none() diff --git a/crates/ide-docker/src/model.rs b/crates/ide-docker/src/model.rs index e449f71144..6626f34864 100644 --- a/crates/ide-docker/src/model.rs +++ b/crates/ide-docker/src/model.rs @@ -145,6 +145,37 @@ pub struct DockerContainerStats { pub pids: String, } +/// One time-series resource sample for a running container (from Docker Engine +/// `GET /containers/{id}/stats?stream=true` or the `docker stats` CLI stream fallback). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DockerContainerStatsSample { + /// Sample timestamp as Unix epoch milliseconds. + pub timestamp_ms: u64, + /// CPU utilization percentage (may exceed 100.0 on multi-core containers). + pub cpu_percent: f64, + /// Number of CPUs visible to this container/daemon, if reported. + pub online_cpus: Option, + /// Working memory usage in bytes (excluding reclaimable page cache, matching `docker stats`). + pub mem_used_bytes: u64, + /// Effective memory limit in bytes (container cgroup limit or Docker VM memory). + pub mem_limit_bytes: u64, + /// Memory usage percentage (`0.0..=100.0`). + pub mem_percent: f64, + /// Cumulative network bytes received across all interfaces. + pub net_rx_bytes: u64, + /// Cumulative network bytes transmitted across all interfaces. + pub net_tx_bytes: u64, + /// Cumulative block device bytes read. + pub disk_read_bytes: u64, + /// Cumulative block device bytes written. + pub disk_write_bytes: u64, + /// Current PID count inside the container. + pub pids: u64, + /// True when I/O or memory counters came from rounded CLI strings rather than raw Engine API bytes. + pub approximate_io: bool, +} + /// CPU and memory capacity of the Docker daemon / VM (`docker info`). #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -517,6 +548,342 @@ pub fn parse_container_stats(text: &str) -> Option { }) } +/// Previous CPU counters retained across Engine API stats frames so CPU% stays +/// accurate even when the daemon omits `precpu_stats` on the first frame. +#[derive(Clone, Debug, Default)] +pub struct EngineStatsState { + prev_cpu_total: Option, + prev_system_cpu: Option, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiStatsFrame { + read: String, + pids_stats: ApiPidsStats, + blkio_stats: ApiBlkioStats, + storage_stats: ApiStorageStats, + cpu_stats: ApiCpuStats, + precpu_stats: ApiCpuStats, + memory_stats: ApiMemoryStats, + networks: Option>, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiPidsStats { + current: Option, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiBlkioStats { + io_service_bytes_recursive: Option>, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiBlkioEntry { + op: String, + value: u64, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiStorageStats { + read_size_bytes: Option, + write_size_bytes: Option, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiCpuStats { + cpu_usage: ApiCpuUsage, + system_cpu_usage: Option, + online_cpus: Option, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiCpuUsage { + total_usage: u64, + percpu_usage: Option>, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiMemoryStats { + usage: Option, + limit: Option, + privateworkingset: Option, + stats: Option>, +} + +#[derive(Deserialize, Default)] +#[serde(default)] +struct ApiNetworkStats { + rx_bytes: u64, + tx_bytes: u64, +} + +fn days_from_civil(year: i64, month: u32, day: u32) -> i64 { + let y = year - i64::from(month <= 2); + let era = y.div_euclid(400); + let yoe = (y - era * 400) as u64; + let m = month as u64; + let d = day as u64; + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe as i64 - 719_468 +} + +/// Parses an RFC3339 timestamp (`YYYY-MM-DDTHH:MM:SS(.frac)?(Z|±HH:MM)`) into Unix +/// epoch milliseconds, rejecting Docker's zero timestamp (`0001-01-01…`). +pub fn parse_rfc3339_ms(raw: &str) -> Option { + let s = raw.trim(); + if s.len() < 20 { + return None; + } + let b = s.as_bytes(); + if b[4] != b'-' + || b[7] != b'-' + || (b[10] != b'T' && b[10] != b't' && b[10] != b' ') + || b[13] != b':' + || b[16] != b':' + { + return None; + } + let year: i64 = s[0..4].parse().ok()?; + let month: u32 = s[5..7].parse().ok()?; + let day: u32 = s[8..10].parse().ok()?; + let hour: u64 = s[11..13].parse().ok()?; + let minute: u64 = s[14..16].parse().ok()?; + let second: u64 = s[17..19].parse().ok()?; + if year <= 1 || !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 { + return None; + } + let mut rest = &s[19..]; + let mut millis: u64 = 0; + if let Some(after_dot) = rest.strip_prefix('.') { + let digits_len = after_dot.bytes().take_while(u8::is_ascii_digit).count(); + let frac = &after_dot[..digits_len]; + let mut scale = 100u64; + for ch in frac.bytes().take(3) { + millis += u64::from(ch - b'0') * scale; + scale /= 10; + } + rest = &after_dot[digits_len..]; + } + let offset_secs: i64 = if rest.eq_ignore_ascii_case("Z") { + 0 + } else if rest.len() == 6 && (rest.starts_with('+') || rest.starts_with('-')) && rest.as_bytes()[3] == b':' { + let sign = if rest.starts_with('-') { -1i64 } else { 1i64 }; + let oh: i64 = rest[1..3].parse().ok()?; + let om: i64 = rest[4..6].parse().ok()?; + if oh > 23 || om > 59 { + return None; + } + sign * (oh * 3600 + om * 60) + } else { + return None; + }; + let days = days_from_civil(year, month, day); + let secs = days * 86_400 + (hour * 3600 + minute * 60 + second) as i64 - offset_secs; + if secs < 0 { + return None; + } + Some((secs as u64).saturating_mul(1000).saturating_add(millis)) +} + +/// Parses one newline-delimited JSON frame from Docker Engine `GET /containers/{id}/stats`. +/// Returns `None` for malformed lines or Docker's empty final frame after a container stops. +pub fn parse_engine_stats_frame( + line: &str, + state: &mut EngineStatsState, + fallback_timestamp_ms: u64, +) -> Option { + let trimmed = line.trim(); + if !trimmed.starts_with('{') { + return None; + } + let frame: ApiStatsFrame = serde_json::from_str(trimmed).ok()?; + + let mem_limit = frame.memory_stats.limit.unwrap_or(0); + let sys_cpu = frame.cpu_stats.system_cpu_usage.unwrap_or(0); + let raw_usage = frame.memory_stats.usage.unwrap_or(0); + let private_ws = frame.memory_stats.privateworkingset.unwrap_or(0); + + // When a container stops mid-stream, Docker sends a final zeroed frame with read="0001-01-01…". + if frame.read.starts_with("0001-01-01") && mem_limit == 0 && sys_cpu == 0 && raw_usage == 0 && private_ws == 0 { + return None; + } + + let timestamp_ms = parse_rfc3339_ms(&frame.read).unwrap_or(fallback_timestamp_ms); + + let online_cpus = frame + .cpu_stats + .online_cpus + .filter(|&n| n > 0) + .or_else(|| frame.cpu_stats.cpu_usage.percpu_usage.as_ref().map(|v| v.len() as u32).filter(|&n| n > 0)); + + let cur_cpu = frame.cpu_stats.cpu_usage.total_usage; + let (pre_cpu, pre_sys) = match frame.precpu_stats.system_cpu_usage.filter(|&s| s > 0) { + Some(s) => (frame.precpu_stats.cpu_usage.total_usage, s), + None => (state.prev_cpu_total.unwrap_or(0), state.prev_system_cpu.unwrap_or(0)), + }; + state.prev_cpu_total = Some(cur_cpu); + state.prev_system_cpu = Some(sys_cpu); + + let cpu_delta = cur_cpu.saturating_sub(pre_cpu); + let system_delta = sys_cpu.saturating_sub(pre_sys); + let cpu_percent = if system_delta > 0 && cpu_delta > 0 { + (cpu_delta as f64 / system_delta as f64) * f64::from(online_cpus.unwrap_or(1)) * 100.0 + } else { + 0.0 + }; + + // Match Docker CLI `calculateMemUsageUnixNoCache`: subtract inactive_file (cgroup v2) + // or total_inactive_file (cgroup v1) when below raw usage; fall back to Windows privateworkingset. + let mem_used_bytes = if raw_usage > 0 { + let reclaimable = frame + .memory_stats + .stats + .as_ref() + .and_then(|s| s.get("total_inactive_file").or_else(|| s.get("inactive_file")).copied()) + .filter(|&v| v < raw_usage) + .unwrap_or(0); + raw_usage - reclaimable + } else { + private_ws + }; + let mem_percent = if mem_limit > 0 { (mem_used_bytes as f64 / mem_limit as f64) * 100.0 } else { 0.0 }; + + let (mut net_rx_bytes, mut net_tx_bytes) = (0u64, 0u64); + if let Some(nets) = frame.networks { + for net in nets.values() { + net_rx_bytes = net_rx_bytes.saturating_add(net.rx_bytes); + net_tx_bytes = net_tx_bytes.saturating_add(net.tx_bytes); + } + } + + let (mut disk_read_bytes, mut disk_write_bytes) = (0u64, 0u64); + let mut saw_blkio = false; + if let Some(entries) = frame.blkio_stats.io_service_bytes_recursive { + for entry in entries { + if entry.op.eq_ignore_ascii_case("read") { + disk_read_bytes = disk_read_bytes.saturating_add(entry.value); + saw_blkio = true; + } else if entry.op.eq_ignore_ascii_case("write") { + disk_write_bytes = disk_write_bytes.saturating_add(entry.value); + saw_blkio = true; + } + } + } + if !saw_blkio { + disk_read_bytes = frame.storage_stats.read_size_bytes.unwrap_or(0); + disk_write_bytes = frame.storage_stats.write_size_bytes.unwrap_or(0); + } + + Some(DockerContainerStatsSample { + timestamp_ms, + cpu_percent, + online_cpus, + mem_used_bytes, + mem_limit_bytes: mem_limit, + mem_percent, + net_rx_bytes, + net_tx_bytes, + disk_read_bytes, + disk_write_bytes, + pids: frame.pids_stats.current.unwrap_or(0), + approximate_io: false, + }) +} + +fn parse_unit_bytes(raw: &str) -> u64 { + let s = raw.trim(); + if s.is_empty() { + return 0; + } + let split = s.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(s.len()); + let num = match s[..split].trim().parse::() { + Ok(v) if v.is_finite() && v > 0.0 => v, + _ => return 0, + }; + let unit = s[split..].trim(); + let mult: f64 = match unit { + "" | "B" => 1.0, + "KiB" | "Ki" => 1024.0, + "MiB" | "Mi" => 1024.0 * 1024.0, + "GiB" | "Gi" => 1024.0 * 1024.0 * 1024.0, + "TiB" | "Ti" => 1024.0 * 1024.0 * 1024.0 * 1024.0, + "PiB" | "Pi" => 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0, + "kB" | "KB" | "K" | "k" => 1000.0, + "MB" | "M" => 1000.0 * 1000.0, + "GB" | "G" => 1000.0 * 1000.0 * 1000.0, + "TB" | "T" => 1000.0 * 1000.0 * 1000.0 * 1000.0, + "PB" | "P" => 1000.0 * 1000.0 * 1000.0 * 1000.0 * 1000.0, + _ => 1.0, + }; + (num * mult).round().max(0.0) as u64 +} + +fn parse_pair_bytes(raw: &str) -> (u64, u64) { + let mut parts = raw.split('/'); + let a = parts.next().map(parse_unit_bytes).unwrap_or(0); + let b = parts.next().map(parse_unit_bytes).unwrap_or(0); + (a, b) +} + +/// Parses one line of `docker stats --no-trunc --format '{{json .}}'` (stripping any +/// leading ANSI screen-clear control codes Docker CLI emits before each JSON object). +pub fn parse_cli_stats_sample(line: &str, timestamp_ms: u64) -> Option { + let start = line.find('{')?; + let end = line.rfind('}')?; + if end < start { + return None; + } + let raw: RawStats = serde_json::from_str(&line[start..=end]).ok()?; + let cpu_percent = raw + .cpu_perc + .trim() + .trim_end_matches('%') + .trim() + .parse::() + .ok() + .filter(|v| v.is_finite() && *v >= 0.0) + .unwrap_or(0.0); + let (mem_used_bytes, mem_limit_bytes) = parse_pair_bytes(&raw.mem_usage); + let mem_percent = raw + .mem_perc + .trim() + .trim_end_matches('%') + .trim() + .parse::() + .ok() + .filter(|v| v.is_finite() && *v >= 0.0) + .unwrap_or_else(|| { + if mem_limit_bytes > 0 { (mem_used_bytes as f64 / mem_limit_bytes as f64) * 100.0 } else { 0.0 } + }); + let (net_rx_bytes, net_tx_bytes) = parse_pair_bytes(&raw.net_io); + let (disk_read_bytes, disk_write_bytes) = parse_pair_bytes(&raw.block_io); + let pids = raw.pids.trim().parse::().unwrap_or(0); + Some(DockerContainerStatsSample { + timestamp_ms, + cpu_percent, + online_cpus: None, + mem_used_bytes, + mem_limit_bytes, + mem_percent, + net_rx_bytes, + net_tx_bytes, + disk_read_bytes, + disk_write_bytes, + pids, + approximate_io: true, + }) +} + /// `docker info --format` template for daemon / VM CPU and memory capacity. pub const INFO_FORMAT: &str = r#"{"NCPU":{{json .NCPU}},"MemTotal":{{json .MemTotal}},"OperatingSystem":{{json .OperatingSystem}}}"#; @@ -937,4 +1304,100 @@ mod tests { .unwrap(); assert_eq!(found.id, "running-c"); } + + #[test] + fn parses_rfc3339_timestamps() { + assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:00Z"), Some(0)); + assert_eq!(parse_rfc3339_ms("2026-12-04T18:12:06.250999999Z"), Some(1_796_407_926_250)); + assert_eq!(parse_rfc3339_ms("2026-12-04T10:12:06.5-08:00"), Some(1_796_407_926_500)); + assert_eq!(parse_rfc3339_ms("0001-01-01T00:00:00Z"), None); + } + + #[test] + fn parses_engine_stats_frames_for_cgroup_v1_v2_and_stopped_containers() { + let mut state = EngineStatsState::default(); + // cgroup v2 frame with multi-core CPU (> 100%), multiple interfaces, and blkio. + let frame = r#"{ + "read": "2026-12-04T18:12:06.500000000Z", + "pids_stats": { "current": 17 }, + "blkio_stats": { + "io_service_bytes_recursive": [ + { "major": 259, "minor": 0, "op": "read", "value": 274000000 }, + { "major": 259, "minor": 0, "op": "write", "value": 11400000000 }, + { "major": 259, "minor": 0, "op": "sync", "value": 999 } + ] + }, + "cpu_stats": { + "cpu_usage": { "total_usage": 250000000 }, + "system_cpu_usage": 2000000000, + "online_cpus": 4 + }, + "precpu_stats": { + "cpu_usage": { "total_usage": 100000000 }, + "system_cpu_usage": 1500000000, + "online_cpus": 4 + }, + "memory_stats": { + "usage": 1000000000, + "stats": { "inactive_file": 100000000 }, + "limit": 4000000000 + }, + "networks": { + "eth0": { "rx_bytes": 280000000, "tx_bytes": 1000000 }, + "eth1": { "rx_bytes": 1000000, "tx_bytes": 200000 } + } + }"#; + let sample = parse_engine_stats_frame(frame, &mut state, 0).unwrap(); + assert_eq!(sample.timestamp_ms, 1_796_407_926_500); + // (150M / 500M) * 4 * 100 = 120% + assert!((sample.cpu_percent - 120.0).abs() < 1e-6); + assert_eq!(sample.online_cpus, Some(4)); + assert_eq!(sample.mem_used_bytes, 900_000_000); + assert_eq!(sample.mem_limit_bytes, 4_000_000_000); + assert!((sample.mem_percent - 22.5).abs() < 1e-6); + assert_eq!(sample.net_rx_bytes, 281_000_000); + assert_eq!(sample.net_tx_bytes, 1_200_000); + assert_eq!(sample.disk_read_bytes, 274_000_000); + assert_eq!(sample.disk_write_bytes, 11_400_000_000); + assert_eq!(sample.pids, 17); + assert!(!sample.approximate_io); + + // Next frame omits `precpu_stats`: uses saved EngineStatsState from previous frame. + let frame2 = r#"{ + "read": "2026-12-04T18:12:07.500000000Z", + "cpu_stats": { + "cpu_usage": { "total_usage": 300000000 }, + "system_cpu_usage": 2500000000, + "online_cpus": 4 + }, + "memory_stats": { + "usage": 500000000, + "stats": { "total_inactive_file": 50000000 }, + "limit": 4000000000 + } + }"#; + let sample2 = parse_engine_stats_frame(frame2, &mut state, 0).unwrap(); + // (50M / 500M) * 4 * 100 = 40% + assert!((sample2.cpu_percent - 40.0).abs() < 1e-6); + assert_eq!(sample2.mem_used_bytes, 450_000_000); + + // Final stopped-container empty frame is ignored. + let stopped = r#"{"read":"0001-01-01T00:00:00Z","cpu_stats":{},"memory_stats":{}}"#; + assert_eq!(parse_engine_stats_frame(stopped, &mut state, 1234), None); + } + + #[test] + fn parses_cli_stats_stream_lines_with_ansi_screen_clear() { + let line = "\x1b[2J\x1b[H{\"CPUPerc\":\"12.34%\",\"MemUsage\":\"891.8MiB / 114.3GiB\",\"MemPerc\":\"0.76%\",\"NetIO\":\"281MB / 1.2MB\",\"BlockIO\":\"274MB / 11.4GB\",\"PIDs\":\"17\"}"; + let sample = parse_cli_stats_sample(line, 42_000).unwrap(); + assert_eq!(sample.timestamp_ms, 42_000); + assert!((sample.cpu_percent - 12.34).abs() < 1e-6); + assert!(sample.mem_used_bytes > 930_000_000 && sample.mem_used_bytes < 940_000_000); + assert_eq!(sample.net_rx_bytes, 281_000_000); + assert_eq!(sample.net_tx_bytes, 1_200_000); + assert_eq!(sample.disk_read_bytes, 274_000_000); + assert_eq!(sample.disk_write_bytes, 11_400_000_000); + assert_eq!(sample.pids, 17); + assert!(sample.approximate_io); + } } diff --git a/crates/ide-host/src/ops/docker.rs b/crates/ide-host/src/ops/docker.rs index 50c878b872..02c5bf93a4 100644 --- a/crates/ide-host/src/ops/docker.rs +++ b/crates/ide-host/src/ops/docker.rs @@ -6,9 +6,9 @@ use crate::Host; use ide_command::command; use ide_core::{CancellationToken, IdeError, IdeResult, RequestId}; use ide_docker::{ - ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, - DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, - RegistryAuth, + ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerContainerStatsSample, DockerEndpoint, + DockerEvent, DockerImageLayer, DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings, + DockerSnapshot, PruneTarget, RegistryAuth, }; use ide_ssh::Tunnel; use std::collections::{BTreeMap, HashMap}; @@ -186,6 +186,24 @@ pub async fn docker_container_stats( host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await } +/// Streams live resource samples of a running container until it stops or the request is cancelled. +#[command(trust = trusted)] +pub async fn docker_container_stats_stream( + host: &Host, + request: RequestId, + endpoint: DockerEndpoint, + id: String, + on_sample: Channel, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + cancellable(host, request, move |cancel| { + ide_docker::stream_container_stats(&endpoint, &id, cancel, &|sample| { + let _ = on_sample.send(sample); + }) + }) + .await +} + /// Dev container resource limits, live usage (`docker stats`), `hostRequirements` and OOM state. #[command(trust = trusted)] pub async fn docker_devcontainer_status( @@ -367,6 +385,7 @@ ide_command::domain!( docker_compose_op, docker_container_op, docker_container_stats, + docker_container_stats_stream, docker_container_top, docker_devcontainer_status, docker_disconnect, diff --git a/docs/en/plugins/guides/themes.mdx b/docs/en/plugins/guides/themes.mdx index 40ebc01a32..8c505c47ab 100644 --- a/docs/en/plugins/guides/themes.mdx +++ b/docs/en/plugins/guides/themes.mdx @@ -389,9 +389,10 @@ conventionally go in the theme file, groups marked _editor scheme_ in the scheme ### Charts (UI theme) -| Token | Islands Dark | Islands Light | -| ---------------- | ------------ | ------------- | -| `--chart-series` | `#e07a7c` | `#d9686a` | +| Token | Islands Dark | Islands Light | +| -------------------------- | ------------ | ------------- | +| `--chart-series` | `#e07a7c` | `#d9686a` | +| `--chart-series-secondary` | `#d59637` | `#b55e12` | ### Status (UI theme) diff --git a/docs/zh/plugins/guides/themes.mdx b/docs/zh/plugins/guides/themes.mdx index d50630c229..8ff5482a58 100644 --- a/docs/zh/plugins/guides/themes.mdx +++ b/docs/zh/plugins/guides/themes.mdx @@ -353,9 +353,10 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light` ### 图表(UI 主题) -| Token | Islands 深色 | Islands 浅色 | -| ---------------- | ------------ | ------------ | -| `--chart-series` | `#e07a7c` | `#d9686a` | +| Token | Islands 深色 | Islands 浅色 | +| -------------------------- | ------------ | ------------ | +| `--chart-series` | `#e07a7c` | `#d9686a` | +| `--chart-series-secondary` | `#d59637` | `#b55e12` | ### 状态(UI 主题) diff --git a/e2e/services.spec.ts b/e2e/services.spec.ts index 29142f69d1..192ec841a0 100644 --- a/e2e/services.spec.ts +++ b/e2e/services.spec.ts @@ -1123,3 +1123,155 @@ test("Services Docker routes to the remote host daemon and switches back on disc await expect(tree.getByRole("treeitem", { name: /desktop-linux/ })).toBeVisible(); await expect(tree.getByRole("treeitem", { name: /selfhost-runner/ })).toHaveCount(0); }); + +test("Docker container dashboard renders synchronized 2x2 metrics charts and collapses cleanly when narrow", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(async () => { + const containerId = "aa4adbf07a7a1234567890abcdef1234567890abcdef1234567890abcdef1234"; + const snapshot = { + availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" }, + executable: "/usr/local/bin/docker", + containers: [ + { + id: containerId, + name: "openidea-bench-arm64", + image: "rust:1.99.1-bookworm", + command: "tail -f /dev/null", + state: "running", + status: "Up 4 minutes", + ports: "", + createdAt: "2026-12-04T18:12:06Z", + composeProject: null, + composeService: null, + composeWorkingDir: null, + composeFiles: [], + mounts: [], + networks: [], + labels: {}, + }, + ], + images: [], + volumes: [], + networks: [], + errors: [], + }; + window.__ipc.handlers.docker_settings = () => ({ + connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], + registries: [], + }); + window.__ipc.handlers.docker_snapshot = () => snapshot; + window.__ipc.handlers.docker_events = () => new Promise(() => {}); + window.__ipc.handlers.docker_inspect = () => + JSON.stringify([ + { + Created: "2026-12-04T18:12:06Z", + State: { Status: "running", Running: true, Pid: 6927, StartedAt: "2026-12-04T18:12:06Z" }, + HostConfig: { RestartPolicy: { Name: "no", MaximumRetryCount: 0 } }, + Config: { Entrypoint: [], Cmd: ["tail", "-f", "/dev/null"], Env: [], Labels: {} }, + Mounts: [], + NetworkSettings: { Ports: {}, Networks: {} }, + }, + ]); + window.__ipc.handlers.docker_container_stats_stream = ({ onSample }) => { + const GiB = 1024 ** 3; + const MiB = 1024 ** 2; + const t0 = Date.parse("2026-12-04T18:12:00Z"); + const cpuSeries = [32, 21, 30, 26, 12, 27, 6, 4, 1, 2, 0.5, 0.2, 0.1, 0.0]; + let diskRead = 40_000_000; + let diskWrite = 500_000_000; + let netRx = 20_000_000; + let netTx = 200_000; + queueMicrotask(() => { + for (let i = 0; i < cpuSeries.length; i++) { + diskRead += i < 6 ? 38_000_000 : 1_000_000; + diskWrite += i < 5 ? 1_800_000_000 : i < 8 ? 600_000_000 : 20_000_000; + netRx += i < 4 ? 62_000_000 : 1_500_000; + netTx += i < 5 ? 180_000 : 20_000; + window.__ipc.send(onSample, { + timestampMs: t0 + i * 5000, + cpuPercent: cpuSeries[i]!, + onlineCpus: 16, + memUsedBytes: Math.round((780 + i * 11) * MiB), + memLimitBytes: Math.round(114.3 * GiB), + memPercent: ((780 + i * 11) * MiB * 100) / (114.3 * GiB), + netRxBytes: netRx, + netTxBytes: netTx, + diskReadBytes: diskRead, + diskWriteBytes: diskWrite, + pids: 1 + (i < 6 ? 8 : 0), + approximateIo: false, + }); + } + }); + return new Promise(() => {}); + }; + window.__ipc.handlers.cancel_request = () => null; + + const storeMod = "/src/features/services/store.ts"; + const treeMod = "/src/features/services/tree.ts"; + const { useServices } = await import(/* @vite-ignore */ storeMod); + const { useServicesTree } = await import(/* @vite-ignore */ treeMod); + + useServices.setState({ + settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] }, + conns: { local: { snapshot, loading: false, error: null } }, + detailTab: "dashboard", + }); + useServicesTree.setState({ + expanded: new Set(["docker:local", "docker:local:group:containers"]), + selectedKey: `docker:local:container:${containerId}`, + selectedKeys: new Set([`docker:local:container:${containerId}`]), + }); + }); + + await page.keyboard.press("Meta+8"); + const services = page.getByRole("region", { name: "Services", exact: true }); + const detail = services.locator("[data-panel][id=services-detail]"); + + const cpuCard = detail.getByRole("group", { name: "CPU" }); + const memCard = detail.getByRole("group", { name: "Memory" }); + const diskCard = detail.getByRole("group", { name: "Disk I/O" }); + const netCard = detail.getByRole("group", { name: "Network I/O" }); + await cpuCard.scrollIntoViewIfNeeded(); + await expect(cpuCard).toBeVisible(); + await expect(memCard).toBeVisible(); + await expect(diskCard).toBeVisible(); + await expect(netCard).toBeVisible(); + + // Wide bottom-docked panel lays cards out in a 2x2 grid (CPU & Memory on row 1, Disk & Net on row 2). + const cpuBox = (await cpuCard.boundingBox())!; + const memBox = (await memCard.boundingBox())!; + const diskBox = (await diskCard.boundingBox())!; + const netBox = (await netCard.boundingBox())!; + expect(Math.abs(cpuBox.y - memBox.y)).toBeLessThan(2); + expect(memBox.x).toBeGreaterThan(cpuBox.x + cpuBox.width - 2); + expect(Math.abs(diskBox.y - netBox.y)).toBeLessThan(2); + expect(diskBox.y).toBeGreaterThan(cpuBox.y + cpuBox.height - 2); + + // Hovering CPU chart draws synchronized crosshairs (4 vertical lines + 6 series dots) across all 4 cards. + const cpuSvg = cpuCard.locator("svg"); + const svgBox = (await cpuSvg.boundingBox())!; + await page.mouse.move(svgBox.x + svgBox.width * 0.35, svgBox.y + svgBox.height * 0.5); + await expect(detail.locator("line[class*='chartCrosshair']")).toHaveCount(4); + await expect(detail.locator("circle[class*='chartCrosshairDot']")).toHaveCount(6); + + // Switching I/O mode to Total switches Disk I/O chart axis and primary readout to cumulative bytes. + await detail.getByRole("radiogroup", { name: "I/O chart mode" }).getByRole("radio", { name: "Total" }).click(); + await expect(diskCard.locator("svg")).toContainText("15 GB"); + await expect(diskCard.locator("svg")).not.toContainText("/s"); + + // Narrow side-docked panel (< 520px) collapses cleanly to a single column. + await page.evaluate(async () => { + const path = "/src/workbench/toolwindows/store.ts"; + const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ path); + moveToolWindow("services", "right"); + setToolWindowSize("right", 340); + }); + await cpuCard.scrollIntoViewIfNeeded(); + const narrowCpu = (await cpuCard.boundingBox())!; + const narrowMem = (await memCard.boundingBox())!; + expect(Math.abs(narrowCpu.x - narrowMem.x)).toBeLessThan(2); + expect(narrowMem.y).toBeGreaterThan(narrowCpu.y + narrowCpu.height - 2); +}); diff --git a/plugins/official/harbor-night/themes/harbor-night.theme.json b/plugins/official/harbor-night/themes/harbor-night.theme.json index 165853abd2..ff08cc0627 100644 --- a/plugins/official/harbor-night/themes/harbor-night.theme.json +++ b/plugins/official/harbor-night/themes/harbor-night.theme.json @@ -45,6 +45,7 @@ // Charts "--chart-series": "#e07a7c", + "--chart-series-secondary": "#d59637", // Status "--danger": "#f57e84", diff --git a/plugins/themes.md b/plugins/themes.md index 0c3351f9f0..b642a31e97 100644 --- a/plugins/themes.md +++ b/plugins/themes.md @@ -334,7 +334,7 @@ a token. -279 themeable tokens: 129 in the UI theme file, 150 in the editor colour scheme file. +280 themeable tokens: 130 in the UI theme file, 150 in the editor colour scheme file. ### Surfaces (UI theme) @@ -389,6 +389,7 @@ a token. | Token | Islands Dark | Islands Light | |---|---|---| | `--chart-series` | `#e07a7c` | `#d9686a` | +| `--chart-series-secondary` | `#d59637` | `#b55e12` | ### Status (UI theme) diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index f2b691a175..8000aba1f4 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -319,6 +319,7 @@ doc_sync_from_disk always project_host bin docker_compose_op trusted project_host bindings async docker_container_op trusted project_host bindings async docker_container_stats trusted project_host bindings async +docker_container_stats_stream trusted project_host bindings async docker_container_top trusted project_host bindings async docker_devcontainer_status trusted project_host bindings async docker_disconnect always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index ba7acbaf09..291df8e168 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -821,6 +821,8 @@ export const commands = { dockerContainerOp: (endpoint: DockerEndpoint, ids: string[], op: ContainerOp) => typedError(__TAURI_INVOKE("docker_container_op", { endpoint, ids, op })), /** One-shot resource usage snapshot of a running container (`docker stats --no-stream`). */ dockerContainerStats: (endpoint: DockerEndpoint, id: string) => typedError(__TAURI_INVOKE("docker_container_stats", { endpoint, id })), + /** Streams live resource samples of a running container until it stops or the request is cancelled. */ + dockerContainerStatsStream: (request: RequestId, endpoint: DockerEndpoint, id: string, onSample: Channel) => typedError(__TAURI_INVOKE("docker_container_stats_stream", { request, endpoint, id, onSample })), /** Processes running inside a container (`docker top`). */ dockerContainerTop: (endpoint: DockerEndpoint, id: string) => typedError(__TAURI_INVOKE("docker_container_top", { endpoint, id })), /** Dev container resource limits, live usage (`docker stats`), `hostRequirements` and OOM state. */ @@ -8859,6 +8861,37 @@ export type DockerContainerStats = { pids: string, }; +/** + * One time-series resource sample for a running container (from Docker Engine + * `GET /containers/{id}/stats?stream=true` or the `docker stats` CLI stream fallback). + */ +export type DockerContainerStatsSample = { + /** Sample timestamp as Unix epoch milliseconds. */ + timestampMs: number, + /** CPU utilization percentage (may exceed 100.0 on multi-core containers). */ + cpuPercent: number | null, + /** Number of CPUs visible to this container/daemon, if reported. */ + onlineCpus: number | null, + /** Working memory usage in bytes (excluding reclaimable page cache, matching `docker stats`). */ + memUsedBytes: number, + /** Effective memory limit in bytes (container cgroup limit or Docker VM memory). */ + memLimitBytes: number, + /** Memory usage percentage (`0.0..=100.0`). */ + memPercent: number | null, + /** Cumulative network bytes received across all interfaces. */ + netRxBytes: number, + /** Cumulative network bytes transmitted across all interfaces. */ + netTxBytes: number, + /** Cumulative block device bytes read. */ + diskReadBytes: number, + /** Cumulative block device bytes written. */ + diskWriteBytes: number, + /** Current PID count inside the container. */ + pids: number, + /** True when I/O or memory counters came from rounded CLI strings rather than raw Engine API bytes. */ + approximateIo: boolean, +}; + /** Which daemon a docker command talks to. */ export type DockerEndpoint = /** Whatever the CLI is configured for (`DOCKER_HOST`, the current context). */ diff --git a/src/features/services/ContainerStatsCharts.test.tsx b/src/features/services/ContainerStatsCharts.test.tsx new file mode 100644 index 0000000000..ce5048daeb --- /dev/null +++ b/src/features/services/ContainerStatsCharts.test.tsx @@ -0,0 +1,234 @@ +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { DockerContainer, DockerContainerStatsSample, DockerSnapshot } from "@/platform/ipc"; +import { ToolWindowShownProvider } from "@/workbench/contributions"; + +const streamMock = vi.hoisted(() => ({ + onMessage: null as ((sample: DockerContainerStatsSample) => void) | null, + startCalls: 0, + cancelCalls: 0, +})); + +vi.mock("@tauri-apps/api/core", async (original) => { + const actual = await original(); + class MockChannel { + onmessage: ((message: T) => void) | null = null; + } + return { ...actual, Channel: MockChannel }; +}); + +vi.mock("@/platform/ipc", async (original) => { + const actual = await original(); + return { + ...actual, + isTauri: () => true, + commands: { + ...actual.commands, + dockerContainerStatsStream: vi.fn( + (_req, _ep, _id, channel: { onmessage: ((s: DockerContainerStatsSample) => void) | null }) => { + streamMock.startCalls += 1; + streamMock.onMessage = (sample) => channel.onmessage?.(sample); + return new Promise(() => { + // Keeps stream open until cancelled. + }); + }, + ), + cancelRequest: vi.fn(async () => { + streamMock.cancelCalls += 1; + return { status: "ok" as const, data: null }; + }), + dockerVolumeSizes: vi.fn(async () => ({ status: "ok" as const, data: {} })), + dockerDevcontainerStatus: vi.fn(async () => ({ + status: "error" as const, + error: { kind: "notFound", message: "none" }, + })), + }, + }; +}); + +import { ContainerDashboard } from "./dashboard"; +import { resetContainerStatsStore } from "./containerStats"; + +const runningContainer: DockerContainer = { + id: "bench-arm64", + name: "openidea-bench-arm64", + image: "rust:1.99.1-bookworm", + command: "tail -f /dev/null", + state: "running", + status: "Up 3 minutes", + ports: "", + createdAt: "2026-12-04T18:12:06Z", + composeProject: null, + composeService: null, + composeWorkingDir: null, + composeFiles: [], + mounts: [], + networks: [], + labels: {}, +}; + +const snapshot: DockerSnapshot = { + availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" }, + executable: "/usr/local/bin/docker", + containers: [runningContainer], + images: [], + volumes: [], + networks: [], + errors: [], +}; + +const GiB = 1024 ** 3; +const MiB = 1024 ** 2; + +function emitSample(overrides: Partial = {}) { + act(() => { + streamMock.onMessage?.({ + timestampMs: 1_796_407_926_000, + cpuPercent: 25.0, + onlineCpus: 16, + memUsedBytes: Math.round(891.8 * MiB), + memLimitBytes: Math.round(114.3 * GiB), + memPercent: 0.76, + netRxBytes: 281_000_000, + netTxBytes: 1_200_000, + diskReadBytes: 274_000_000, + diskWriteBytes: 11_400_000_000, + pids: 17, + approximateIo: false, + ...overrides, + }); + }); +} + +beforeEach(() => { + resetContainerStatsStore(); + streamMock.onMessage = null; + streamMock.startCalls = 0; + streamMock.cancelCalls = 0; + vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("ContainerDashboard live 2x2 metrics charts", () => { + it("streams exact metrics into 4 synchronized charts with Rate/Total, Auto/Limit, Pause, Clear, and keyboard scrubbing", () => { + render( + + + , + ); + + expect(streamMock.startCalls).toBe(1); + emitSample({ + timestampMs: 1_796_407_926_000, + cpuPercent: 12.5, + diskReadBytes: 274_000_000, + diskWriteBytes: 11_400_000_000, + netRxBytes: 281_000_000, + netTxBytes: 1_200_000, + pids: 17, + }); + emitSample({ + timestampMs: 1_796_407_927_000, + cpuPercent: 35.0, + diskReadBytes: 275_000_000, + diskWriteBytes: 11_450_000_000, + netRxBytes: 283_000_000, + netTxBytes: 1_300_000, + pids: 19, + }); + + expect(screen.getByText("Live")).toBeInTheDocument(); + expect(screen.getByText("PIDs 19")).toBeInTheDocument(); + + const cpuCard = screen.getByRole("group", { name: "CPU" }); + expect(within(cpuCard).getByText("35.0%")).toBeInTheDocument(); + + // Auto memory scale zooms to ~1 GiB rather than flatlining at 114.3 GiB. + const memCard = screen.getByRole("group", { name: "Memory" }); + expect(within(memCard).getByText(/891\.8 MiB \/ 114\.3 GiB/)).toBeInTheDocument(); + expect(within(memCard).queryByText("114.3 GiB")).not.toBeInTheDocument(); + + // Switching Memory scale to Limit zooms Y-axis out to cover 114.3 GiB. + const memScale = screen.getByRole("radiogroup", { name: "Memory scale" }); + fireEvent.click(within(memScale).getByRole("radio", { name: "Limit" })); + expect(within(memCard).getByText("Limit")).toBeInTheDocument(); + + // Disk & Network default to Rate (B/s) with cumulative totals in sub-text. + const diskCard = screen.getByRole("group", { name: "Disk I/O" }); + expect(within(diskCard).getByText("R 1 MB/s · W 50 MB/s")).toBeInTheDocument(); + expect(within(diskCard).getByText("Total 275 MB / 11.4 GB")).toBeInTheDocument(); + // X-axis labels never repeat the same timestamp on short spans. + const diskAxisTexts = Array.from(diskCard.querySelectorAll("svg text")).map((el) => el.textContent); + const clockTicks = diskAxisTexts.filter((t) => /^\d{2}:\d{2}:\d{2}$/.test(t ?? "")); + expect(new Set(clockTicks).size).toBe(clockTicks.length); + + const netCard = screen.getByRole("group", { name: "Network I/O" }); + expect(within(netCard).getByText("↓ 2 MB/s · ↑ 100 kB/s")).toBeInTheDocument(); + + // Toggle I/O mode to Total switches Disk & Network primary readouts to cumulative totals. + const ioMode = screen.getByRole("radiogroup", { name: "I/O chart mode" }); + fireEvent.click(within(ioMode).getByRole("radio", { name: "Total" })); + expect(within(diskCard).getByText("275 MB / 11.4 GB")).toBeInTheDocument(); + expect(within(netCard).getByText("283 MB / 1.3 MB")).toBeInTheDocument(); + + // Keyboard scrubbing navigates back to sample 0 (12.5% CPU) and Escape clears scrub. + const region = screen.getByRole("region", { name: "Container resource metrics" }); + fireEvent.keyDown(region, { key: "Home" }); + expect(within(cpuCard).getByText("12.5%")).toBeInTheDocument(); + fireEvent.keyDown(region, { key: "Escape" }); + expect(within(cpuCard).getByText("35.0%")).toBeInTheDocument(); + + // Pause stops the stream and switches badge to Paused; Resume restarts it. + fireEvent.click(screen.getByRole("button", { name: "Pause metrics" })); + expect(screen.getByText("Paused")).toBeInTheDocument(); + expect(streamMock.cancelCalls).toBe(1); + fireEvent.click(screen.getByRole("button", { name: "Resume metrics" })); + expect(screen.getByText("Live")).toBeInTheDocument(); + expect(streamMock.startCalls).toBe(2); + + // Clear resets history. + fireEvent.click(screen.getByRole("button", { name: "Clear metrics history" })); + expect(screen.queryByRole("group", { name: "CPU" })).not.toBeInTheDocument(); + }); + + it("preserves recorded charts with a Last session badge when a running container stops", () => { + const { rerender } = render( + + + , + ); + + emitSample({ timestampMs: 1_796_407_926_000, cpuPercent: 88.0 }); + emitSample({ timestampMs: 1_796_407_927_000, cpuPercent: 99.0 }); + + const stoppedContainer: DockerContainer = { + ...runningContainer, + state: "exited", + status: "Exited (137) Just now", + }; + const oomInspect = JSON.stringify([ + { + Created: "2026-12-04T18:12:06Z", + State: { Status: "exited", Running: false, OOMKilled: true, ExitCode: 137 }, + HostConfig: { Memory: 4 * GiB, RestartPolicy: { Name: "no", MaximumRetryCount: 0 } }, + Config: { Entrypoint: [], Cmd: [], Env: [], Labels: {} }, + Mounts: [], + NetworkSettings: { Ports: {}, Networks: {} }, + }, + ]); + + rerender( + + + , + ); + + expect(screen.getByText("Last session")).toBeInTheDocument(); + expect(screen.getByRole("alert")).toBeInTheDocument(); + expect(within(screen.getByRole("group", { name: "CPU" })).getByText("99.0%")).toBeInTheDocument(); + }); +}); diff --git a/src/features/services/ContainerStatsCharts.tsx b/src/features/services/ContainerStatsCharts.tsx new file mode 100644 index 0000000000..ee80df915c --- /dev/null +++ b/src/features/services/ContainerStatsCharts.tsx @@ -0,0 +1,819 @@ +/** + * Synchronized 2×2 time-series charts (CPU, Memory, Disk I/O, Network I/O) + * embedded directly in Services › Docker › Container Dashboard › Resource Usage. + */ +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; +import clsx from "clsx"; +import { tx, useTx } from "@/platform/i18n"; +import { IconButton, SegmentedControl, Spinner, T } from "@/ui"; +import { + buildSegmentedPaths, + deriveStatsSeries, + formatBinaryBytes, + formatDecimalBytes, + formatLocalClock, + formatPercentCompact, + formatThroughputRate, + niceAxisTicks, + pressureForRatio, + setStatsIoMode, + setStatsMemoryScale, + setStatsTimeWindow, + summarizeValues, + TIME_WINDOW_MS, + useContainerStatsStore, + type DerivedStatsPoint, + type IoChartMode, + type MemoryScaleMode, + type PressureLevel, + type StatsSample, + type StatsTimeWindow, +} from "./containerStats"; +import styles from "./Services.module.css"; + +const PLOT_PAD = { left: 58, right: 8, top: 6, bottom: 16 }; +const MIN_CPU_CEILING = 20; +const MIN_MEM_CEILING = 64 * 1024 * 1024; +const MIN_IO_RATE_CEILING = 10_000; +const MIN_IO_TOTAL_CEILING = 1000; + +const WINDOW_OPTIONS: ReadonlyArray<{ value: StatsTimeWindow; label: string }> = [ + { value: "1m", label: "1m" }, + { value: "5m", label: "5m" }, + { value: "15m", label: "15m" }, +]; + +const IO_MODE_OPTIONS: ReadonlyArray<{ value: IoChartMode; label: string }> = [ + { value: "rate", label: "Rate" }, + { value: "total", label: "Total" }, +]; + +const MEM_SCALE_OPTIONS: ReadonlyArray<{ value: MemoryScaleMode; label: string }> = [ + { value: "auto", label: "Auto" }, + { value: "limit", label: "Limit" }, +]; + +interface ChartSeriesConfig { + id: string; + values: ReadonlyArray; + tone: "primary" | "secondary" | "warn" | "danger"; + dashed?: boolean; + fill?: boolean; +} + +interface MetricChartCardProps { + title: string; + primaryValue: string; + primaryLevel?: PressureLevel; + subText: string | null; + legend?: ReadonlyArray<{ label: string; tone: "primary" | "secondary"; dashed?: boolean }>; + points: readonly DerivedStatsPoint[]; + series: readonly ChartSeriesConfig[]; + ticks: readonly number[]; + formatTick: (v: number) => string; + referenceLine?: { value: number; label: string; level?: PressureLevel } | null; + activeIndex: number | null; + onHoverIndex: (idx: number | null) => void; +} + +function strokeClass(tone: ChartSeriesConfig["tone"]): string | undefined { + switch (tone) { + case "secondary": + return styles.chartStrokeSecondary; + case "warn": + return styles.chartStrokeWarn; + case "danger": + return styles.chartStrokeDanger; + default: + return styles.chartStrokePrimary; + } +} + +function areaClass(tone: ChartSeriesConfig["tone"]): string | undefined { + switch (tone) { + case "secondary": + return styles.chartAreaSecondary; + case "warn": + return styles.chartAreaWarn; + case "danger": + return styles.chartAreaDanger; + default: + return styles.chartAreaPrimary; + } +} + +function dotClass(tone: ChartSeriesConfig["tone"]): string | undefined { + switch (tone) { + case "secondary": + return styles.chartDotSecondary; + case "warn": + return styles.chartDotWarn; + case "danger": + return styles.chartDotDanger; + default: + return styles.chartDotPrimary; + } +} + +function MetricChartCard({ + title, + primaryValue, + primaryLevel = "normal", + subText, + legend, + points, + series, + ticks, + formatTick, + referenceLine, + activeIndex, + onHoverIndex, +}: MetricChartCardProps) { + const txFn = useTx(); + const plotHostRef = useRef(null); + const [size, setSize] = useState({ w: 300, h: 80 }); + + useLayoutEffect(() => { + const el = plotHostRef.current; + if (!el) return; + const measure = () => { + const w = el.clientWidth; + const h = el.clientHeight; + if (w > 0 && h > 0) setSize({ w, h }); + }; + measure(); + if (typeof ResizeObserver === "undefined") return; + const ro = new ResizeObserver(measure); + ro.observe(el); + return () => ro.disconnect(); + }, []); + + const plotW = Math.max(1, size.w - PLOT_PAD.left - PLOT_PAD.right); + const plotH = Math.max(1, size.h - PLOT_PAD.top - PLOT_PAD.bottom); + const baselineY = PLOT_PAD.top + plotH; + const maxTick = ticks[ticks.length - 1] ?? 1; + + const xMin = points.length > 0 ? points[0]!.sample.timestampMs : 0; + const xMax = points.length >= 2 ? Math.max(points[points.length - 1]!.sample.timestampMs, xMin + 1000) : xMin + 1000; + + const xAtIndex = useCallback( + (idx: number): number => { + if (points.length <= 1) return PLOT_PAD.left + plotW; + const ts = points[idx]!.sample.timestampMs; + return PLOT_PAD.left + ((ts - xMin) / (xMax - xMin)) * plotW; + }, + [points, plotW, xMin, xMax], + ); + + const yAtValue = useCallback( + (v: number): number => { + const ratio = maxTick > 0 ? Math.min(1, Math.max(0, v / maxTick)) : 0; + return PLOT_PAD.top + plotH * (1 - ratio); + }, + [maxTick, plotH], + ); + + const renderedSeries = useMemo( + () => + series.map((s) => ({ + config: s, + paths: buildSegmentedPaths( + points.map((pt, idx) => { + const val = s.values[idx] ?? null; + return { + x: xAtIndex(idx), + y: val !== null && Number.isFinite(val) ? yAtValue(val) : null, + gapBefore: pt.gapBefore, + }; + }), + baselineY, + ), + })), + [series, points, xAtIndex, yAtValue, baselineY], + ); + + const xLabels = useMemo(() => { + if (points.length === 0) return []; + const spanMs = xMax - xMin; + if (points.length === 1 || spanMs < 1000) { + return [ + { + x: PLOT_PAD.left + plotW, + text: formatLocalClock(points[points.length - 1]!.sample.timestampMs), + anchor: "end" as const, + }, + ]; + } + const maxSlots = plotW >= 320 ? 4 : 3; + const distinctSeconds = Math.max(1, Math.floor(spanMs / 1000)); + const tickCount = Math.min(maxSlots, distinctSeconds + 1); + const out: Array<{ x: number; text: string; anchor: "start" | "middle" | "end" }> = []; + for (let i = 0; i < tickCount; i++) { + const ratio = tickCount === 1 ? 1 : i / (tickCount - 1); + const ts = Math.round(xMin + ratio * spanMs); + const text = formatLocalClock(ts); + if (out.length > 0 && out[out.length - 1]!.text === text) continue; + const anchor = i === 0 ? "start" : i === tickCount - 1 ? "end" : "middle"; + out.push({ x: PLOT_PAD.left + ratio * plotW, text, anchor }); + } + return out; + }, [points, plotW, xMin, xMax]); + + const handlePointerMove = (e: PointerEvent) => { + if (!points.length) return; + const rect = e.currentTarget.getBoundingClientRect(); + const px = e.clientX - rect.left; + if (px < PLOT_PAD.left - 4 || px > PLOT_PAD.left + plotW + 4) { + onHoverIndex(null); + return; + } + if (points.length === 1) { + onHoverIndex(0); + return; + } + const ratio = Math.min(1, Math.max(0, (px - PLOT_PAD.left) / plotW)); + const targetTs = xMin + ratio * (xMax - xMin); + // Binary search nearest point by timestamp. + let lo = 0; + let hi = points.length - 1; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (points[mid]!.sample.timestampMs < targetTs) lo = mid + 1; + else hi = mid; + } + let best = lo; + if (lo > 0) { + const dPrev = Math.abs(points[lo - 1]!.sample.timestampMs - targetTs); + const dCurr = Math.abs(points[lo]!.sample.timestampMs - targetTs); + if (dPrev < dCurr) best = lo - 1; + } + onHoverIndex(best); + }; + + const showRefLine = + referenceLine && + Number.isFinite(referenceLine.value) && + referenceLine.value > 0 && + referenceLine.value <= maxTick * 1.001; + const refY = showRefLine ? yAtValue(referenceLine.value) : 0; + + const crosshairX = + activeIndex !== null && activeIndex >= 0 && activeIndex < points.length ? xAtIndex(activeIndex) : null; + + return ( +
+
+ {txFn(title)} + + {primaryValue} + +
+
+ + {subText ?? "\u00A0"} + + {legend && legend.length > 0 && ( +
+ +
+ {points.length === 0 ? ( +
+ Collecting samples… +
+ ) : ( + onHoverIndex(null)} + > + {ticks.map((tickVal) => { + const y = yAtValue(tickVal); + return ( + + + + {formatTick(tickVal)} + + + ); + })} + + {showRefLine && ( + + + + {referenceLine.label} + + + )} + + {renderedSeries.map(({ config, paths }) => ( + + {config.fill && paths.area && } + {paths.line && ( + + )} + {paths.isolated.map((pt, i) => ( + // oxlint-disable-next-line react/no-array-index-key -- isolated single-sample coordinates + + ))} + + ))} + + {crosshairX !== null && activeIndex !== null && ( + + + {series.map((s) => { + const val = s.values[activeIndex] ?? null; + if (val === null || !Number.isFinite(val)) return null; + return ( + + ); + })} + + )} + + {xLabels.map((lbl, idx) => ( + + {lbl.text} + + ))} + + )} +
+
+ ); +} + +export interface ContainerStatsChartsProps { + samples: readonly StatsSample[]; + running: boolean; + paused: boolean; + statsLoading: boolean; + onTogglePause: () => void; + onClear: () => void; + cpuLimit: number | null; + cpuLimitText: string | null; + vmCpuText: string | null; + memoryLimitBytes: number | null; + memLimitText: string | null; + vmMemText: string | null; + sourceLabel: string | null; + extraBannerActions?: React.ReactNode; +} + +/** + * Renders the `Resource Usage` section banner with inline chart controls plus the + * responsive 2×2 synchronized metrics grid (CPU, Memory, Disk I/O, Network I/O). + */ +export function ContainerStatsCharts({ + samples, + running, + paused, + statsLoading, + onTogglePause, + onClear, + cpuLimit, + cpuLimitText, + vmCpuText, + memoryLimitBytes, + memLimitText, + vmMemText, + sourceLabel, + extraBannerActions, +}: ContainerStatsChartsProps) { + const txFn = useTx(); + const timeWindow = useContainerStatsStore((s) => s.timeWindow); + const ioMode = useContainerStatsStore((s) => s.ioMode); + const memoryScale = useContainerStatsStore((s) => s.memoryScale); + + const [hoverIndex, setHoverIndex] = useState(null); + const [keyboardIndex, setKeyboardIndex] = useState(null); + + const { points } = useMemo(() => deriveStatsSeries(samples, TIME_WINDOW_MS[timeWindow]), [samples, timeWindow]); + + const rawActiveIndex = hoverIndex ?? keyboardIndex; + const activeIndex = + rawActiveIndex !== null && rawActiveIndex >= 0 && rawActiveIndex < points.length ? rawActiveIndex : null; + const displayPoint = activeIndex !== null ? points[activeIndex]! : (points[points.length - 1] ?? null); + const displaySample = displayPoint?.sample ?? null; + + const effectiveMemLimit = + memoryLimitBytes && memoryLimitBytes > 0 + ? memoryLimitBytes + : displaySample && displaySample.memLimitBytes > 0 + ? displaySample.memLimitBytes + : 0; + const hasMemoryLimit = effectiveMemLimit > 0; + + // CPU series & scaling + const cpuValues = useMemo(() => points.map((p) => p.sample.cpuPercent), [points]); + const cpuSummary = useMemo(() => summarizeValues(cpuValues), [cpuValues]); + const cpuCapPct = cpuLimit && cpuLimit > 0 ? cpuLimit * 100 : null; + const cpuCeiling = useMemo(() => { + const peak = cpuSummary.peak ?? 0; + let ceil = Math.max(MIN_CPU_CEILING, peak * 1.15); + if (cpuCapPct && peak >= cpuCapPct * 0.6) ceil = Math.max(ceil, cpuCapPct); + return ceil; + }, [cpuSummary.peak, cpuCapPct]); + const cpuTicks = useMemo(() => niceAxisTicks(cpuCeiling, 3, 10), [cpuCeiling]); + const cpuPressureRatio = displaySample + ? cpuCapPct + ? (displaySample.cpuPercent / cpuCapPct) * 100 + : displaySample.onlineCpus + ? (displaySample.cpuPercent / (displaySample.onlineCpus * 100)) * 100 + : displaySample.cpuPercent + : 0; + const cpuLevel = pressureForRatio(cpuPressureRatio); + const cpuValueText = displaySample + ? (displaySample.raw?.cpuPerc ?? formatPercentCompact(displaySample.cpuPercent)) + : "—"; + const cpuLimitMeta = cpuLimitText + ? tx`Limit: ${cpuLimitText}` + : vmCpuText + ? tx`Unlimited (Docker VM: ${vmCpuText})` + : null; + const cpuSubParts: string[] = []; + if (cpuSummary.peak !== null && cpuSummary.avg !== null && points.length >= 2) { + const peak = formatPercentCompact(cpuSummary.peak); + const avg = formatPercentCompact(cpuSummary.avg); + cpuSubParts.push(tx`Peak ${peak} · Avg ${avg}`); + } + if (cpuLimitMeta) cpuSubParts.push(cpuLimitMeta); + const cpuSubText = cpuSubParts.length > 0 ? cpuSubParts.join(" · ") : null; + + // Memory series & smart Auto vs Limit scaling + const memValues = useMemo(() => points.map((p) => p.sample.memUsedBytes), [points]); + const memSummary = useMemo(() => summarizeValues(memValues), [memValues]); + const memCeiling = useMemo(() => { + const peak = memSummary.peak ?? 0; + if (effectiveMemLimit > 0 && (memoryScale === "limit" || peak >= effectiveMemLimit * 0.6)) { + return Math.max(effectiveMemLimit, peak); + } + return Math.max(MIN_MEM_CEILING, peak * 1.25); + }, [memSummary.peak, effectiveMemLimit, memoryScale]); + const memTicks = useMemo(() => niceAxisTicks(memCeiling, 3, 1024), [memCeiling]); + const memRatio = displaySample + ? effectiveMemLimit > 0 + ? (displaySample.memUsedBytes / effectiveMemLimit) * 100 + : displaySample.memPercent + : 0; + const memLevel = pressureForRatio(memRatio); + const memValueText = displaySample + ? displaySample.raw?.memUsage + ? `${displaySample.raw.memUsage} (${displaySample.raw.memPerc})` + : effectiveMemLimit > 0 + ? `${formatBinaryBytes(displaySample.memUsedBytes)} / ${formatBinaryBytes(effectiveMemLimit)} (${formatPercentCompact(memRatio)})` + : formatBinaryBytes(displaySample.memUsedBytes) + : "—"; + const memLimitMeta = + memLimitText && sourceLabel + ? tx`Limit: ${memLimitText} · ${sourceLabel}` + : memLimitText + ? tx`Limit: ${memLimitText}` + : vmMemText + ? tx`Docker VM: ${vmMemText}` + : null; + const memSubParts: string[] = []; + if (memSummary.peak !== null && points.length >= 2) { + const peak = formatBinaryBytes(memSummary.peak); + memSubParts.push(tx`Peak ${peak}`); + } + if (memLimitMeta) memSubParts.push(memLimitMeta); + const memSubText = memSubParts.length > 0 ? memSubParts.join(" · ") : null; + + // Disk I/O series (Rate B/s or Cumulative bytes) + const diskReadValues = useMemo( + () => points.map((p) => (ioMode === "rate" ? p.diskReadRate : p.sample.diskReadBytes)), + [points, ioMode], + ); + const diskWriteValues = useMemo( + () => points.map((p) => (ioMode === "rate" ? p.diskWriteRate : p.sample.diskWriteBytes)), + [points, ioMode], + ); + const diskPeak = useMemo(() => { + const r = summarizeValues(diskReadValues).peak ?? 0; + const w = summarizeValues(diskWriteValues).peak ?? 0; + return Math.max(r, w); + }, [diskReadValues, diskWriteValues]); + const diskCeiling = + ioMode === "rate" ? Math.max(MIN_IO_RATE_CEILING, diskPeak * 1.2) : Math.max(MIN_IO_TOTAL_CEILING, diskPeak * 1.15); + const diskTicks = useMemo(() => niceAxisTicks(diskCeiling, 3, 1000), [diskCeiling]); + const diskTotalStr = displaySample + ? (displaySample.raw?.blockIo ?? + `${formatDecimalBytes(displaySample.diskReadBytes)} / ${formatDecimalBytes(displaySample.diskWriteBytes)}`) + : null; + const hasDiskRates = + displayPoint !== null && (displayPoint.diskReadRate !== null || displayPoint.diskWriteRate !== null); + const diskRateStr = hasDiskRates + ? `R ${formatThroughputRate(displayPoint.diskReadRate)} · W ${formatThroughputRate(displayPoint.diskWriteRate)}` + : null; + const diskValueText = ioMode === "rate" ? (diskRateStr ?? diskTotalStr ?? "—") : (diskTotalStr ?? "—"); + const formatTotalMeta = (total: string) => tx`Total ${total}`; + const diskSubText = ioMode === "rate" ? (diskTotalStr ? formatTotalMeta(diskTotalStr) : null) : diskRateStr; + + // Network I/O series (Rate B/s or Cumulative bytes) + const netRxValues = useMemo( + () => points.map((p) => (ioMode === "rate" ? p.netRxRate : p.sample.netRxBytes)), + [points, ioMode], + ); + const netTxValues = useMemo( + () => points.map((p) => (ioMode === "rate" ? p.netTxRate : p.sample.netTxBytes)), + [points, ioMode], + ); + const netPeak = useMemo(() => { + const rx = summarizeValues(netRxValues).peak ?? 0; + const txVal = summarizeValues(netTxValues).peak ?? 0; + return Math.max(rx, txVal); + }, [netRxValues, netTxValues]); + const netCeiling = + ioMode === "rate" ? Math.max(MIN_IO_RATE_CEILING, netPeak * 1.2) : Math.max(MIN_IO_TOTAL_CEILING, netPeak * 1.15); + const netTicks = useMemo(() => niceAxisTicks(netCeiling, 3, 1000), [netCeiling]); + const netTotalStr = displaySample + ? (displaySample.raw?.netIo ?? + `${formatDecimalBytes(displaySample.netRxBytes)} / ${formatDecimalBytes(displaySample.netTxBytes)}`) + : null; + const hasNetRates = displayPoint !== null && (displayPoint.netRxRate !== null || displayPoint.netTxRate !== null); + const netRateStr = hasNetRates + ? `↓ ${formatThroughputRate(displayPoint.netRxRate)} · ↑ ${formatThroughputRate(displayPoint.netTxRate)}` + : null; + const netValueText = ioMode === "rate" ? (netRateStr ?? netTotalStr ?? "—") : (netTotalStr ?? "—"); + const netSubText = ioMode === "rate" ? (netTotalStr ? formatTotalMeta(netTotalStr) : null) : netRateStr; + + const handleGridKeyDown = (e: KeyboardEvent) => { + if (e.key === " " && running) { + e.preventDefault(); + onTogglePause(); + return; + } + if (!points.length) return; + if (e.key === "Escape") { + setKeyboardIndex(null); + setHoverIndex(null); + return; + } + if (e.key === "ArrowLeft") { + e.preventDefault(); + setKeyboardIndex((prev) => { + const base = prev ?? points.length - 1; + return Math.max(0, base - 1); + }); + } else if (e.key === "ArrowRight") { + e.preventDefault(); + setKeyboardIndex((prev) => { + if (prev === null) return points.length - 1; + return Math.min(points.length - 1, prev + 1); + }); + } else if (e.key === "Home") { + e.preventDefault(); + setKeyboardIndex(0); + } else if (e.key === "End") { + e.preventDefault(); + setKeyboardIndex(points.length - 1); + } + }; + + const scrubbedClock = activeIndex !== null && displaySample ? formatLocalClock(displaySample.timestampMs) : null; + const pids = displaySample + ? displaySample.raw?.pids || (displaySample.pids > 0 ? String(displaySample.pids) : null) + : null; + + const statusTone = !running ? styles.dotMuted : paused ? styles.dotWarn : styles.dotOk; + + const cpuTone: ChartSeriesConfig["tone"] = + cpuLevel === "danger" ? "danger" : cpuLevel === "warn" ? "warn" : "primary"; + const memTone: ChartSeriesConfig["tone"] = + memLevel === "danger" ? "danger" : memLevel === "warn" ? "warn" : "primary"; + + return ( + <> +
+ + + Resource Usage + + + + {pids && {tx`PIDs ${pids}`}} + {scrubbedClock && ( + + {scrubbedClock} + + )} + + + + + + {hasMemoryLimit && ( + + )} + {running && ( + + )} + { + setHoverIndex(null); + setKeyboardIndex(null); + onClear(); + }} + /> + {extraBannerActions} + +
+ + {running && statsLoading && samples.length === 0 ? ( +
+ Loading… +
+ ) : running && samples.length === 0 ? ( +
+ Metrics unavailable +
+ ) : ( +
setKeyboardIndex(null)} + > +
+ `${Number(v.toFixed(1))}%`} + referenceLine={cpuCapPct ? { value: cpuCapPct, label: txFn("Limit"), level: cpuLevel } : null} + activeIndex={activeIndex} + onHoverIndex={setHoverIndex} + /> + + 0 ? { value: effectiveMemLimit, label: txFn("Limit"), level: memLevel } : null + } + activeIndex={activeIndex} + onHoverIndex={setHoverIndex} + /> + + + + +
+
+ )} + + ); +} diff --git a/src/features/services/Services.module.css b/src/features/services/Services.module.css index eb5f037225..9ad219b3aa 100644 --- a/src/features/services/Services.module.css +++ b/src/features/services/Services.module.css @@ -697,3 +697,262 @@ button.entityChip:not(:disabled):hover { color: var(--warning); font-size: var(--fs-small); } + +/* Container live metrics 2×2 grid inside Dashboard › Resource Usage */ +.resourceBanner { + flex-wrap: wrap; + row-gap: var(--space-1); + column-gap: var(--space-2); +} +.resourceBannerLeft { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-1-5); + min-width: 0; +} +.resourceBannerControls { + display: inline-flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-1-5); +} +.statsStatusBadge { + display: inline-flex; + align-items: center; + gap: var(--space-1); + font-size: var(--fs-tiny); + font-weight: 400; + color: var(--fg-muted); +} +.dotWarn { + background: var(--warning); +} +.statsScrubTime { + padding: 0 5px; + border-radius: var(--radius-small); + background: var(--bg-app); + border: 1px solid var(--border); + font-family: var(--font-mono); + font-size: var(--fs-tiny); + font-weight: 400; + color: var(--fg-strong); + font-variant-numeric: tabular-nums; +} +.statsSegmented > button { + min-height: 20px; + padding: 0 var(--space-1-5); + font-size: var(--fs-tiny); + font-weight: 400; +} +:global([data-compact]) .statsSegmented > button { + min-height: 18px; + padding: 0 var(--space-1); +} +.statsGridWrap { + container-type: inline-size; + padding: var(--space-2) var(--space-3); + border-bottom: 1px solid var(--border); +} +.statsGridWrap:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: -2px; +} +.statsGrid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: var(--space-2); +} +@container (min-width: 520px) { + .statsGrid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} +.statsCard { + display: flex; + flex-direction: column; + gap: var(--space-0-5); + min-width: 0; + padding: 7px 10px 6px; + border-radius: var(--radius-control); + background: var(--bg-elev); + border: 1px solid var(--border); +} +.statsCardTop { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-2); + min-width: 0; +} +.statsCardTitle { + flex: none; + font-size: var(--fs-small); + font-weight: 600; + color: var(--fg-secondary); +} +.statsCardValue { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--font-mono); + font-size: var(--fs-small); + color: var(--fg-strong); + font-variant-numeric: tabular-nums; +} +.statsValueWarn { + color: var(--warning); +} +.statsValueDanger { + color: var(--danger); +} +.statsCardSub { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + min-width: 0; + font-size: var(--fs-tiny); + color: var(--fg-muted); + font-variant-numeric: tabular-nums; +} +.statsCardMeta { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.statsLegend { + display: inline-flex; + align-items: center; + gap: var(--space-2); + flex: none; +} +.statsLegendItem { + display: inline-flex; + align-items: center; + gap: var(--space-1); + color: var(--fg-muted); +} +.statsLegendSwatch { + width: 14px; + height: 2px; + border-radius: 1px; + background: var(--info); +} +.swatchPrimary { + background: var(--info); +} +.swatchSecondary { + background: var(--chart-series-secondary); +} +.swatchDashed { + background: repeating-linear-gradient(to right, var(--chart-series-secondary) 0 4px, transparent 4px 6.5px); +} +.statsPlotHost { + position: relative; + width: 100%; + height: 82px; + margin-top: var(--space-0-5); +} +:global([data-compact]) .statsPlotHost { + height: 68px; +} +.statsEmptyPlot { + display: flex; + align-items: center; + justify-content: center; + height: 100%; + color: var(--fg-subtle); + font-size: var(--fs-tiny); +} +.statsSvg { + display: block; + width: 100%; + height: 100%; + overflow: visible; + cursor: crosshair; +} +.chartGridLine { + stroke: var(--border); + stroke-width: 1; +} +.chartAxisLabel { + fill: var(--fg-subtle); + font-family: var(--font-mono); + font-size: var(--fs-tiny); + font-variant-numeric: tabular-nums; +} +.chartRefLine { + stroke: var(--fg-subtle); + stroke-width: 1; + stroke-dasharray: 3 3; +} +.chartRefWarn { + stroke: var(--warning); +} +.chartRefDanger { + stroke: var(--danger); +} +.chartRefLabel { + fill: var(--fg-subtle); + font-family: var(--font-ui); + font-size: var(--fs-tiny); +} +.chartStroke { + fill: none; + stroke-width: 1.5; + stroke-linecap: round; + stroke-linejoin: round; +} +.chartStrokeDashed { + stroke-dasharray: 4 2.5; +} +.chartStrokePrimary { + stroke: var(--info); +} +.chartStrokeSecondary { + stroke: var(--chart-series-secondary); +} +.chartStrokeWarn { + stroke: var(--warning); +} +.chartStrokeDanger { + stroke: var(--danger); +} +.chartAreaPrimary { + fill: color-mix(in srgb, var(--info) 15%, transparent); +} +.chartAreaSecondary { + fill: color-mix(in srgb, var(--chart-series-secondary) 12%, transparent); +} +.chartAreaWarn { + fill: color-mix(in srgb, var(--warning) 18%, transparent); +} +.chartAreaDanger { + fill: color-mix(in srgb, var(--danger) 20%, transparent); +} +.chartDotPrimary { + fill: var(--info); +} +.chartDotSecondary { + fill: var(--chart-series-secondary); +} +.chartDotWarn { + fill: var(--warning); +} +.chartDotDanger { + fill: var(--danger); +} +.chartCrosshair { + stroke: var(--fg-muted); + stroke-width: 1; + stroke-dasharray: 2 2; + pointer-events: none; +} +.chartCrosshairDot { + stroke: var(--bg-elev); + stroke-width: 1.5; + pointer-events: none; +} diff --git a/src/features/services/containerResources.tsx b/src/features/services/containerResources.tsx index 19fe7fed7d..6dacf52eef 100644 --- a/src/features/services/containerResources.tsx +++ b/src/features/services/containerResources.tsx @@ -5,17 +5,10 @@ * Designed so follow-up limit-editing flows (`#7468` Change Limits…) can plug actions * into `extraLimitActions` without rewriting the dashboard layout. */ -import { useEffect, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { tx } from "@/platform/i18n"; -import { - call, - commands, - isTauri, - type DevContainerResourceStatus, - type DockerContainer, - type DockerContainerStats, -} from "@/platform/ipc"; -import { Button, Icon, Spinner, T } from "@/ui"; +import { call, commands, isTauri, type DevContainerResourceStatus, type DockerContainer } from "@/platform/ipc"; +import { Button, Icon, T } from "@/ui"; import { formatCpuLimit, formatMemoryLimit, @@ -25,6 +18,8 @@ import { resolveDevContainerLimits, type DevContainerLimitAction, } from "@/workbench/devcontainerResources"; +import { ContainerStatsCharts } from "./ContainerStatsCharts"; +import { sampleFromLegacyStats, type StatsSample } from "./containerStats"; import { isDevContainer } from "./model"; import { endpointOf } from "./store"; import styles from "./Services.module.css"; @@ -139,31 +134,33 @@ export function ContainerOomBanner({ export interface ContainerResourcesSectionProps { container: DockerContainer; running: boolean; - stats: DockerContainerStats | null; + samples: readonly StatsSample[]; statsLoading: boolean; + paused: boolean; + onTogglePause: () => void; + onClearHistory: () => void; inspect: ContainerInspectLimits | null; devStatus: DevContainerResourceStatus | null; - cpuPercent: number; - memoryPercent: number; extraLimitActions?: ReadonlyArray; - renderProgress: (percent: number) => React.ReactNode; } /** - * Renders live CPU & memory usage next to effective limits (and configured limits / - * `hostRequirements` for dev containers, even while stopped). + * Renders live 2×2 resource charts (CPU, Memory, Disk I/O, Network I/O) with effective + * limits while running or when session history was recorded, and falls back to compact + * `Resource Limits` rows for stopped containers that carry configured limits or + * dev container `hostRequirements`. */ export function ContainerResourcesSection({ container, running, - stats, + samples, statsLoading, + paused, + onTogglePause, + onClearHistory, inspect, devStatus, - cpuPercent, - memoryPercent, extraLimitActions, - renderProgress, }: ContainerResourcesSectionProps) { const isDev = isDevContainer(container); const resolved = resolveDevContainerLimits(devStatus); @@ -184,170 +181,125 @@ export function ContainerResourcesSection({ const shortfalls = devStatus?.hostRequirements.shortfalls ?? []; const hasLimits = cpuLimit !== null || memoryLimitBytes !== null || isDev; - if (!running && !hasLimits) return null; + const devUsage = devStatus?.usage ?? null; + const effectiveSamples = useMemo(() => { + if (samples.length > 0) return samples; + if (running && devUsage) { + return [sampleFromLegacyStats(devUsage, 0)]; + } + return samples; + }, [samples, running, devUsage]); - const effectiveStats = stats ?? (running ? (devStatus?.usage ?? null) : null); - // `docker stats` CPU% can exceed 100% on multi-core containers; scale bar against the CPU limit when set. - const scaledCpuPercent = cpuLimit && cpuLimit > 0 ? Math.min(100, cpuPercent / cpuLimit) : cpuPercent; + const showCharts = running || effectiveSamples.length > 0; + if (!showCharts && !hasLimits) return null; + + const limitActionButtons = ( + <> + {configPath && ( + + )} + {extraLimitActions?.map((action) => ( + + ))} + + ); + + const requirementsRow = req && ( +
+
+
+ Host requirements +
+
+
+ + {[ + formatCpuLimit(req.cpus), + req.memoryBytes ? tx`${formatMemoryLimit(req.memoryBytes)} RAM` : null, + req.storageBytes ? tx`${formatMemoryLimit(req.storageBytes)} storage` : null, + ] + .filter(Boolean) + .join(" · ")} + + {shortfalls.map((s) => ( + + {s.message} + + ))} +
+
+
+
+ ); + + if (showCharts) { + return ( + <> + + {requirementsRow} + + ); + } return ( <>
- {running ? Resource Usage : Resource Limits} - - {configPath && ( - - )} - {extraLimitActions?.map((action) => ( - - ))} + + Resource Limits + {limitActionButtons}
- {running && !effectiveStats && statsLoading && !hasLimits ? ( -
- Loading… -
- ) : running && !effectiveStats && !hasLimits ? ( -
- Metrics unavailable -
- ) : ( -
-
-
- CPU -
-
- {running && effectiveStats ? ( -
- - {effectiveStats.cpuPerc} - {cpuLimitText ? ( - {tx`Limit: ${cpuLimitText}`} - ) : vmCpuText ? ( - {tx`Unlimited (Docker VM: ${vmCpuText})`} - ) : null} - - {renderProgress(scaledCpuPercent)} -
- ) : running && statsLoading ? ( - - Loading… - {cpuLimitText && {tx`Limit: ${cpuLimitText}`}} - - ) : ( - - - {cpuLimitText ?? (vmCpuText ? tx`Unlimited (Docker VM: ${vmCpuText})` : tx("Unlimited"))} - - {sourceLabel && cpuLimitText && {sourceLabel}} - - )} -
+
+
+
+ CPU
- -
-
- Memory -
-
- {running && effectiveStats ? ( -
- - - {effectiveStats.memUsage} ({effectiveStats.memPerc}) - - {memLimitText && sourceLabel ? ( - {tx`Limit: ${memLimitText} · ${sourceLabel}`} - ) : memLimitText ? ( - {tx`Limit: ${memLimitText}`} - ) : vmMemText ? ( - {tx`Docker VM: ${vmMemText}`} - ) : null} - - {renderProgress(memoryPercent)} -
- ) : running && statsLoading ? ( - - Loading… - {memLimitText && {tx`Limit: ${memLimitText}`}} - - ) : ( - - - {memLimitText ?? (vmMemText ? tx`Unlimited (Docker VM: ${vmMemText})` : tx("Unlimited"))} - - {sourceLabel && memLimitText && {sourceLabel}} - - )} -
+
+ + + {cpuLimitText ?? (vmCpuText ? tx`Unlimited (Docker VM: ${vmCpuText})` : tx("Unlimited"))} + + {sourceLabel && cpuLimitText && {sourceLabel}} +
- - {running && effectiveStats?.netIo && ( -
-
- Network I/O -
-
- {effectiveStats.netIo} -
-
- )} - - {running && effectiveStats?.blockIo && ( -
-
- Block I/O -
-
- {effectiveStats.blockIo} -
-
- )} - - {running && effectiveStats?.pids && ( -
-
- PIDs -
-
- {effectiveStats.pids} -
-
- )} - - {req && ( -
-
- Host requirements -
-
-
- - {[ - formatCpuLimit(req.cpus), - req.memoryBytes ? tx`${formatMemoryLimit(req.memoryBytes)} RAM` : null, - req.storageBytes ? tx`${formatMemoryLimit(req.storageBytes)} storage` : null, - ] - .filter(Boolean) - .join(" · ")} - - {shortfalls.map((s) => ( - - {s.message} - - ))} -
-
-
- )}
- )} + +
+
+ Memory +
+
+ + + {memLimitText ?? (vmMemText ? tx`Unlimited (Docker VM: ${vmMemText})` : tx("Unlimited"))} + + {sourceLabel && memLimitText && {sourceLabel}} + +
+
+
+ + {requirementsRow} ); } diff --git a/src/features/services/containerStats.test.ts b/src/features/services/containerStats.test.ts new file mode 100644 index 0000000000..0d2fd8889a --- /dev/null +++ b/src/features/services/containerStats.test.ts @@ -0,0 +1,199 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + buildSegmentedPaths, + clearContainerStatsHistory, + containerStatsScope, + deriveStatsSeries, + formatBinaryBytes, + formatDecimalBytes, + formatThroughputRate, + MAX_CONTAINER_STATS_SAMPLES, + MAX_TRACKED_CONTAINERS, + niceAxisTicks, + pushContainerStatsSample, + resetContainerStatsStore, + sampleFromLegacyStats, + useContainerStatsStore, + type StatsSample, +} from "./containerStats"; + +function makeSample(overrides: Partial = {}): StatsSample { + return { + timestampMs: 1_700_000_000_000, + cpuPercent: 12.5, + onlineCpus: 4, + memUsedBytes: 512 * 1024 * 1024, + memLimitBytes: 4 * 1024 ** 3, + memPercent: 12.5, + netRxBytes: 1_000_000, + netTxBytes: 500_000, + diskReadBytes: 2_000_000, + diskWriteBytes: 4_000_000, + pids: 12, + approximateIo: false, + ...overrides, + }; +} + +beforeEach(() => { + resetContainerStatsStore(); +}); + +describe("container stats ring buffer store", () => { + it("caps per-container history, rejects out-of-order timestamps, and LRU-evicts old containers", () => { + const scope = containerStatsScope("default", "c1"); + for (let i = 0; i < MAX_CONTAINER_STATS_SAMPLES + 25; i++) { + pushContainerStatsSample(scope, makeSample({ timestampMs: 1_700_000_000_000 + i * 1000 })); + } + const retained = useContainerStatsStore.getState().byScope[scope]!; + expect(retained).toHaveLength(MAX_CONTAINER_STATS_SAMPLES); + expect(retained[0]!.timestampMs).toBe(1_700_000_000_000 + 25_000); + + // Duplicate / older timestamps are ignored. + pushContainerStatsSample(scope, makeSample({ timestampMs: retained.at(-1)!.timestampMs })); + pushContainerStatsSample(scope, makeSample({ timestampMs: retained.at(-1)!.timestampMs - 500 })); + expect(useContainerStatsStore.getState().byScope[scope]).toHaveLength(MAX_CONTAINER_STATS_SAMPLES); + + // Exceeding MAX_TRACKED_CONTAINERS evicts the least recently updated scope. + for (let c = 2; c <= MAX_TRACKED_CONTAINERS + 2; c++) { + pushContainerStatsSample(containerStatsScope("default", `c${c}`), makeSample({ timestampMs: 1000 })); + } + const keys = Object.keys(useContainerStatsStore.getState().byScope); + expect(keys).toHaveLength(MAX_TRACKED_CONTAINERS); + expect(keys).not.toContain(scope); + + clearContainerStatsHistory(containerStatsScope("default", `c${MAX_TRACKED_CONTAINERS + 2}`)); + expect(Object.keys(useContainerStatsStore.getState().byScope)).toHaveLength(MAX_TRACKED_CONTAINERS - 1); + }); +}); + +describe("deriveStatsSeries", () => { + it("derives throughput rates, breaks across downtime gaps, and nulls counter resets", () => { + const t0 = 1_700_000_000_000; + const samples: StatsSample[] = [ + makeSample({ timestampMs: t0, diskReadBytes: 1000, diskWriteBytes: 2000, netRxBytes: 500, netTxBytes: 100 }), + makeSample({ + timestampMs: t0 + 2000, + diskReadBytes: 5000, + diskWriteBytes: 12000, + netRxBytes: 2500, + netTxBytes: 500, + }), + // 30s downtime gap (> 15s) and counter reset after container restart. + makeSample({ + timestampMs: t0 + 32_000, + diskReadBytes: 200, + diskWriteBytes: 400, + netRxBytes: 100, + netTxBytes: 50, + }), + makeSample({ + timestampMs: t0 + 33_000, + diskReadBytes: 1200, + diskWriteBytes: 2400, + netRxBytes: 600, + netTxBytes: 150, + }), + ]; + + const { points } = deriveStatsSeries(samples, 60_000); + expect(points).toHaveLength(4); + expect(points[0]!.diskReadRate).toBeNull(); + expect(points[0]!.gapBefore).toBe(false); + + expect(points[1]!.diskReadRate).toBe(2000); + expect(points[1]!.diskWriteRate).toBe(5000); + expect(points[1]!.netRxRate).toBe(1000); + expect(points[1]!.netTxRate).toBe(200); + expect(points[1]!.gapBefore).toBe(false); + + // Downtime gap breaks the line and nulls rates. + expect(points[2]!.gapBefore).toBe(true); + expect(points[2]!.diskReadRate).toBeNull(); + expect(points[2]!.netRxRate).toBeNull(); + + // Post-restart rate resumes cleanly from the new baseline. + expect(points[3]!.gapBefore).toBe(false); + expect(points[3]!.diskReadRate).toBe(1000); + expect(points[3]!.diskWriteRate).toBe(2000); + expect(points[3]!.netRxRate).toBe(500); + expect(points[3]!.netTxRate).toBe(100); + }); + + it("anchors window to latest sample and computes rate for first visible point using preceding sample", () => { + const t0 = 1_700_000_000_000; + const samples: StatsSample[] = [ + makeSample({ timestampMs: t0, netRxBytes: 0 }), + makeSample({ timestampMs: t0 + 59_000, netRxBytes: 59_000 }), + makeSample({ timestampMs: t0 + 60_000, netRxBytes: 61_000 }), + makeSample({ timestampMs: t0 + 120_000, netRxBytes: 121_000 }), + ]; + const { points } = deriveStatsSeries(samples, 60_000); + expect(points.map((p) => p.sample.timestampMs)).toEqual([t0 + 60_000, t0 + 120_000]); + // Preceding sample at t0+59s (1s earlier) yields 2000 B/s for the first visible point at t0+60s. + expect(points[0]!.netRxRate).toBe(2000); + }); + + it("converts legacy CLI stats strings into structured samples", () => { + const s = sampleFromLegacyStats( + { + cpuPerc: "40.00%", + memUsage: "1.5GiB / 4GiB", + memPerc: "37.50%", + netIo: "281MB / 1.2MB", + blockIo: "274MB / 11.4GB", + pids: "17", + }, + 1234, + ); + expect(s.cpuPercent).toBe(40); + expect(s.memUsedBytes).toBe(1.5 * 1024 ** 3); + expect(s.memLimitBytes).toBe(4 * 1024 ** 3); + expect(s.netRxBytes).toBe(281_000_000); + expect(s.diskWriteBytes).toBe(11_400_000_000); + expect(s.pids).toBe(17); + expect(s.approximateIo).toBe(true); + }); +}); + +describe("axis ticks, formatting and segmented SVG paths", () => { + it("produces clean human-readable decimal and IEC binary ticks", () => { + expect(niceAxisTicks(20, 3, 10)).toEqual([0, 10, 20]); + expect(niceAxisTicks(95, 3, 10)).toEqual([0, 50, 100]); + // 1.1 GiB -> binary steps in GiB or MiB without awkward fractional GiB ticks. + const memTicks = niceAxisTicks(900 * 1024 ** 2, 3, 1024); + expect(memTicks[0]).toBe(0); + expect(memTicks.at(-1)!).toBeGreaterThanOrEqual(900 * 1024 ** 2); + expect(memTicks[1]! % 1024 ** 2).toBe(0); + }); + + it("formats binary bytes, decimal bytes, and throughput rates", () => { + expect(formatBinaryBytes(0)).toBe("0 B"); + expect(formatBinaryBytes(512 * 1024 ** 2)).toBe("512 MiB"); + expect(formatBinaryBytes(891.8 * 1024 ** 2)).toBe("891.8 MiB"); + expect(formatDecimalBytes(100_000)).toBe("100 kB"); + expect(formatDecimalBytes(200_000_000)).toBe("200 MB"); + expect(formatDecimalBytes(11_400_000_000)).toBe("11.4 GB"); + expect(formatThroughputRate(null)).toBe("—"); + expect(formatThroughputRate(0)).toBe("0 B/s"); + expect(formatThroughputRate(100_000)).toBe("100 kB/s"); + expect(formatThroughputRate(12_400_000)).toBe("12.4 MB/s"); + }); + + it("splits SVG paths across null values and downtime gaps and tracks isolated points", () => { + const res = buildSegmentedPaths( + [ + { x: 0, y: 10, gapBefore: false }, + { x: 10, y: 20, gapBefore: false }, + { x: 30, y: 15, gapBefore: true }, + { x: 40, y: null, gapBefore: false }, + { x: 50, y: 5, gapBefore: false }, + { x: 60, y: 8, gapBefore: false }, + ], + 80, + ); + expect(res.line).toBe("M0,10 L10,20 M50,5 L60,8"); + expect(res.area).toBe("M0,10 L10,20 L10,80 L0,80 Z M50,5 L60,8 L60,80 L50,80 Z"); + expect(res.isolated).toEqual([{ x: 30, y: 15 }]); + }); +}); diff --git a/src/features/services/containerStats.ts b/src/features/services/containerStats.ts new file mode 100644 index 0000000000..14af803ca3 --- /dev/null +++ b/src/features/services/containerStats.ts @@ -0,0 +1,615 @@ +/** + * Live container resource history store, Engine API streaming hook (with graceful + * polling fallback), throughput rate derivation, nice axis ticks, and segmented + * SVG geometry for Services › Docker › Dashboard. + */ +import { useEffect, useState } from "react"; +import { create } from "zustand"; +import { Channel } from "@tauri-apps/api/core"; +import { + call, + commands, + isCancelled, + isTauri, + nextRequestId, + type DockerContainerStats, + type DockerContainerStatsSample, +} from "@/platform/ipc"; +import { useToolWindowShown } from "@/workbench/contributions"; +import { endpointOf } from "./store"; + +export type StatsTimeWindow = "1m" | "5m" | "15m"; +export type IoChartMode = "rate" | "total"; +export type MemoryScaleMode = "auto" | "limit"; +export type PressureLevel = "normal" | "warn" | "danger"; + +export const TIME_WINDOW_MS: Record = { + "1m": 60_000, + "5m": 300_000, + "15m": 900_000, +}; + +/** 15 minutes at 1 Hz per container. */ +export const MAX_CONTAINER_STATS_SAMPLES = 900; +/** Cap retained histories across containers so memory stays bounded. */ +export const MAX_TRACKED_CONTAINERS = 8; +/** Break plotted lines across downtime / pause gaps longer than 15 seconds. */ +export const MAX_CONTINUOUS_GAP_MS = 15_000; +/** Default polling fallback delay (`top` interval) when streaming is unavailable. */ +export const STATS_FALLBACK_POLL_MS = 3000; + +export interface StatsSample { + timestampMs: number; + cpuPercent: number; + onlineCpus: number | null; + memUsedBytes: number; + memLimitBytes: number; + memPercent: number; + netRxBytes: number; + netTxBytes: number; + diskReadBytes: number; + diskWriteBytes: number; + pids: number; + approximateIo: boolean; + /** Original CLI strings when sampled via legacy one-shot `docker stats` fallback. */ + raw?: DockerContainerStats; +} + +export interface DerivedStatsPoint { + sample: StatsSample; + diskReadRate: number | null; + diskWriteRate: number | null; + netRxRate: number | null; + netTxRate: number | null; + /** True when a downtime or pause gap precedes this sample (splits SVG path). */ + gapBefore: boolean; +} + +interface ContainerStatsStore { + /** Ring buffer per `${conn}\0${containerId}`. */ + byScope: Record; + /** LRU order of tracked scopes (oldest first, newest last). */ + order: string[]; + timeWindow: StatsTimeWindow; + ioMode: IoChartMode; + memoryScale: MemoryScaleMode; +} + +const INITIAL_STORE: ContainerStatsStore = { + byScope: {}, + order: [], + timeWindow: "5m", + ioMode: "rate", + memoryScale: "auto", +}; + +export const useContainerStatsStore = create(() => ({ ...INITIAL_STORE })); + +export function containerStatsScope(conn: string, containerId: string): string { + return `${conn}\0${containerId}`; +} + +export function pushContainerStatsSample(scope: string, sample: StatsSample): void { + useContainerStatsStore.setState((state) => { + const existing = state.byScope[scope] ?? []; + const last = existing.at(-1); + if (last && sample.timestampMs <= last.timestampMs) { + return state; + } + const nextSamples = + existing.length >= MAX_CONTAINER_STATS_SAMPLES + ? [...existing.slice(existing.length - MAX_CONTAINER_STATS_SAMPLES + 1), sample] + : [...existing, sample]; + const nextOrder = [...state.order.filter((k) => k !== scope), scope]; + const nextByScope: Record = { ...state.byScope, [scope]: nextSamples }; + while (nextOrder.length > MAX_TRACKED_CONTAINERS) { + const evicted = nextOrder.shift(); + if (evicted && evicted !== scope) { + delete nextByScope[evicted]; + } + } + return { byScope: nextByScope, order: nextOrder }; + }); +} + +export function clearContainerStatsHistory(scope: string): void { + useContainerStatsStore.setState((state) => { + if (!(scope in state.byScope)) return state; + const nextByScope = { ...state.byScope }; + delete nextByScope[scope]; + return { + byScope: nextByScope, + order: state.order.filter((k) => k !== scope), + }; + }); +} + +export function setStatsTimeWindow(timeWindow: StatsTimeWindow): void { + useContainerStatsStore.setState({ timeWindow }); +} + +export function setStatsIoMode(ioMode: IoChartMode): void { + useContainerStatsStore.setState({ ioMode }); +} + +export function setStatsMemoryScale(memoryScale: MemoryScaleMode): void { + useContainerStatsStore.setState({ memoryScale }); +} + +/** Resets in-memory history and preferences (intended for tests). */ +export function resetContainerStatsStore(): void { + useContainerStatsStore.setState({ ...INITIAL_STORE }); +} + +// --------------------------------------------------------------------------- +// Parsing & formatting helpers + +const UNIT_MULTIPLIERS: Record = { + B: 1, + KiB: 1024, + MiB: 1024 ** 2, + GiB: 1024 ** 3, + TiB: 1024 ** 4, + PiB: 1024 ** 5, + Ki: 1024, + Mi: 1024 ** 2, + Gi: 1024 ** 3, + Ti: 1024 ** 4, + Pi: 1024 ** 5, + kB: 1000, + KB: 1000, + MB: 1000 ** 2, + GB: 1000 ** 3, + TB: 1000 ** 4, + PB: 1000 ** 5, + K: 1000, + k: 1000, + M: 1000 ** 2, + G: 1000 ** 3, + T: 1000 ** 4, +}; + +function parseUnitBytes(raw: string | undefined | null): number { + if (!raw) return 0; + const s = raw.trim(); + if (!s) return 0; + const m = /^([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]+)?$/.exec(s); + if (!m) return 0; + const num = Number.parseFloat(m[1]!); + if (!Number.isFinite(num) || num <= 0) return 0; + const unit = m[2] ?? ""; + if (!unit) return num; + const mult = UNIT_MULTIPLIERS[unit] ?? UNIT_MULTIPLIERS[unit.replace(/B$/i, "")]; + return mult ? num * mult : num; +} + +function parsePair(raw: string | undefined | null): [number, number] { + const parts = (raw ?? "").split("/"); + return [parseUnitBytes(parts[0]), parseUnitBytes(parts[1])]; +} + +function parsePct(raw: string | undefined | null): number { + if (!raw) return 0; + const n = Number.parseFloat(raw.replace(/%/g, "").trim()); + return Number.isFinite(n) && n >= 0 ? n : 0; +} + +/** Converts a one-shot `DockerContainerStats` CLI snapshot into a structured `StatsSample`. */ +export function sampleFromLegacyStats(stats: DockerContainerStats, timestampMs = Date.now()): StatsSample { + const [memUsedBytes, memLimitBytes] = parsePair(stats.memUsage); + const [netRxBytes, netTxBytes] = parsePair(stats.netIo); + const [diskReadBytes, diskWriteBytes] = parsePair(stats.blockIo); + const parsedMemPct = parsePct(stats.memPerc); + const memPercent = + parsedMemPct > 0 || memLimitBytes <= 0 ? parsedMemPct : Math.min(100, (memUsedBytes / memLimitBytes) * 100); + const pids = Number.parseInt((stats.pids ?? "").trim(), 10); + return { + timestampMs, + cpuPercent: parsePct(stats.cpuPerc), + onlineCpus: null, + memUsedBytes, + memLimitBytes, + memPercent, + netRxBytes, + netTxBytes, + diskReadBytes, + diskWriteBytes, + pids: Number.isFinite(pids) && pids >= 0 ? pids : 0, + approximateIo: true, + raw: stats, + }; +} + +/** Converts an Engine API `DockerContainerStatsSample` IPC payload into a `StatsSample`. */ +export function sampleFromStreamPayload(payload: DockerContainerStatsSample): StatsSample { + return { + timestampMs: payload.timestampMs, + cpuPercent: payload.cpuPercent ?? 0, + onlineCpus: payload.onlineCpus ?? null, + memUsedBytes: payload.memUsedBytes, + memLimitBytes: payload.memLimitBytes, + memPercent: payload.memPercent ?? 0, + netRxBytes: payload.netRxBytes, + netTxBytes: payload.netTxBytes, + diskReadBytes: payload.diskReadBytes, + diskWriteBytes: payload.diskWriteBytes, + pids: payload.pids, + approximateIo: payload.approximateIo, + }; +} + +/** Formats binary bytes (`0 B`, `512 KiB`, `891.8 MiB`, `1.16 GiB`). */ +export function formatBinaryBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) return "0 B"; + const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; + let idx = 0; + let val = bytes; + while (val >= 1024 && idx < units.length - 1) { + val /= 1024; + idx++; + } + if (idx === 0) return `${Math.round(val)} B`; + const digits = val >= 100 ? 1 : val >= 10 ? 1 : 2; + const formatted = digits > 0 ? val.toFixed(digits).replace(/\.?0+$/, "") : val.toFixed(0); + return `${formatted} ${units[idx]!}`; +} + +/** Formats decimal bytes (`0 B`, `450 kB`, `281 MB`, `11.4 GB`). */ +export function formatDecimalBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) return "0 B"; + const units = ["B", "kB", "MB", "GB", "TB", "PB"]; + let idx = 0; + let val = bytes; + while (val >= 1000 && idx < units.length - 1) { + val /= 1000; + idx++; + } + if (idx === 0) return `${Math.round(val)} B`; + const digits = val >= 100 ? 0 : val >= 10 ? 1 : 2; + const formatted = digits > 0 ? val.toFixed(digits).replace(/\.?0+$/, "") : val.toFixed(0); + return `${formatted} ${units[idx]!}`; +} + +/** Formats decimal byte throughput (`0 B/s`, `48 kB/s`, `12.4 MB/s`). */ +export function formatThroughputRate(bytesPerSec: number | null): string { + if (bytesPerSec === null || !Number.isFinite(bytesPerSec) || bytesPerSec < 0) return "—"; + if (bytesPerSec < 1) return "0 B/s"; + return `${formatDecimalBytes(bytesPerSec)}/s`; +} + +/** Formats CPU or memory percentage consistently (`0.0%`, `12.4%`, `142%`). */ +export function formatPercentCompact(percent: number): string { + if (!Number.isFinite(percent) || percent <= 0) return "0.0%"; + if (percent >= 100) return `${percent.toFixed(0)}%`; + if (percent >= 10) return `${percent.toFixed(1)}%`; + return `${percent.toFixed(2)}%`; +} + +const localTimeFormatter = new Intl.DateTimeFormat(undefined, { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hour12: false, +}); + +/** Formats a Unix ms timestamp in the user's system local timezone (`HH:mm:ss`). */ +export function formatLocalClock(timestampMs: number): string { + if (!Number.isFinite(timestampMs) || timestampMs <= 0) return ""; + return localTimeFormatter.format(new Date(timestampMs)); +} + +// --------------------------------------------------------------------------- +// Series derivation, ticks, pressure & SVG geometry + +/** + * Slices `samples` to the selected window (anchored to the latest recorded sample + * so paused or stopped sessions remain visible) and computes per-sample I/O rates + * and line-break gaps. + */ +export function deriveStatsSeries( + samples: readonly StatsSample[], + windowMs: number, +): { points: DerivedStatsPoint[]; windowStartMs: number; windowEndMs: number } { + if (!samples.length) { + return { points: [], windowStartMs: 0, windowEndMs: 0 }; + } + const windowEndMs = samples[samples.length - 1]!.timestampMs; + const windowStartMs = windowEndMs - windowMs; + // Include one preceding sample before `windowStartMs` when available so the first + // visible point still has an accurate rate delta. + let firstVisible = samples.findIndex((s) => s.timestampMs >= windowStartMs); + if (firstVisible < 0) firstVisible = samples.length - 1; + const startIdx = Math.max(0, firstVisible - 1); + + const points: DerivedStatsPoint[] = []; + for (let i = startIdx; i < samples.length; i++) { + const curr = samples[i]!; + const prev = i > 0 ? samples[i - 1]! : null; + const dtMs = prev ? curr.timestampMs - prev.timestampMs : 0; + const gapBefore = prev !== null && (dtMs <= 0 || dtMs > MAX_CONTINUOUS_GAP_MS); + const rate = (a: number, b: number): number | null => { + if (!prev || gapBefore || dtMs <= 0 || b < a) return null; + return ((b - a) * 1000) / dtMs; + }; + if (i >= firstVisible) { + points.push({ + sample: curr, + diskReadRate: rate(prev?.diskReadBytes ?? 0, curr.diskReadBytes), + diskWriteRate: rate(prev?.diskWriteBytes ?? 0, curr.diskWriteBytes), + netRxRate: rate(prev?.netRxBytes ?? 0, curr.netRxBytes), + netTxRate: rate(prev?.netTxBytes ?? 0, curr.netTxBytes), + gapBefore: i > firstVisible && gapBefore, + }); + } + } + return { points, windowStartMs, windowEndMs }; +} + +export interface SeriesSummary { + current: number | null; + peak: number | null; + avg: number | null; +} + +export function summarizeValues(values: ReadonlyArray): SeriesSummary { + let sum = 0; + let count = 0; + let peak = -Infinity; + let current: number | null = null; + for (const v of values) { + if (v !== null && Number.isFinite(v) && v >= 0) { + current = v; + sum += v; + count += 1; + if (v > peak) peak = v; + } + } + if (count === 0) return { current: null, peak: null, avg: null }; + return { current, peak, avg: sum / count }; +} + +/** Pressure tone for CPU / Memory ratios (`0..100+`). */ +export function pressureForRatio(percent: number): PressureLevel { + if (!Number.isFinite(percent)) return "normal"; + if (percent >= 95) return "danger"; + if (percent >= 85) return "warn"; + return "normal"; +} + +const DECIMAL_STEPS = [1, 2, 2.5, 5, 10]; +const BINARY_STEPS = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]; + +/** + * Generates clean Y-axis ticks from `0` up to `>= maxVal` using either decimal (`10`), + * SI byte (`1000`), or IEC binary byte (`1024`) human-readable step intervals. + */ +export function niceAxisTicks(maxVal: number, targetIntervals = 3, base: 10 | 1000 | 1024 = 10): number[] { + const safeMax = Number.isFinite(maxVal) && maxVal > 0 ? maxVal : 1; + const intervals = Math.max(1, targetIntervals); + + if (base === 1024) { + let unitScale = 1; + while (safeMax / unitScale >= 1024 && unitScale < 1024 ** 5) { + unitScale *= 1024; + } + const rawStep = safeMax / unitScale / intervals; + let chosen = BINARY_STEPS[BINARY_STEPS.length - 1]!; + for (const s of BINARY_STEPS) { + if (s >= rawStep) { + chosen = s; + break; + } + } + const step = chosen * unitScale; + const count = Math.max(1, Math.ceil(safeMax / step)); + return Array.from({ length: count + 1 }, (_, i) => i * step); + } + + const rawStep = safeMax / intervals; + const power = Math.pow(10, Math.floor(Math.log10(rawStep))); + const norm = rawStep / power; + const factor = DECIMAL_STEPS.find((s) => s >= norm) ?? 10; + const step = factor * power; + const count = Math.max(1, Math.ceil(safeMax / step)); + return Array.from({ length: count + 1 }, (_, i) => Number((i * step).toPrecision(12))); +} + +export interface SegmentedSeriesPaths { + line: string; + area: string; + /** Isolated single-point coordinates that cannot form a 2-point line segment. */ + isolated: Array<{ x: number; y: number }>; +} + +/** + * Builds SVG line & area path strings for a series, cleanly breaking across `null` + * values and `gapBefore` downtime boundaries so restarts never bridge fake lines. + */ +export function buildSegmentedPaths( + points: ReadonlyArray<{ x: number; y: number | null; gapBefore: boolean }>, + baselineY: number, +): SegmentedSeriesPaths { + const fmt = (n: number) => Number(n.toFixed(1)); + const lineParts: string[] = []; + const areaParts: string[] = []; + const isolated: Array<{ x: number; y: number }> = []; + + let segment: Array<{ x: number; y: number }> = []; + const flush = () => { + if (segment.length === 1) { + isolated.push(segment[0]!); + } else if (segment.length >= 2) { + const segLine = segment.map((p, idx) => `${idx === 0 ? "M" : "L"}${fmt(p.x)},${fmt(p.y)}`).join(" "); + const first = segment[0]!; + const last = segment[segment.length - 1]!; + lineParts.push(segLine); + areaParts.push(`${segLine} L${fmt(last.x)},${fmt(baselineY)} L${fmt(first.x)},${fmt(baselineY)} Z`); + } + segment = []; + }; + + for (const pt of points) { + if (pt.gapBefore) flush(); + if (pt.y === null || !Number.isFinite(pt.y)) { + flush(); + } else { + segment.push({ x: pt.x, y: pt.y }); + } + } + flush(); + + return { + line: lineParts.join(" "), + area: areaParts.join(" "), + isolated, + }; +} + +// --------------------------------------------------------------------------- +// Live stats subscription hook (streaming primary, 3s polling fallback) + +const EMPTY_SAMPLES: readonly StatsSample[] = []; + +export interface ContainerStatsStreamResult { + samples: readonly StatsSample[]; + loading: boolean; +} + +/** + * Streams live stats for a running container into the bounded ring buffer while + * the Services tool window and document are visible and unpaused. Automatically + * falls back to 3s `dockerContainerStats` polling when streaming is unavailable. + */ +export function useLiveContainerStatsHistory( + conn: string, + containerId: string, + running: boolean, + paused: boolean, +): ContainerStatsStreamResult { + const shown = useToolWindowShown(); + const scope = containerStatsScope(conn, containerId); + const samples = useContainerStatsStore((s) => s.byScope[scope] ?? EMPTY_SAMPLES); + const [settledScope, setSettledScope] = useState(""); + + const active = running && !paused && shown && isTauri(); + + useEffect(() => { + if (!active || !containerId) return; + let alive = true; + let pollTimer: ReturnType | undefined; + let inFlightPoll = false; + let activeStreamRequest: ReturnType | null = null; + let mode: "idle" | "stream" | "poll" = "idle"; + + const clearPollTimer = () => { + if (pollTimer !== undefined) { + clearTimeout(pollTimer); + pollTimer = undefined; + } + }; + + const stopStream = () => { + if (activeStreamRequest !== null) { + const req = activeStreamRequest; + activeStreamRequest = null; + void Promise.resolve(commands.cancelRequest(req)).catch(() => {}); + } + }; + + const isDocumentHidden = () => document.visibilityState === "hidden"; + + const pollOnce = async () => { + clearPollTimer(); + if (!alive || inFlightPoll || isDocumentHidden()) return; + inFlightPoll = true; + try { + const stats = await call(commands.dockerContainerStats(endpointOf(conn), containerId)); + if (alive) { + pushContainerStatsSample(scope, sampleFromLegacyStats(stats, Date.now())); + setSettledScope(scope); + } + } catch { + if (alive) setSettledScope(scope); + } finally { + inFlightPoll = false; + if (alive && mode === "poll" && !isDocumentHidden()) { + pollTimer = setTimeout(() => void pollOnce(), STATS_FALLBACK_POLL_MS); + } + } + }; + + const startPolling = () => { + if (!alive || mode === "poll") return; + stopStream(); + mode = "poll"; + if (!isDocumentHidden()) void pollOnce(); + }; + + const startStream = () => { + if (!alive || isDocumentHidden()) return; + if (typeof commands.dockerContainerStatsStream !== "function") { + startPolling(); + return; + } + clearPollTimer(); + stopStream(); + mode = "stream"; + let receivedAny = false; + try { + const request = nextRequestId(); + const channel = new Channel(); + channel.onmessage = (payload) => { + if (!alive || mode !== "stream") return; + receivedAny = true; + pushContainerStatsSample(scope, sampleFromStreamPayload(payload)); + setSettledScope(scope); + }; + activeStreamRequest = request; + call(commands.dockerContainerStatsStream(request, endpointOf(conn), containerId, channel)) + .then(() => { + if (!alive || activeStreamRequest !== request) return; + activeStreamRequest = null; + setSettledScope(scope); + if (!receivedAny) startPolling(); + }) + .catch((e) => { + if (!alive || activeStreamRequest !== request) return; + activeStreamRequest = null; + if (isCancelled(e)) return; + if (!receivedAny) { + startPolling(); + } else { + setSettledScope(scope); + } + }); + } catch { + startPolling(); + } + }; + + const onVisibility = () => { + if (isDocumentHidden()) { + clearPollTimer(); + stopStream(); + mode = "idle"; + } else { + startStream(); + } + }; + + document.addEventListener("visibilitychange", onVisibility); + if (!isDocumentHidden()) startStream(); + + return () => { + alive = false; + clearPollTimer(); + stopStream(); + document.removeEventListener("visibilitychange", onVisibility); + }; + }, [active, conn, containerId, scope]); + + return { + samples, + loading: active && samples.length === 0 && settledScope !== scope, + }; +} diff --git a/src/features/services/dashboard.tsx b/src/features/services/dashboard.tsx index ea1e67c0b7..6624df7965 100644 --- a/src/features/services/dashboard.tsx +++ b/src/features/services/dashboard.tsx @@ -59,6 +59,7 @@ import { isContainerOomKilled, useDevContainerResourceStatus, } from "./containerResources"; +import { clearContainerStatsHistory, containerStatsScope, useLiveContainerStatsHistory } from "./containerStats"; import { containerOp, endpointOf, errorMessage, useServices } from "./store"; import { useServicesTree } from "./tree"; import styles from "./Services.module.css"; @@ -1101,8 +1102,14 @@ export function ContainerDashboard({ const ports = useMemo(() => inspect?.ports ?? parsePortMappings(container.ports), [inspect, container.ports]); const matchedImage = useMemo(() => findImageForContainer(snapshot, container), [snapshot, container]); - const { byId: statsById, loading: statsLoading } = useLiveContainerStats(conn, running ? container.id : ""); - const stats = running ? (statsById[container.id] ?? null) : null; + const [statsPaused, setStatsPaused] = useState(false); + const statsScope = containerStatsScope(conn, container.id); + const { samples: statsSamples, loading: statsLoading } = useLiveContainerStatsHistory( + conn, + container.id, + running, + statsPaused, + ); const devStatus = useDevContainerResourceStatus(conn, container); const oomKilled = isContainerOomKilled(running, inspect, devStatus); @@ -1118,8 +1125,6 @@ export function ContainerDashboard({ Boolean(mountedVolumesKey), ); - const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0; - const memPair = stats ? parseUsagePair(stats.memUsage) : null; const labels = inspect?.labels.length ? inspect.labels : Object.entries(container.labels ?? {}); const command = useMemo( () => formatDockerCommand(inspect?.entrypoint ?? [], inspect?.cmd ?? [], container.command), @@ -1276,13 +1281,13 @@ export function ContainerDashboard({ setStatsPaused((p) => !p)} + onClearHistory={() => clearContainerStatsHistory(statsScope)} inspect={inspect} devStatus={devStatus} - cpuPercent={cpuPct} - memoryPercent={memPair?.percent ?? (stats ? parsePercent(stats.memPerc) : 0)} - renderProgress={(pct) => } /> diff --git a/src/features/services/dashboardStats.test.tsx b/src/features/services/dashboardStats.test.tsx index c83d7e3c7d..676af56af7 100644 --- a/src/features/services/dashboardStats.test.tsx +++ b/src/features/services/dashboardStats.test.tsx @@ -31,6 +31,7 @@ import { VOLUME_SIZES_POLL_MS, VolumeDashboard, } from "./dashboard"; +import { resetContainerStatsStore } from "./containerStats"; const ok = (data: T) => ({ status: "ok" as const, data }); @@ -83,6 +84,7 @@ const snapshot: DockerSnapshot = { beforeEach(() => { vi.useFakeTimers(); + resetContainerStatsStore(); backend.stats.mockReset(); backend.volumeSizes.mockReset(); backend.volumeSizes.mockResolvedValue(ok({})); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7450e3190a..e4d6159c15 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -5368,6 +5368,31 @@ "Limit: {memLimitText} · {sourceLabel}": "Limit: {memLimitText} · {sourceLabel}", "Docker VM: {vmMemText}": "Docker VM: {vmMemText}", "Host requirements": "Host requirements", + "1m": "1m", + "5m": "5m", + "15m": "15m", + "Rate": "Rate", + "Total": "Total", + "Limit": "Limit", + "Time window": "Time window", + "I/O chart mode": "I/O chart mode", + "Memory scale": "Memory scale", + "Live": "Live", + "Last session": "Last session", + "Resume metrics": "Resume metrics", + "Pause metrics": "Pause metrics", + "Clear metrics history": "Clear metrics history", + "Container resource metrics": "Container resource metrics", + "Collecting samples…": "Collecting samples…", + "Disk I/O": "Disk I/O", + "Read": "Read", + "Write": "Write", + "Received": "Received", + "Sent": "Sent", + "Peak {peak} · Avg {avg}": "Peak {peak} · Avg {avg}", + "Peak {peak}": "Peak {peak}", + "Total {total}": "Total {total}", + "PIDs {pids}": "PIDs {pids}", "{memoryBytes} RAM": "{memoryBytes} RAM", "{storageBytes} storage": "{storageBytes} storage", "OOM killed": "OOM killed", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9101799fb4..591f5715e9 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -12267,6 +12267,30 @@ "Limit: {memLimitText} · {sourceLabel}": "限制:{memLimitText} · {sourceLabel}", "Docker VM: {vmMemText}": "Docker 虚拟机:{vmMemText}", "Host requirements": "主机要求", + "1m": "1 分钟", + "5m": "5 分钟", + "15m": "15 分钟", + "Rate": "速率", + "Limit": "上限", + "Time window": "时间窗口", + "I/O chart mode": "I/O 图表模式", + "Memory scale": "内存刻度", + "Live": "实时", + "Last session": "上次会话", + "Resume metrics": "恢复指标", + "Pause metrics": "暂停指标", + "Clear metrics history": "清除指标历史", + "Container resource metrics": "容器资源指标", + "Collecting samples…": "正在采集样本…", + "Disk I/O": "磁盘 I/O", + "Read": "读取", + "Write": "写入", + "Received": "接收", + "Sent": "发送", + "Peak {peak} · Avg {avg}": "峰值 {peak} · 平均 {avg}", + "Peak {peak}": "峰值 {peak}", + "Total {total}": "累计 {total}", + "PIDs {pids}": "进程数 {pids}", "{memoryBytes} RAM": "{memoryBytes} 内存", "{storageBytes} storage": "{storageBytes} 存储", "OOM killed": "OOM 终止", diff --git a/src/styles/tokens.css b/src/styles/tokens.css index fcacc22cdf..fb193c67e3 100644 --- a/src/styles/tokens.css +++ b/src/styles/tokens.css @@ -99,6 +99,7 @@ html[data-os="windows"] { /* charts (IDEA's first series colour) */ --chart-series: #e07a7c; + --chart-series-secondary: #d59637; /* status */ --danger: #f57e84; @@ -635,6 +636,7 @@ html[data-os="windows"] { /* charts */ --chart-series: #d9686a; + --chart-series-secondary: #b55e12; /* status */ --danger: #c54e58; @@ -949,6 +951,7 @@ html[data-os="windows"] { --link-hover: #d0dffe; --chart-series: #ff9b9f; + --chart-series-secondary: #f2c55c; --danger: #ff9b9f; --warning: #f2c55c; @@ -1322,6 +1325,7 @@ html[data-os="windows"] { --wave-error: var(--palette-red); --syn-invalid: var(--palette-red); --chart-series: var(--palette-red); + --chart-series-secondary: var(--palette-yellow); --warning: var(--palette-yellow); --wave-warning: var(--palette-yellow); --fg-bulb: var(--palette-yellow);