diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 94bb4d34fb..981b36dc8b 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -125,6 +125,7 @@ pub struct Host { pub(crate) rebase_editors: Arc, /// The IDE's Java build: resident javac processes shared by every window's launches. pub(crate) java_build: Arc, + pub(crate) metrics_sampler: Mutex, /// SSH connections of Settings › SSH Configurations. pub ssh: Arc, /// SFTP deployment, remote file editing and runs on run targets. @@ -255,6 +256,7 @@ impl Host { heap_requests: Default::default(), rebase_editors: Default::default(), java_build: Default::default(), + metrics_sampler: Default::default(), languages, syntax, config_dir, diff --git a/crates/ide-host/src/ops/host_metrics.rs b/crates/ide-host/src/ops/host_metrics.rs new file mode 100644 index 0000000000..7930ad8efe --- /dev/null +++ b/crates/ide-host/src/ops/host_metrics.rs @@ -0,0 +1,264 @@ +//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host +//! Resources status bar widget and popover dashboard. + +use crate::Host; +use ide_command::command; +use ide_core::IdeResult; +use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable}; +use ide_workspace::system::SystemSampler; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +#[derive(Default)] +pub(crate) struct HostMetricsSampler { + system: SystemSampler, + cpu: CpuSampler, +} + +/// One process outside OpenIDEA's own process tree on the host (read-only in the UI). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct HostProcess { + pub pid: u32, + pub name: String, + pub cpu_percent: Option, + pub memory_bytes: Option, +} + +/// Snapshot of host-wide CPU, memory, network, disk and process usage. +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct HostMetrics { + /// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample. + pub cpu_percent: Option, + /// Logical CPU cores available to this host or container. + pub cpu_cores: u32, + /// Unix 1m, 5m, 15m load averages; `null` on Windows. + pub load_average: Option<[f32; 3]>, + /// Host or container memory in use, in bytes. + pub memory_used_bytes: Option, + /// Total physical (or container limit) memory, in bytes. + pub memory_total_bytes: Option, + /// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS. + pub net_rx_bytes_per_sec: Option, + /// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS. + pub net_tx_bytes_per_sec: Option, + /// Bytes/s read from block storage; `null` on the first sample or unsupported OS. + pub disk_read_bytes_per_sec: Option, + /// Bytes/s written to block storage; `null` on the first sample or unsupported OS. + pub disk_write_bytes_per_sec: Option, + /// Free bytes available to the user on the project volume (or `$HOME` fallback). + pub disk_available_bytes: Option, + /// Total capacity in bytes of the project volume (or `$HOME` fallback). + pub disk_total_bytes: Option, + /// Uptime of the backend process in milliseconds. + pub uptime_ms: f64, + /// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`). + pub processes: Vec, + /// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`). + pub external_processes: Vec, +} + +const MAX_EXTERNAL_PROCESSES: usize = 5; +const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5; +const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20; + +fn project_name(root: &Path) -> String { + root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string()) +} + +fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot { + MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true } +} + +fn volume_path(host: &Host, window: &str) -> PathBuf { + if let Ok(p) = host.project(window) { + return p.root.clone(); + } + if let Some(p) = host.projects().into_iter().next() { + return p.root.clone(); + } + dirs::home_dir().unwrap_or_else(|| host.data_dir.clone()) +} + +fn disk_space(path: &Path) -> Option<(u64, u64)> { + #[cfg(unix)] + #[allow(clippy::unnecessary_cast)] + { + let stat = rustix::fs::statvfs(path).ok()?; + let frsize = stat.f_frsize as u64; + let total = (stat.f_blocks as u64).saturating_mul(frsize); + let avail = (stat.f_bavail as u64).saturating_mul(frsize); + (total > 0).then_some((avail.min(total), total)) + } + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + let wide: Vec = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect(); + let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64); + // SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable. + let ok = unsafe { + windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW( + wide.as_ptr(), + &mut avail, + &mut total, + &mut free, + ) + }; + (ok != 0 && total > 0).then_some((avail.min(total), total)) + } + #[cfg(not(any(unix, windows)))] + { + let _ = path; + None + } +} + +fn collect_roots(host: &Host) -> Vec { + let mut roots = Vec::new(); + for p in host.projects() { + for s in p.lsp.servers() { + if let Some(pid) = s.pid { + roots.push(MemoryRoot { + pid, + category: MemoryCategory::LanguageServer, + label: s.name, + detail: Some(project_name(s.root.as_ref())), + with_children: true, + }); + } + } + } + for r in host.processes.list().into_iter().filter(|r| r.running) { + if let Some(pid) = r.pid { + roots.push(process_root(pid, r.name, "Run")); + } + } + for t in host.terminals.list() { + if let Some(pid) = t.pid { + roots.push(process_root(pid, t.title, "Terminal")); + } + } + roots +} + +fn resource_share(p: &HostProcess, cores: u32, total_memory: Option) -> f64 { + let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0); + let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) { + (Some(b), Some(t)) => b as f64 / t as f64, + _ => 0.0, + }; + cpu_share.max(mem_share) +} + +/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when +/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes. +#[command(trust = always)] +pub async fn host_metrics(host: &Arc, window: &str, include_processes: bool) -> IdeResult { + let disk_target = volume_path(host, window); + let roots = if include_processes { collect_roots(host) } else { Vec::new() }; + let h = host.clone(); + host.blocking(move || { + let table = include_processes.then(ProcessTable::snapshot); + let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) { + Some((a, t)) => (Some(a), Some(t)), + None => (None, None), + }; + let uptime_ms = + ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0; + + let mut sampler = h.metrics_sampler.lock(); + let rates = sampler.system.sample(); + + let (processes, external_processes) = if let Some(table) = table { + sampler.cpu.retain(&table); + let me = std::process::id(); + let processes = + memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid)); + let claimed: HashSet = table.tree(me).into_iter().collect(); + let mut external: Vec = table + .entries() + .filter(|e| e.pid != 0 && !claimed.contains(&e.pid)) + .filter_map(|e| { + let cpu_percent = sampler.cpu.percent(e.pid); + let memory_bytes = memory::fast_resident_bytes(e.pid); + let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT + || memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES; + active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes }) + }) + .collect(); + external.sort_by(|a, b| { + resource_share(b, rates.cpu_cores, rates.memory_total_bytes) + .total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes)) + .then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0))) + .then_with(|| a.pid.cmp(&b.pid)) + }); + external.truncate(MAX_EXTERNAL_PROCESSES); + (processes, external) + } else { + (Vec::new(), Vec::new()) + }; + + Ok(HostMetrics { + cpu_percent: rates.cpu_percent, + cpu_cores: rates.cpu_cores, + load_average: rates.load_average, + memory_used_bytes: rates.memory_used_bytes, + memory_total_bytes: rates.memory_total_bytes, + net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec, + net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec, + disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec, + disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec, + disk_available_bytes, + disk_total_bytes, + uptime_ms, + processes, + external_processes, + }) + }) + .await +} + +/// Ends a child process started by this OpenIDEA host (language server, run, terminal, +/// debug adapter or agent) and its descendants; refuses processes outside this host's tree. +#[command(trust = trusted)] +pub async fn host_end_process(host: &Arc, pid: u32) -> IdeResult { + host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await +} + +ide_command::domain!(host_metrics: host_metrics, host_end_process); + +#[cfg(test)] +mod tests { + use super::*; + use crate::HostConfig; + + #[tokio::test] + async fn collects_light_and_detailed_host_metrics() { + let dir = tempfile::tempdir().unwrap(); + let host = Arc::new(Host::new(HostConfig::for_test(dir.path()))); + + let light = host_metrics(&host, "main", false).await.unwrap(); + assert!(light.cpu_cores >= 1); + assert!(light.processes.is_empty()); + assert!(light.external_processes.is_empty()); + if cfg!(any(unix, windows)) { + let avail = light.disk_available_bytes.expect("disk_available_bytes"); + let total = light.disk_total_bytes.expect("disk_total_bytes"); + assert!(total > 0 && avail <= total, "{avail} / {total}"); + } + + let detailed = host_metrics(&host, "main", true).await.unwrap(); + assert!(!detailed.processes.is_empty()); + assert_eq!(detailed.processes[0].label, "Backend"); + assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES); + + // Refuses to terminate the backend itself or PID 1. + assert!(!host_end_process(&host, std::process::id()).await.unwrap()); + assert!(!host_end_process(&host, 1).await.unwrap()); + } +} diff --git a/crates/ide-host/src/ops/mod.rs b/crates/ide-host/src/ops/mod.rs index 9996dfa5cd..3851054cb3 100644 --- a/crates/ide-host/src/ops/mod.rs +++ b/crates/ide-host/src/ops/mod.rs @@ -19,6 +19,7 @@ pub mod flutter; pub mod fs; pub mod heap; pub mod history; +pub mod host_metrics; pub mod http; pub mod java; pub mod jvm_icons; @@ -94,6 +95,7 @@ ide_command::domains!( fs: crate::ops::fs, heap: crate::ops::heap, history: crate::ops::history, + host_metrics: crate::ops::host_metrics, http: crate::ops::http, java: crate::ops::java, jvm_icons: crate::ops::jvm_icons, diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/rpc.rs index c964949055..553dde18e7 100644 --- a/crates/ide-host/tests/rpc.rs +++ b/crates/ide-host/tests/rpc.rs @@ -80,14 +80,23 @@ async fn serves_projects_files_documents_search_and_runs() { assert_eq!(opened["name"], "demo"); assert_eq!(opened["trusted"], false); invoke(&peer, "index_status", json!({})).await.unwrap(); + let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap(); + assert!(metrics["cpuCores"].as_u64().unwrap() >= 1); + assert_eq!(metrics["processes"][0]["label"], "Backend"); assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([])); invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap(); let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap(); assert!(files.is_array()); - for command in - ["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"] - { - let error = invoke(&peer, command, json!({})).await.unwrap_err(); + for (command, args) in [ + ("build_sync", json!({})), + ("run_start", json!({})), + ("sdk_locate_tools", json!({})), + ("notebook_execute", json!({})), + ("debug_start", json!({})), + ("agent_refresh_models", json!({})), + ("host_end_process", json!({ "pid": 1 })), + ] { + let error = invoke(&peer, command, args).await.unwrap_err(); assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}"); } let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) }; diff --git a/crates/ide-workspace/src/lib.rs b/crates/ide-workspace/src/lib.rs index b39a3a9221..cd5198c689 100644 --- a/crates/ide-workspace/src/lib.rs +++ b/crates/ide-workspace/src/lib.rs @@ -16,6 +16,7 @@ pub mod project_discovery; pub mod recent; pub mod roots; pub mod settings; +pub mod system; pub mod text_refs; pub mod unity; pub mod unreal; diff --git a/crates/ide-workspace/src/memory.rs b/crates/ide-workspace/src/memory.rs index 1274990cf4..b1fc25ef53 100644 --- a/crates/ide-workspace/src/memory.rs +++ b/crates/ide-workspace/src/memory.rs @@ -58,6 +58,11 @@ impl ProcessTable { self.entries.get(&pid) } + /// Every process in the snapshot, in arbitrary order. + pub fn entries(&self) -> impl Iterator { + self.entries.values() + } + /// Direct children of `pid`, ascending. pub fn children(&self, pid: u32) -> &[u32] { self.children.get(&pid).map(Vec::as_slice).unwrap_or_default() @@ -274,6 +279,12 @@ pub fn footprint_bytes(pid: u32) -> Option { imp::footprint_bytes(pid) } +/// Fast O(1) resident memory estimate for scanning many external processes +/// without walking every mapping (`/proc//statm` on Linux). +pub fn fast_resident_bytes(pid: u32) -> Option { + imp::fast_resident_bytes(pid) +} + /// Processes serving one `WKWebView` (0 = none / unknown). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WebKitPids { @@ -414,6 +425,10 @@ mod imp { (rc == 0).then_some(info[PHYS_FOOTPRINT_WORD]) } + pub fn fast_resident_bytes(pid: u32) -> Option { + footprint_bytes(pid) + } + /// `ri_user_time + ri_system_time` (words 2 and 3), in Mach absolute time units. pub fn cpu_time(pid: u32) -> Option { static TIMEBASE: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); @@ -520,6 +535,10 @@ mod imp { kb_field(&std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?, "VmRSS:") } + pub fn fast_resident_bytes(pid: u32) -> Option { + kb_field(&std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?, "VmRSS:") + } + pub fn responsible_pid(_pid: u32) -> Option { None } @@ -668,6 +687,10 @@ mod imp { (ok != 0).then_some(c.PrivateUsage as u64) } + pub fn fast_resident_bytes(pid: u32) -> Option { + footprint_bytes(pid) + } + /// Kernel + user time from `GetProcessTimes` (100 ns units). pub fn cpu_time(pid: u32) -> Option { // SAFETY: plain Win32 call; the handle is closed below. @@ -711,6 +734,9 @@ mod imp { pub fn footprint_bytes(_pid: u32) -> Option { None } + pub fn fast_resident_bytes(_pid: u32) -> Option { + None + } pub fn cpu_time(_pid: u32) -> Option { None } diff --git a/crates/ide-workspace/src/system.rs b/crates/ide-workspace/src/system.rs new file mode 100644 index 0000000000..f0c774871b --- /dev/null +++ b/crates/ide-workspace/src/system.rs @@ -0,0 +1,767 @@ +//! Host-wide resource counters (CPU, memory, load average, network and disk I/O) +//! and rate sampling for the Remote Host Resources status bar widget and dashboard. +//! +//! On Linux (including cgroup v2 containers such as Dev Containers and Kubernetes +//! pods) container CPU and memory quotas take precedence when narrower than the +//! physical host, so percentages reflect the headroom actually available to builds, +//! language servers and coding agents. + +use std::time::{Duration, Instant}; + +/// Raw cumulative CPU counters at one instant. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum CpuCounters { + /// Aggregate host ticks (`busy <= total`). + Ticks { busy: u64, total: u64 }, + /// Container cgroup v2 `usage_usec` against a quota of `cores` logical CPUs. + CgroupUsec { usage_usec: u64, cores: f64 }, +} + +/// Cumulative byte counters at one instant (network RX/TX or disk read/write). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TransferCounters { + pub read_or_rx_bytes: u64, + pub write_or_tx_bytes: u64, +} + +/// Raw OS counters captured in one snapshot. +#[derive(Clone, Debug, PartialEq)] +pub struct RawSystemCounters { + pub cpu: Option, + pub cpu_cores: u32, + pub load_average: Option<[f32; 3]>, + pub memory_used_bytes: Option, + pub memory_total_bytes: Option, + pub net: Option, + pub disk_io: Option, +} + +/// Sampled host metrics with computed rates (`None` on the first sample). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SystemRates { + /// Overall CPU utilization across all available cores (`0.0..=100.0`). + pub cpu_percent: Option, + pub cpu_cores: u32, + pub load_average: Option<[f32; 3]>, + pub memory_used_bytes: Option, + pub memory_total_bytes: Option, + pub net_rx_bytes_per_sec: Option, + pub net_tx_bytes_per_sec: Option, + pub disk_read_bytes_per_sec: Option, + pub disk_write_bytes_per_sec: Option, +} + +/// Shorter gaps (multiple windows polling at once) reuse the previous rates +/// instead of dividing over a few milliseconds. +const MIN_SAMPLE_INTERVAL: Duration = Duration::from_millis(500); + +#[derive(Clone, Debug)] +struct PrevSample { + at: Instant, + raw: RawSystemCounters, + rates: SystemRates, +} + +/// Stateful sampler that turns cumulative OS counters into percentages and bytes/s. +#[derive(Debug, Default)] +pub struct SystemSampler { + prev: Option, +} + +impl SystemSampler { + pub fn sample(&mut self) -> SystemRates { + self.record(snapshot(), Instant::now()) + } + + pub fn record(&mut self, raw: RawSystemCounters, at: Instant) -> SystemRates { + if let Some(prev) = &self.prev + && at.saturating_duration_since(prev.at) < MIN_SAMPLE_INTERVAL + { + return SystemRates { + cpu_cores: raw.cpu_cores, + load_average: raw.load_average, + memory_used_bytes: raw.memory_used_bytes, + memory_total_bytes: raw.memory_total_bytes, + ..prev.rates + }; + } + + let elapsed = self.prev.as_ref().map(|p| at.saturating_duration_since(p.at).as_secs_f64()).filter(|&s| s > 0.0); + + let cpu_percent = match (self.prev.as_ref().and_then(|p| p.raw.cpu), raw.cpu, elapsed) { + ( + Some(CpuCounters::Ticks { busy: b0, total: t0 }), + Some(CpuCounters::Ticks { busy: b1, total: t1 }), + Some(_), + ) if b1 >= b0 && t1 > t0 => Some(((b1 - b0) as f64 / (t1 - t0) as f64 * 100.0).clamp(0.0, 100.0) as f32), + ( + Some(CpuCounters::CgroupUsec { usage_usec: u0, .. }), + Some(CpuCounters::CgroupUsec { usage_usec: u1, cores }), + Some(secs), + ) if u1 >= u0 && cores > 0.0 => { + let wall_usec = secs * 1_000_000.0 * cores; + (wall_usec > 0.0).then(|| ((u1 - u0) as f64 / wall_usec * 100.0).clamp(0.0, 100.0) as f32) + } + _ => None, + }; + + let (net_rx_bytes_per_sec, net_tx_bytes_per_sec) = + transfer_rate(self.prev.as_ref().and_then(|p| p.raw.net), raw.net, elapsed); + let (disk_read_bytes_per_sec, disk_write_bytes_per_sec) = + transfer_rate(self.prev.as_ref().and_then(|p| p.raw.disk_io), raw.disk_io, elapsed); + + let rates = SystemRates { + cpu_percent, + cpu_cores: raw.cpu_cores, + load_average: raw.load_average, + memory_used_bytes: raw.memory_used_bytes, + memory_total_bytes: raw.memory_total_bytes, + net_rx_bytes_per_sec, + net_tx_bytes_per_sec, + disk_read_bytes_per_sec, + disk_write_bytes_per_sec, + }; + self.prev = Some(PrevSample { at, raw, rates }); + rates + } +} + +fn transfer_rate( + prev: Option, + curr: Option, + elapsed: Option, +) -> (Option, Option) { + let (Some(p), Some(c), Some(secs)) = (prev, curr, elapsed) else { + return (None, None); + }; + let rx = c.read_or_rx_bytes.checked_sub(p.read_or_rx_bytes).map(|d| d as f64 / secs); + let tx = c.write_or_tx_bytes.checked_sub(p.write_or_tx_bytes).map(|d| d as f64 / secs); + (rx, tx) +} + +/// Captures raw OS counters right now. +pub fn snapshot() -> RawSystemCounters { + imp::snapshot() +} + +pub(crate) fn host_cpu_cores() -> u32 { + std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(1).max(1) +} + +#[cfg(any(target_os = "linux", test))] +mod linux_parse { + use super::{CpuCounters, TransferCounters}; + + pub fn proc_stat_cpu(text: &str) -> Option { + let line = text.lines().find(|l| l.starts_with("cpu "))?; + let fields: Vec = line["cpu ".len()..].split_whitespace().take(8).filter_map(|s| s.parse().ok()).collect(); + if fields.len() < 4 { + return None; + } + let idle = fields[3].saturating_add(fields.get(4).copied().unwrap_or(0)); + let total = fields.iter().copied().fold(0u64, u64::saturating_add); + Some(CpuCounters::Ticks { busy: total.saturating_sub(idle), total }) + } + + pub fn cgroup_cpu_quota_cores(cpu_max: &str) -> Option { + let mut parts = cpu_max.split_whitespace(); + let quota_str = parts.next()?; + if quota_str == "max" { + return None; + } + let quota: u64 = quota_str.parse().ok()?; + let period: u64 = parts.next()?.parse().ok()?; + (quota > 0 && period > 0).then(|| quota as f64 / period as f64) + } + + pub fn cgroup_cpu_usage_usec(cpu_stat: &str) -> Option { + for line in cpu_stat.lines() { + let mut parts = line.split_whitespace(); + if parts.next() == Some("usage_usec") { + return parts.next()?.parse().ok(); + } + } + None + } + + fn kb_field(text: &str, key: &str) -> Option { + let line = text.lines().find(|l| l.starts_with(key))?; + let kb: u64 = line[key.len()..].split_whitespace().next()?.parse().ok()?; + Some(kb.saturating_mul(1024)) + } + + pub fn meminfo(text: &str) -> Option<(u64, u64)> { + let total = kb_field(text, "MemTotal:")?; + let avail = kb_field(text, "MemAvailable:").or_else(|| { + let free = kb_field(text, "MemFree:")?; + let buffers = kb_field(text, "Buffers:").unwrap_or(0); + let cached = kb_field(text, "Cached:").unwrap_or(0); + Some(free.saturating_add(buffers).saturating_add(cached)) + })?; + Some((total.saturating_sub(avail), total)) + } + + pub fn cgroup_memory( + max_text: &str, + current_text: &str, + stat_text: Option<&str>, + host_total: Option, + ) -> Option<(u64, u64)> { + let max_str = max_text.trim(); + if max_str == "max" { + return None; + } + let max_bytes: u64 = max_str.parse().ok()?; + if max_bytes == 0 || host_total.is_some_and(|ht| max_bytes >= ht) { + return None; + } + let current_bytes: u64 = current_text.trim().parse().ok()?; + let inactive_file = stat_text + .and_then(|s| { + s.lines().find_map(|l| { + let mut p = l.split_whitespace(); + (p.next() == Some("inactive_file")).then(|| p.next()?.parse::().ok())? + }) + }) + .unwrap_or(0); + let used = current_bytes.saturating_sub(inactive_file).min(max_bytes); + Some((used, max_bytes)) + } + + pub fn loadavg(text: &str) -> Option<[f32; 3]> { + let mut p = text.split_whitespace(); + Some([p.next()?.parse().ok()?, p.next()?.parse().ok()?, p.next()?.parse().ok()?]) + } + + pub fn net_dev(text: &str) -> Option { + let mut rx = 0u64; + let mut tx = 0u64; + let mut any = false; + for line in text.lines() { + let Some((iface, rest)) = line.split_once(':') else { continue }; + if iface.trim() == "lo" { + continue; + } + let mut cols = rest.split_whitespace(); + let Some(ibytes) = cols.next().and_then(|s| s.parse::().ok()) else { continue }; + let Some(obytes) = cols.nth(7).and_then(|s| s.parse::().ok()) else { continue }; + rx = rx.saturating_add(ibytes); + tx = tx.saturating_add(obytes); + any = true; + } + any.then_some(TransferCounters { read_or_rx_bytes: rx, write_or_tx_bytes: tx }) + } + + pub fn is_whole_disk(name: &str) -> bool { + if let Some(rest) = name.strip_prefix("nvme") { + let Some((ctrl, ns)) = rest.split_once('n') else { return false }; + return !ctrl.is_empty() + && ctrl.bytes().all(|b| b.is_ascii_digit()) + && !ns.is_empty() + && ns.bytes().all(|b| b.is_ascii_digit()); + } + if let Some(rest) = name.strip_prefix("mmcblk") { + return !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()); + } + for prefix in ["xvd", "sd", "hd", "vd"] { + if let Some(rest) = name.strip_prefix(prefix) { + return !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_lowercase()); + } + } + false + } + + pub fn diskstats(text: &str) -> Option { + let mut r = 0u64; + let mut w = 0u64; + let mut any = false; + for line in text.lines() { + let mut parts = line.split_whitespace(); + let Some(name) = parts.nth(2) else { continue }; + if !is_whole_disk(name) { + continue; + } + let Some(sectors_read) = parts.nth(2).and_then(|s| s.parse::().ok()) else { continue }; + let Some(sectors_written) = parts.nth(3).and_then(|s| s.parse::().ok()) else { continue }; + r = r.saturating_add(sectors_read.saturating_mul(512)); + w = w.saturating_add(sectors_written.saturating_mul(512)); + any = true; + } + any.then_some(TransferCounters { read_or_rx_bytes: r, write_or_tx_bytes: w }) + } + + pub fn cgroup_io_stat(text: &str) -> Option { + let mut r = 0u64; + let mut w = 0u64; + let mut any = false; + for line in text.lines() { + for token in line.split_whitespace().skip(1) { + if let Some(v) = token.strip_prefix("rbytes=").and_then(|s| s.parse::().ok()) { + r = r.saturating_add(v); + any = true; + } else if let Some(v) = token.strip_prefix("wbytes=").and_then(|s| s.parse::().ok()) { + w = w.saturating_add(v); + any = true; + } + } + } + any.then_some(TransferCounters { read_or_rx_bytes: r, write_or_tx_bytes: w }) + } +} + +#[cfg(target_os = "linux")] +mod imp { + use super::{CpuCounters, RawSystemCounters, host_cpu_cores, linux_parse}; + use std::fs; + + pub fn snapshot() -> RawSystemCounters { + let physical_cores = host_cpu_cores(); + let cgroup_cores = fs::read_to_string("/sys/fs/cgroup/cpu.max") + .ok() + .and_then(|s| linux_parse::cgroup_cpu_quota_cores(&s)) + .filter(|&c| c < physical_cores as f64); + + let (cpu, cpu_cores) = if let Some(cores) = cgroup_cores + && let Ok(stat) = fs::read_to_string("/sys/fs/cgroup/cpu.stat") + && let Some(usage_usec) = linux_parse::cgroup_cpu_usage_usec(&stat) + { + (Some(CpuCounters::CgroupUsec { usage_usec, cores }), (cores.ceil() as u32).max(1)) + } else { + let ticks = fs::read_to_string("/proc/stat").ok().and_then(|s| linux_parse::proc_stat_cpu(&s)); + (ticks, physical_cores) + }; + + let host_mem = fs::read_to_string("/proc/meminfo").ok().and_then(|s| linux_parse::meminfo(&s)); + let cgroup_mem = fs::read_to_string("/sys/fs/cgroup/memory.max") + .ok() + .zip(fs::read_to_string("/sys/fs/cgroup/memory.current").ok()) + .and_then(|(max, cur)| { + let stat = fs::read_to_string("/sys/fs/cgroup/memory.stat").ok(); + linux_parse::cgroup_memory(&max, &cur, stat.as_deref(), host_mem.map(|(_, t)| t)) + }); + let (memory_used_bytes, memory_total_bytes) = match cgroup_mem.or(host_mem) { + Some((used, total)) => (Some(used), Some(total)), + None => (None, None), + }; + + let load_average = fs::read_to_string("/proc/loadavg").ok().and_then(|s| linux_parse::loadavg(&s)); + let net = fs::read_to_string("/proc/net/dev").ok().and_then(|s| linux_parse::net_dev(&s)); + let disk_io = fs::read_to_string("/proc/diskstats") + .ok() + .and_then(|s| linux_parse::diskstats(&s)) + .filter(|c| c.read_or_rx_bytes > 0 || c.write_or_tx_bytes > 0) + .or_else(|| fs::read_to_string("/sys/fs/cgroup/io.stat").ok().and_then(|s| linux_parse::cgroup_io_stat(&s))) + .or_else(|| fs::read_to_string("/proc/diskstats").ok().and_then(|s| linux_parse::diskstats(&s))); + + RawSystemCounters { cpu, cpu_cores, load_average, memory_used_bytes, memory_total_bytes, net, disk_io } + } +} + +#[cfg(target_os = "macos")] +#[allow(non_camel_case_types, unsafe_code)] +mod imp { + use super::{CpuCounters, RawSystemCounters, TransferCounters, host_cpu_cores}; + use std::ffi::c_void; + use std::sync::OnceLock; + + type kern_return_t = i32; + type mach_port_t = u32; + type natural_t = u32; + type integer_t = i32; + type mach_msg_type_number_t = u32; + + const HOST_CPU_LOAD_INFO: i32 = 3; + const HOST_VM_INFO64: i32 = 4; + + const CTL_NET: i32 = 4; + const PF_ROUTE: i32 = 17; + const NET_RT_IFLIST2: i32 = 6; + const RTM_IFINFO2: u8 = 0x12; + const IFF_LOOPBACK: i32 = 0x8; + + #[repr(C)] + #[derive(Default)] + struct HostCpuLoadInfo { + cpu_ticks: [natural_t; 4], + } + + #[repr(C, packed(4))] + #[derive(Default)] + struct VmStatistics64 { + free_count: natural_t, + active_count: natural_t, + inactive_count: natural_t, + wire_count: natural_t, + zero_fill_count: u64, + reactivations: u64, + pageins: u64, + pageouts: u64, + faults: u64, + cow_faults: u64, + lookups: u64, + hits: u64, + purges: u64, + purgeable_count: natural_t, + speculative_count: natural_t, + decompressions: u64, + compressions: u64, + swapins: u64, + swapouts: u64, + compressor_page_count: natural_t, + throttled_count: natural_t, + external_page_count: natural_t, + internal_page_count: natural_t, + total_uncompressed_pages_in_compressor: u64, + } + + unsafe extern "C" { + fn mach_host_self() -> mach_port_t; + fn host_page_size(host: mach_port_t, out_page_size: *mut usize) -> kern_return_t; + fn host_statistics( + host: mach_port_t, + flavor: i32, + host_info_out: *mut integer_t, + host_info_out_cnt: *mut mach_msg_type_number_t, + ) -> kern_return_t; + fn host_statistics64( + host: mach_port_t, + flavor: i32, + host_info_out: *mut integer_t, + host_info_out_cnt: *mut mach_msg_type_number_t, + ) -> kern_return_t; + fn getloadavg(loadavg: *mut f64, nelem: i32) -> i32; + fn sysctl( + name: *const i32, + namelen: u32, + oldp: *mut c_void, + oldlenp: *mut usize, + newp: *const c_void, + newlen: usize, + ) -> i32; + } + + fn host_port() -> mach_port_t { + static PORT: OnceLock = OnceLock::new(); + // SAFETY: plain Mach trap; cached once so no send rights accumulate. + *PORT.get_or_init(|| unsafe { mach_host_self() }) + } + + fn cpu_counters() -> Option { + let mut info = HostCpuLoadInfo::default(); + let mut count = (std::mem::size_of::() / std::mem::size_of::()) as u32; + // SAFETY: `info` is a writable HOST_CPU_LOAD_INFO buffer and `count` matches its integer_t length. + let rc = unsafe { host_statistics(host_port(), HOST_CPU_LOAD_INFO, (&raw mut info).cast(), &mut count) }; + if rc != 0 { + return None; + } + let user = info.cpu_ticks[0] as u64; + let system = info.cpu_ticks[1] as u64; + let idle = info.cpu_ticks[2] as u64; + let nice = info.cpu_ticks[3] as u64; + let busy = user.saturating_add(system).saturating_add(nice); + Some(CpuCounters::Ticks { busy, total: busy.saturating_add(idle) }) + } + + fn memory_usage() -> Option<(u64, u64)> { + let total = crate::process::total_memory_bytes()?; + let mut page_size: usize = 0; + // SAFETY: `page_size` is writable. + if unsafe { host_page_size(host_port(), &mut page_size) } != 0 || page_size == 0 { + return None; + } + let mut vm = VmStatistics64::default(); + let mut count = (std::mem::size_of::() / std::mem::size_of::()) as u32; + // SAFETY: `vm` is a writable HOST_VM_INFO64 buffer and `count` matches its integer_t length. + let rc = unsafe { host_statistics64(host_port(), HOST_VM_INFO64, (&raw mut vm).cast(), &mut count) }; + if rc != 0 { + return None; + } + // Activity Monitor's "Memory Used": App Memory (internal - purgeable) + Wired + Compressed. + let app_pages = (vm.internal_page_count as u64).saturating_sub(vm.purgeable_count as u64); + let used_pages = app_pages.saturating_add(vm.wire_count as u64).saturating_add(vm.compressor_page_count as u64); + let used = used_pages.saturating_mul(page_size as u64).min(total); + Some((used, total)) + } + + fn load_average() -> Option<[f32; 3]> { + let mut avg = [0.0f64; 3]; + // SAFETY: `avg` holds 3 doubles. + let got = unsafe { getloadavg(avg.as_mut_ptr(), 3) }; + (got == 3).then_some([avg[0] as f32, avg[1] as f32, avg[2] as f32]) + } + + fn net_counters() -> Option { + let mib = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]; + let mut len: usize = 0; + // SAFETY: null buffer queries the required byte count for NET_RT_IFLIST2. + if unsafe { sysctl(mib.as_ptr(), 6, std::ptr::null_mut(), &mut len, std::ptr::null(), 0) } != 0 || len == 0 { + return None; + } + let mut buf = vec![0u8; len.saturating_add(4096)]; + let mut got = buf.len(); + // SAFETY: `buf` has `got` writable bytes. + if unsafe { sysctl(mib.as_ptr(), 6, buf.as_mut_ptr().cast(), &mut got, std::ptr::null(), 0) } != 0 { + return None; + } + buf.truncate(got); + let mut off = 0usize; + let mut rx = 0u64; + let mut tx = 0u64; + let mut any = false; + // `struct if_msghdr2` header is 32 bytes followed by `struct if_data64`, where + // `ifi_ibytes` is at offset 32 + 64 = 96 and `ifi_obytes` at 32 + 72 = 104. + // Note: on 64-bit Darwin `if_data64` starts with 8 u8s, 2 u32s, 1 u64 (`ifi_baudrate`), + // then 5 u64 packet/collision counters (40 bytes) before `ifi_ibytes` & `ifi_obytes`: + // 8 + 8 + 8 + 40 = 64 -> 32 + 64 = 96, 32 + 72 = 104. + while off + 4 <= buf.len() { + let msglen = u16::from_ne_bytes([buf[off], buf[off + 1]]) as usize; + if msglen < 4 || off + msglen > buf.len() { + break; + } + let msg_type = buf[off + 3]; + if msg_type == RTM_IFINFO2 && msglen >= 112 { + let flags = i32::from_ne_bytes(buf[off + 8..off + 12].try_into().unwrap()); + if flags & IFF_LOOPBACK == 0 { + let ibytes = u64::from_ne_bytes(buf[off + 96..off + 104].try_into().unwrap()); + let obytes = u64::from_ne_bytes(buf[off + 104..off + 112].try_into().unwrap()); + rx = rx.saturating_add(ibytes); + tx = tx.saturating_add(obytes); + any = true; + } + } + off += msglen; + } + any.then_some(TransferCounters { read_or_rx_bytes: rx, write_or_tx_bytes: tx }) + } + + pub fn snapshot() -> RawSystemCounters { + let (memory_used_bytes, memory_total_bytes) = match memory_usage() { + Some((u, t)) => (Some(u), Some(t)), + None => (None, crate::process::total_memory_bytes()), + }; + RawSystemCounters { + cpu: cpu_counters(), + cpu_cores: host_cpu_cores(), + load_average: load_average(), + memory_used_bytes, + memory_total_bytes, + net: net_counters(), + disk_io: None, + } + } +} + +#[cfg(windows)] +#[allow(non_snake_case, unsafe_code)] +mod imp { + use super::{CpuCounters, RawSystemCounters, host_cpu_cores}; + + #[repr(C)] + #[derive(Default)] + struct MemoryStatusEx { + dwLength: u32, + dwMemoryLoad: u32, + ullTotalPhys: u64, + ullAvailPhys: u64, + ullTotalPageFile: u64, + ullAvailPageFile: u64, + ullTotalVirtual: u64, + ullAvailVirtual: u64, + ullAvailExtendedVirtual: u64, + } + + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetSystemTimes(idle: *mut u64, kernel: *mut u64, user: *mut u64) -> i32; + fn GlobalMemoryStatusEx(buffer: *mut MemoryStatusEx) -> i32; + } + + fn cpu_counters() -> Option { + let (mut idle, mut kernel, mut user) = (0u64, 0u64, 0u64); + // SAFETY: FILETIME pointers read as packed u64s (`kernel` includes `idle` on Win32). + let ok = unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) }; + if ok == 0 { + return None; + } + let total = kernel.saturating_add(user); + Some(CpuCounters::Ticks { busy: total.saturating_sub(idle), total }) + } + + fn memory_usage() -> Option<(u64, u64)> { + let mut m = MemoryStatusEx { dwLength: std::mem::size_of::() as u32, ..Default::default() }; + // SAFETY: `m` is a writable MEMORYSTATUSEX with `dwLength` set. + let ok = unsafe { GlobalMemoryStatusEx(&mut m) }; + (ok != 0 && m.ullTotalPhys > 0).then(|| (m.ullTotalPhys.saturating_sub(m.ullAvailPhys), m.ullTotalPhys)) + } + + pub fn snapshot() -> RawSystemCounters { + let (memory_used_bytes, memory_total_bytes) = match memory_usage() { + Some((u, t)) => (Some(u), Some(t)), + None => (None, None), + }; + RawSystemCounters { + cpu: cpu_counters(), + cpu_cores: host_cpu_cores(), + load_average: None, + memory_used_bytes, + memory_total_bytes, + net: None, + disk_io: None, + } + } +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +mod imp { + use super::{RawSystemCounters, host_cpu_cores}; + + pub fn snapshot() -> RawSystemCounters { + RawSystemCounters { + cpu: None, + cpu_cores: host_cpu_cores(), + load_average: None, + memory_used_bytes: None, + memory_total_bytes: None, + net: None, + disk_io: None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + #[test] + fn parses_linux_proc_and_cgroup_counters() { + let stat = "cpu 1000 200 300 8000 500 50 25 10 999 888\ncpu0 500 100 150 4000 250 25 12 5 0 0\n"; + assert_eq!(linux_parse::proc_stat_cpu(stat), Some(CpuCounters::Ticks { busy: 1585, total: 10085 })); + + assert_eq!(linux_parse::cgroup_cpu_quota_cores("max 100000\n"), None); + assert_eq!(linux_parse::cgroup_cpu_quota_cores("250000 100000\n"), Some(2.5)); + assert_eq!( + linux_parse::cgroup_cpu_usage_usec("usage_usec 482910\nuser_usec 300000\nsystem_usec 182910\n"), + Some(482910) + ); + + let mem = "MemTotal: 16384000 kB\nMemFree: 2048000 kB\nMemAvailable: 6144000 kB\n"; + assert_eq!(linux_parse::meminfo(mem), Some((10_240_000 * 1024, 16_384_000 * 1024))); + + // Container memory quota narrower than host RAM subtracts reclaimable `inactive_file`. + let cg = linux_parse::cgroup_memory( + "4294967296\n", + "2147483648\n", + Some("anon 1073741824\ninactive_file 536870912\n"), + Some(16 * 1024 * 1024 * 1024), + ); + assert_eq!(cg, Some((1_610_612_736, 4_294_967_296))); + assert_eq!(linux_parse::cgroup_memory("max\n", "100\n", None, Some(1000)), None); + + assert_eq!(linux_parse::loadavg("0.42 1.25 2.50 2/812 9912\n"), Some([0.42, 1.25, 2.5])); + + let net = "\ +Inter-| Receive | Transmit + face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed + lo: 99999 10 0 0 0 0 0 0 99999 10 0 0 0 0 0 0 + eth0: 1048576 500 0 0 0 0 0 0 524288 400 0 0 0 0 0 0 + wlan0: 4096 10 0 0 0 0 0 0 2048 5 0 0 0 0 0 0 +"; + assert_eq!( + linux_parse::net_dev(net), + Some(TransferCounters { read_or_rx_bytes: 1_052_672, write_or_tx_bytes: 526_336 }) + ); + + let disks = "\ + 7 0 loop0 10 0 80 1 0 0 0 0 0 1 1 + 259 0 nvme0n1 100 0 2000 10 50 0 1000 20 0 15 30 + 259 1 nvme0n1p1 90 0 1800 9 45 0 900 18 0 14 27 + 8 0 sda 10 0 400 2 5 0 200 4 0 3 6 + 8 1 sda1 10 0 400 2 5 0 200 4 0 3 6 +"; + assert_eq!( + linux_parse::diskstats(disks), + Some(TransferCounters { read_or_rx_bytes: 2400 * 512, write_or_tx_bytes: 1200 * 512 }) + ); + + let io_stat = "259:0 rbytes=10240 wbytes=20480 rios=1 wios=2\n8:0 rbytes=512 wbytes=1024\n"; + assert_eq!( + linux_parse::cgroup_io_stat(io_stat), + Some(TransferCounters { read_or_rx_bytes: 10752, write_or_tx_bytes: 21504 }) + ); + } + + #[test] + fn sampler_computes_rates_and_throttles_burst_polls() { + let mut sampler = SystemSampler::default(); + let t0 = Instant::now(); + let first = sampler.record( + RawSystemCounters { + cpu: Some(CpuCounters::Ticks { busy: 100, total: 1000 }), + cpu_cores: 8, + load_average: Some([1.0, 0.5, 0.25]), + memory_used_bytes: Some(4 << 30), + memory_total_bytes: Some(16 << 30), + net: Some(TransferCounters { read_or_rx_bytes: 1_000, write_or_tx_bytes: 2_000 }), + disk_io: Some(TransferCounters { read_or_rx_bytes: 4_000, write_or_tx_bytes: 8_000 }), + }, + t0, + ); + assert_eq!(first.cpu_percent, None); + assert_eq!(first.net_rx_bytes_per_sec, None); + + let second = sampler.record( + RawSystemCounters { + cpu: Some(CpuCounters::Ticks { busy: 350, total: 2000 }), + cpu_cores: 8, + load_average: Some([1.5, 0.75, 0.3]), + memory_used_bytes: Some(6 << 30), + memory_total_bytes: Some(16 << 30), + net: Some(TransferCounters { read_or_rx_bytes: 21_000, write_or_tx_bytes: 12_000 }), + disk_io: Some(TransferCounters { read_or_rx_bytes: 104_000, write_or_tx_bytes: 48_000 }), + }, + t0 + Duration::from_secs(2), + ); + assert_eq!(second.cpu_percent, Some(25.0)); + assert_eq!(second.net_rx_bytes_per_sec, Some(10_000.0)); + assert_eq!(second.net_tx_bytes_per_sec, Some(5_000.0)); + assert_eq!(second.disk_read_bytes_per_sec, Some(50_000.0)); + assert_eq!(second.disk_write_bytes_per_sec, Some(20_000.0)); + + // A second window polling 100 ms later reuses the rate window rather than dividing over 100 ms. + let burst = sampler.record( + RawSystemCounters { + cpu: Some(CpuCounters::Ticks { busy: 360, total: 2020 }), + cpu_cores: 8, + load_average: Some([1.6, 0.75, 0.3]), + memory_used_bytes: Some(7 << 30), + memory_total_bytes: Some(16 << 30), + net: Some(TransferCounters { read_or_rx_bytes: 21_500, write_or_tx_bytes: 12_100 }), + disk_io: Some(TransferCounters { read_or_rx_bytes: 104_000, write_or_tx_bytes: 48_000 }), + }, + t0 + Duration::from_millis(2100), + ); + assert_eq!(burst.cpu_percent, Some(25.0)); + assert_eq!(burst.memory_used_bytes, Some(7 << 30)); + } + + #[test] + fn live_os_snapshot_reports_plausible_values() { + let s = snapshot(); + assert!(s.cpu_cores >= 1); + if cfg!(any(target_os = "macos", target_os = "linux", windows)) { + assert!(s.cpu.is_some()); + let used = s.memory_used_bytes.expect("memory_used_bytes"); + let total = s.memory_total_bytes.expect("memory_total_bytes"); + assert!(used > 0 && used <= total, "{used} / {total}"); + } + if cfg!(any(target_os = "macos", target_os = "linux")) { + let load = s.load_average.expect("load_average"); + assert!(load.iter().all(|v| v.is_finite() && *v >= 0.0), "{load:?}"); + } + if cfg!(target_os = "macos") { + let net = s.net.expect("macos net counters"); + assert!(net.read_or_rx_bytes > 0 || net.write_or_tx_bytes > 0, "{net:?}"); + } + } +} diff --git a/docs/en/guide/remote/ssh.mdx b/docs/en/guide/remote/ssh.mdx index a1a50b424c..de3ad28726 100644 --- a/docs/en/guide/remote/ssh.mdx +++ b/docs/en/guide/remote/ssh.mdx @@ -95,6 +95,7 @@ After the project opens you are asked whether to trust it, as for a local folder - The window title ends with the host, and the status bar shows **SSH: ``**. Clicking it opens the **Remote Development** dialog. +- Next to **SSH: ``**, the **Remote Host Resources** indicator shows CPU and memory usage of the remote host (and highlights network or disk pressure when saturated). Click it — or run **Show Remote Host Resources** — to open a dashboard with rolling CPU, memory, network (including SSH round-trip latency) and disk graphs, plus running remote processes with **End Process**. - Remote projects appear in the recent projects list on the Welcome screen, so you can reopen them from there. - Language servers, debuggers and other tools that OpenIDEA installs go to the remote host, under `~/.openidea/data`. diff --git a/docs/zh/guide/remote/ssh.mdx b/docs/zh/guide/remote/ssh.mdx index b771c8ae17..efc090898a 100644 --- a/docs/zh/guide/remote/ssh.mdx +++ b/docs/zh/guide/remote/ssh.mdx @@ -74,6 +74,7 @@ SSH 代理使用 `IdentityAgent` 指定的那个,未指定时使用登录 shel ## 在远程窗口中工作 - 窗口标题末尾显示主机名,状态栏显示 **SSH: ``**,点击它会打开**远程开发**对话框。 +- **SSH: ``** 旁的**远程主机资源**微件显示远程主机的 CPU 和内存占用(在网络或磁盘饱和时高亮提示)。点击该微件(或执行**显示远程主机资源**操作)可打开资源面板,查看 CPU、内存、网络(含 SSH 往返延迟)和磁盘曲线,以及远程进程列表和**结束进程**操作。 - 远程项目会出现在欢迎页的最近项目列表中,可以从那里重新打开。 - OpenIDEA 安装的语言服务器、调试器等工具都装在远程主机的 `~/.openidea/data` 下。 - 快捷键、外观、编辑器字体和配色方案保留在本机;项目和工具相关的设置保存在主机上。 diff --git a/e2e/remoteResources.spec.ts b/e2e/remoteResources.spec.ts new file mode 100644 index 0000000000..e89f988ff8 --- /dev/null +++ b/e2e/remoteResources.spec.ts @@ -0,0 +1,155 @@ +import { expect, openFromTree, stubDesktop, test } from "./fixtures"; + +const MB = 1024 * 1024; +const GB = 1024 * MB; + +test("shows compact remote CPU+RAM pill beside SSH status and opens detailed dashboard", async ({ + workbench: page, +}) => { + await openFromTree(page, "README.md"); + await stubDesktop(page); + + const statusBar = page.getByRole("contentinfo", { name: "Status bar" }); + await expect(statusBar.getByRole("button", { name: /Remote host resources:/ })).toHaveCount(0); + + await page.evaluate(async () => { + const MB = 1024 * 1024; + const GB = 1024 * MB; + const remoteMod = "/src/platform/remote.ts"; + const projectMod = "/src/platform/project.ts"; + const { enableRemote } = await import(/* @vite-ignore */ remoteMod); + const { useProject } = await import(/* @vite-ignore */ projectMod); + + let step = 0; + const series = [ + { cpu: 22, mem: 5.8 * GB, rx: 420 * 1024, tx: 120 * 1024, r: 2 * MB, w: 6 * MB }, + { cpu: 38, mem: 6.2 * GB, rx: 1.8 * MB, tx: 340 * 1024, r: 8 * MB, w: 14 * MB }, + { cpu: 54, mem: 6.6 * GB, rx: 3.4 * MB, tx: 610 * 1024, r: 18 * MB, w: 24 * MB }, + { cpu: 41, mem: 6.4 * GB, rx: 1.2 * MB, tx: 210 * 1024, r: 4 * MB, w: 9 * MB }, + ]; + let endedLsp = false; + + window.__ipc.handlers.remote_invoke = ({ cmd, args }) => { + const parsed = JSON.parse(String(args ?? "{}")) as { includeProcesses?: boolean; pid?: number }; + if (cmd === "host_end_process") { + if (parsed.pid === 2048) endedLsp = true; + return JSON.stringify(true); + } + if (cmd === "host_metrics") { + const pt = series[Math.min(step++, series.length - 1)]!; + return JSON.stringify({ + cpuPercent: pt.cpu, + cpuCores: 16, + loadAverage: [1.42, 1.18, 0.95], + memoryUsedBytes: pt.mem, + memoryTotalBytes: 16 * GB, + netRxBytesPerSec: pt.rx, + netTxBytesPerSec: pt.tx, + diskReadBytesPerSec: pt.r, + diskWriteBytesPerSec: pt.w, + diskAvailableBytes: 84 * GB, + diskTotalBytes: 200 * GB, + uptimeMs: 9_840_000, + processes: parsed.includeProcesses + ? [ + { + category: "app", + label: "Backend", + detail: null, + pid: 1024, + processes: 1, + bytes: 54 * MB, + cpuPercent: 2.1, + }, + ...(endedLsp + ? [] + : [ + { + category: "languageServer", + label: "rust-analyzer", + detail: "acme-api", + pid: 2048, + processes: 2, + bytes: 1450 * MB, + cpuPercent: 34.5, + }, + ]), + { + category: "process", + label: "pnpm run dev", + detail: "Run", + pid: 3072, + processes: 4, + bytes: 410 * MB, + cpuPercent: 11.2, + }, + ] + : [], + externalProcesses: parsed.includeProcesses + ? [{ pid: 9100, name: "dockerd", cpuPercent: 5.4, memoryBytes: 780 * MB }] + : [], + }); + } + return JSON.stringify(null); + }; + + enableRemote({ + target: { kind: "ssh", config: "thinkpad" }, + root: useProject.getState().project?.root ?? "/home/deng/acme-api", + host: "deng@deng-thinkpad.local", + os: "linux", + commands: ["host_metrics", "host_end_process"], + idlePolicy: null, + takenOver: false, + }); + }); + + await expect(statusBar.getByRole("button", { name: "SSH: deng@deng-thinkpad.local" })).toBeVisible(); + const pill = statusBar.getByRole("button", { name: /Remote host resources:/ }); + await expect(pill).toBeVisible(); + await expect(pill).toContainText("22% · 5.8G"); + + // Sits immediately to the right of the Remote Host status bar item. + const leftOrder = await statusBar + .locator(":scope > [data-status-item]") + .evaluateAll((els) => els.filter((e) => e.getClientRects().length > 0).map((e) => e.dataset.statusItem)); + expect(leftOrder.slice(0, 2)).toEqual(["remote.location", "remote.resources"]); + + await pill.click(); + const dialog = page.getByRole("dialog", { name: "Remote Host Resources" }); + await expect(dialog).toBeVisible(); + await expect(dialog.getByText("SSH: deng@deng-thinkpad.local")).toBeVisible(); + await expect(dialog.getByText("16 cores · load 1.42 · 1.18 · 0.95")).toBeVisible(); + await expect(dialog.getByText("84 GB free")).toBeVisible(); + await expect(dialog.getByRole("group", { name: "Language servers" })).toContainText("rust-analyzer"); + await expect(dialog.getByRole("group", { name: "Other host processes" })).toContainText("dockerd"); + + // Hover, cancel confirmation first, then confirm ending the remote language server process. + const lspRow = dialog.locator("[title='PID 2048 · 2 processes']"); + await lspRow.hover(); + await lspRow.getByRole("button", { name: "End Process rust-analyzer" }).click(); + const confirmDialog = page.getByRole("dialog", { name: "End Remote Process" }); + await expect(confirmDialog).toContainText("End 'rust-analyzer' (PID 2048) and its child processes"); + await confirmDialog.getByRole("button", { name: "Cancel" }).click(); + await expect(confirmDialog).toHaveCount(0); + await expect(dialog.getByRole("group", { name: "Language servers" })).toContainText("rust-analyzer"); + + await lspRow.hover(); + await lspRow.getByRole("button", { name: "End Process rust-analyzer" }).click(); + await page.getByRole("dialog", { name: "End Remote Process" }).getByRole("button", { name: "End Process" }).click(); + await expect(dialog.getByRole("group", { name: "Language servers" })).toHaveCount(0); + + // Escape dismisses the popover while keeping the status bar pill live. + await page.keyboard.press("Escape"); + await expect(dialog).toHaveCount(0); + await expect(pill).toBeVisible(); + + // Disconnecting removes the remote resource pill cleanly. + await page.evaluate(async () => { + const remoteMod = "/src/platform/remote.ts"; + const { disableRemote } = await import(/* @vite-ignore */ remoteMod); + disableRemote(); + }); + await expect(pill).toHaveCount(0); + expect(GB).toBeGreaterThan(MB); +}); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 75e82a907f..d38d21a20a 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -337,6 +337,8 @@ history_list always project_host bin history_list_dir always project_host bindings async history_put_label always project_host bindings sync history_restore always project_host bindings async +host_end_process trusted project_host bindings async +host_metrics always project_host bindings async http_curl trusted project_host bindings async http_environment_file trusted project_host bindings async http_environments trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 2594135d6a..e3e74f7a61 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -841,6 +841,16 @@ export const commands = { * file and its folders); an open editor updates in place. */ historyRestore: (path: string, id: string) => typedError(__TAURI_INVOKE("history_restore", { path, id })), + /** + * Ends a child process started by this OpenIDEA host (language server, run, terminal, + * debug adapter or agent) and its descendants; refuses processes outside this host's tree. + */ + hostEndProcess: (pid: number) => typedError(__TAURI_INVOKE("host_end_process", { pid })), + /** + * Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when + * `include_processes` is true, the process breakdown of OpenIDEA and top host processes. + */ + hostMetrics: (includeProcesses: boolean) => typedError(__TAURI_INVOKE("host_metrics", { includeProcesses })), /** * Convert to cURL and Copy: request `index` of `text` (the editor buffer of `path`), with * the variables of `env` substituted, as a cURL command. @@ -8421,6 +8431,46 @@ export type HistoryTip = { commit: string, }; +/** Snapshot of host-wide CPU, memory, network, disk and process usage. */ +export type HostMetrics = { + /** Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample. */ + cpuPercent: number | null, + /** Logical CPU cores available to this host or container. */ + cpuCores: number, + /** Unix 1m, 5m, 15m load averages; `null` on Windows. */ + loadAverage: [(number | null), (number | null), (number | null)] | null, + /** Host or container memory in use, in bytes. */ + memoryUsedBytes: number | null, + /** Total physical (or container limit) memory, in bytes. */ + memoryTotalBytes: number | null, + /** Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS. */ + netRxBytesPerSec: number | null, + /** Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS. */ + netTxBytesPerSec: number | null, + /** Bytes/s read from block storage; `null` on the first sample or unsupported OS. */ + diskReadBytesPerSec: number | null, + /** Bytes/s written to block storage; `null` on the first sample or unsupported OS. */ + diskWriteBytesPerSec: number | null, + /** Free bytes available to the user on the project volume (or `$HOME` fallback). */ + diskAvailableBytes: number | null, + /** Total capacity in bytes of the project volume (or `$HOME` fallback). */ + diskTotalBytes: number | null, + /** Uptime of the backend process in milliseconds. */ + uptimeMs: number | null, + /** OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`). */ + processes: ProcessMemory[], + /** Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`). */ + externalProcesses: HostProcess[], +}; + +/** One process outside OpenIDEA's own process tree on the host (read-only in the UI). */ +export type HostProcess = { + pid: number, + name: string, + cpuPercent: number | null, + memoryBytes: number | null, +}; + /** What triggered a hot reload; `flutter debug_adapter` takes it as `reason`. */ export type HotReloadReason = "manual" | "save"; diff --git a/src/features/remote-dev/RemoteResources.module.css b/src/features/remote-dev/RemoteResources.module.css new file mode 100644 index 0000000000..44af8d89b1 --- /dev/null +++ b/src/features/remote-dev/RemoteResources.module.css @@ -0,0 +1,351 @@ +.pill { + gap: var(--space-1-5); + font-variant-numeric: tabular-nums; +} + +.meter { + display: inline-flex; + align-items: flex-end; + gap: var(--space-0-5); + height: 12px; + padding: 1px; + border-radius: 2px; + background: color-mix(in srgb, var(--border-strong) 45%, transparent); + flex: none; +} + +.meterTrack { + position: relative; + width: 3px; + height: 10px; + border-radius: 1px; + background: color-mix(in srgb, var(--fg-faint) 35%, transparent); + overflow: hidden; +} + +.meterFill { + position: absolute; + inset: auto 0 0 0; + border-radius: 1px; + background: var(--fg-muted); + transition: height 180ms ease-out; +} + +.levelWarn { + color: var(--warning); +} + +.levelDanger { + color: var(--danger); +} + +.meterFillWarn { + background: var(--warning); +} + +.meterFillDanger { + background: var(--danger); +} + +.pillText { + font-size: var(--fs-small); +} + +.badge { + display: inline-flex; + align-items: center; + padding: 0 4px; + height: 15px; + border-radius: var(--radius-small); + font-size: var(--fs-tiny); + background: color-mix(in srgb, var(--warning) 18%, transparent); + color: var(--warning); +} + +.badgeDanger { + background: color-mix(in srgb, var(--danger) 18%, transparent); + color: var(--danger); +} + +/* Popover dashboard */ +.panel { + width: 420px; + max-height: min(560px, calc(100vh - 64px)); + overflow-y: auto; + padding: 8px 0 6px; + font-family: var(--font-ui); + font-size: var(--fs-ui); + color: var(--fg); +} + +.header { + display: flex; + align-items: center; + gap: var(--space-2); + padding: 2px 12px 8px; +} + +.hostInfo { + display: flex; + align-items: baseline; + gap: var(--space-1-5); + min-width: 0; + flex: 1; +} + +.hostTitle { + font-weight: 600; + color: var(--fg-strong); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.uptime { + color: var(--fg-subtle); + font-size: var(--fs-tiny); + flex: none; +} + +.rttBadge { + flex: none; + padding: 1px 6px; + border-radius: var(--radius-small); + background: var(--bg-elev); + border: 1px solid var(--border-popup); + font-family: var(--font-mono); + font-size: var(--fs-tiny); + color: var(--fg-secondary); + font-variant-numeric: tabular-nums; +} + +.rttWarn { + color: var(--warning); + border-color: color-mix(in srgb, var(--warning) 45%, var(--border-popup)); +} + +.rttDanger { + color: var(--danger); + border-color: color-mix(in srgb, var(--danger) 45%, var(--border-popup)); +} + +.grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-2); + padding: 0 12px 8px; +} + +.card { + display: flex; + flex-direction: column; + gap: var(--space-0-5); + padding: 8px 10px; + border-radius: var(--radius-control); + background: var(--bg-elev); + border: 1px solid var(--border-popup); + min-width: 0; +} + +.cardTop { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-1-5); + min-width: 0; +} + +.cardTitle { + flex: none; + font-size: var(--fs-tiny); + color: var(--fg-subtle); +} + +.cardValue { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + font-family: var(--font-mono); + font-size: var(--fs-small); + color: var(--fg-strong); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.cardSub { + font-size: var(--fs-tiny); + color: var(--fg-muted); + font-variant-numeric: tabular-nums; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sparkline { + width: 100%; + height: 28px; + display: block; + margin-top: 2px; +} + +.sparkStroke { + fill: none; + stroke: var(--info); + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sparkArea { + fill: color-mix(in srgb, var(--info) 18%, transparent); +} + +.sparkWarn .sparkStroke { + stroke: var(--warning); +} + +.sparkWarn .sparkArea { + fill: color-mix(in srgb, var(--warning) 20%, transparent); +} + +.sparkDanger .sparkStroke { + stroke: var(--danger); +} + +.sparkDanger .sparkArea { + fill: color-mix(in srgb, var(--danger) 22%, transparent); +} + +.capacityTrack { + width: 100%; + height: 5px; + margin-top: 4px; + border-radius: 3px; + background: color-mix(in srgb, var(--fg-faint) 30%, transparent); + overflow: hidden; +} + +.capacityFill { + height: 100%; + border-radius: 3px; + background: var(--info); +} + +.capacityWarn { + background: var(--warning); +} + +.capacityDanger { + background: var(--danger); +} + +/* Process breakdown (matches perf.module.css layout) */ +.section { + margin-top: 4px; + padding-top: 4px; + border-top: 1px solid var(--border-popup); +} + +.columns { + display: flex; + align-items: center; + gap: var(--space-2); + padding: 2px 4px 4px 12px; + font-size: var(--fs-tiny); + color: var(--fg-subtle); +} + +.columnsTitle { + flex: 1; +} + +.groupRow, +.processRow { + display: flex; + align-items: center; + min-height: var(--h-list-row); + padding: 0 4px 0 12px; + gap: var(--space-2); +} + +.indented { + padding-left: 22px; +} + +.groupTitle { + flex: 1; + color: var(--fg-emphasis); + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.rowLabel { + flex: 1; + color: var(--fg-secondary); + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.detail { + margin-left: 6px; + color: var(--fg-subtle); +} + +.metricCol { + flex: none; + text-align: right; + font-family: var(--font-mono); + font-size: var(--fs-small); + color: var(--fg-emphasis); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.cpu, +.memory { + flex: none; + text-align: right; +} + +.cpu { + width: 48px; +} + +.memory { + width: 64px; +} + +.end { + flex: none; + display: flex; + justify-content: center; + width: 20px; +} + +.end button { + opacity: 0; +} + +.processRow:hover .end button, +.end button:focus-visible { + opacity: 1; +} + +.error { + padding: 4px 12px; + color: var(--danger); + font-size: var(--fs-small); +} + +.actions { + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--space-1-5); + margin-top: 4px; + padding: 6px 12px 2px; + border-top: 1px solid var(--border-popup); +} diff --git a/src/features/remote-dev/RemoteResources.tsx b/src/features/remote-dev/RemoteResources.tsx new file mode 100644 index 0000000000..77f1e6907d --- /dev/null +++ b/src/features/remote-dev/RemoteResources.tsx @@ -0,0 +1,463 @@ +import { useEffect, useRef, useState } from "react"; +import clsx from "clsx"; +import { executeAction } from "@/platform/actions"; +import { t, tx } from "@/platform/i18n"; +import { isTauri, type HostMetrics, type HostProcess } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; +import { BarButton, Button, Dialog, IconButton, Popup, showContextMenu, T } from "@/ui"; +import { formatBytes, formatMs, formatPercent, formatSize, formatUptime } from "@/features/perf/format"; +import { memorySections, type BreakdownRow } from "@/features/perf/memory"; +import { startPolling } from "@/features/perf/poll"; +import { remoteBadge } from "./RemoteStatus"; +import { + canMonitorRemoteHost, + compactResourceText, + diskUsedPercent, + endRemoteProcess, + formatRate, + memoryPercent, + refreshRemoteResources, + REMOTE_DASHBOARD_POLL_MS, + REMOTE_METRICS_POLL_MS, + resourceTooltip, + sparklineGeometry, + summarizePressure, + useRemoteResources, + type PressureLevel, + type ResourceSample, +} from "./resources"; +import styles from "./RemoteResources.module.css"; + +export const REMOTE_RESOURCES_WIDGET = { + id: "remote.resources", + title: "Remote Host Resources", + defaultVisible: true, +} as const; + +const SPARK_W = 176; +const SPARK_H = 28; +const MIN_NET_CEILING_BPS = 256 * 1024; +const MIN_DISK_CEILING_BPS = 512 * 1024; + +function barHeightPercent(percent: number | null): string { + if (percent == null || !Number.isFinite(percent) || percent <= 0) return "0%"; + return `${Math.min(100, Math.max(15, Math.round(percent)))}%`; +} + +function fillLevelClass(level: PressureLevel): string | undefined { + if (level === "danger") return styles.meterFillDanger; + if (level === "warn") return styles.meterFillWarn; + return undefined; +} + +function sparkLevelClass(level: PressureLevel): string | undefined { + if (level === "danger") return styles.sparkDanger; + if (level === "warn") return styles.sparkWarn; + return undefined; +} + +function Sparkline({ + values, + level = "normal", + fixedMax, + minCeiling, +}: { + values: ReadonlyArray; + level?: PressureLevel; + fixedMax?: number; + minCeiling?: number; +}) { + const paths = sparklineGeometry(values, SPARK_W, SPARK_H, { fixedMax, minCeiling }); + return ( + + ); +} + +export function RemoteResources() { + const session = useRemote((s) => s.session); + const lost = useRemote((s) => s.lost !== null); + const metrics = useRemoteResources((s) => s.metrics); + const rttMs = useRemoteResources((s) => s.rttMs); + const history = useRemoteResources((s) => s.history); + const open = useRemoteResources((s) => s.popupOpen); + const ref = useRef(null); + + const active = Boolean(session && !lost && canMonitorRemoteHost(session)); + + useEffect(() => { + if (!isTauri() || !active) return; + const intervalMs = open ? REMOTE_DASHBOARD_POLL_MS : REMOTE_METRICS_POLL_MS; + return startPolling(() => void refreshRemoteResources(open), { intervalMs }); + }, [active, open]); + + if (!active || !session) return null; + + const pressure = summarizePressure(metrics, rttMs); + const memPct = memoryPercent(metrics); + const tooltip = resourceTooltip(metrics, rttMs); + const compact = compactResourceText(metrics); + + return ( + <> + useRemoteResources.setState({ popupOpen: !open })} + onContextMenu={(e) => { + e.preventDefault(); + showContextMenu(e, [ + { kind: "action", action: "remote.showResources" }, + { kind: "action", action: "remote.reloadEnvironment" }, + { kind: "separator" }, + { kind: "action", action: "remote.disconnect" }, + { kind: "action", action: "remote.stopBackend" }, + ]); + }} + > + + useRemoteResources.setState({ popupOpen: false })} + aria-label="Remote Host Resources" + > + + + + ); +} + +function ProcessRow({ + row, + trusted, + onRequestEnd, +}: { + row: BreakdownRow; + trusted: boolean; + onRequestEnd: (row: BreakdownRow) => void; +}) { + const title = row.processes > 1 ? tx`PID ${row.pid} · ${row.processes} processes` : tx`PID ${row.pid}`; + return ( +
+ + {row.label} + {row.detail && {row.detail}} + + {row.cpu} + {row.value} + + {row.endable && trusted && ( + onRequestEnd(row)} + /> + )} + +
+ ); +} + +function ExternalProcessRow({ proc }: { proc: HostProcess }) { + return ( +
+ {proc.name} + {formatPercent(proc.cpuPercent)} + {formatSize(proc.memoryBytes)} + +
+ ); +} + +export function RemoteResourcesDashboard({ + hostLabel, + metrics: m, + rttMs, + history, +}: { + hostLabel: string; + metrics: HostMetrics | null; + rttMs: number | null; + history: ReadonlyArray; +}) { + const error = useRemoteResources((s) => s.error); + const trusted = useProject((s) => s.project?.trusted !== false); + const [confirmingRow, setConfirmingRow] = useState(null); + const pressure = summarizePressure(m, rttMs); + const memPct = memoryPercent(m); + const diskPct = diskUsedPercent(m); + const sections = memorySections(m?.processes ?? []); + const external = m?.externalProcesses ?? []; + + const loadText = + m?.loadAverage && m.loadAverage.every((v) => v != null) + ? m.loadAverage.map((v) => v!.toFixed(2)).join(" · ") + : null; + const cpuCores = m?.cpuCores ?? 0; + const cpuSub = + cpuCores <= 0 + ? tx("Sampling…") + : loadText + ? cpuCores === 1 + ? tx`1 core · load ${loadText}` + : tx`${cpuCores} cores · load ${loadText}` + : cpuCores === 1 + ? tx("1 core") + : tx`${cpuCores} cores`; + + const memValue = + m?.memoryTotalBytes != null + ? `${formatBytes(m.memoryUsedBytes)} / ${formatBytes(m.memoryTotalBytes)}` + : formatSize(m?.memoryUsedBytes); + const memAvail = + m?.memoryTotalBytes != null && m.memoryUsedBytes != null + ? Math.max(0, m.memoryTotalBytes - m.memoryUsedBytes) + : null; + const memSub = memPct != null && memAvail != null ? tx`${formatPercent(memPct)} · ${formatSize(memAvail)} free` : "–"; + + const hasNetRates = m?.netRxBytesPerSec != null || m?.netTxBytesPerSec != null; + const netTotal = hasNetRates ? (m?.netRxBytesPerSec ?? 0) + (m?.netTxBytesPerSec ?? 0) : null; + const netValue = hasNetRates ? formatRate(netTotal) : "–"; + const netSub = hasNetRates + ? `↓ ${formatBytes(m?.netRxBytesPerSec)}/s · ↑ ${formatBytes(m?.netTxBytesPerSec)}/s${rttMs != null ? ` · ${formatMs(rttMs)}` : ""}` + : rttMs != null + ? tx`SSH / RPC RTT ${formatMs(rttMs)}` + : "–"; + + const hasDiskIo = m?.diskReadBytesPerSec != null || m?.diskWriteBytesPerSec != null; + const diskValue = m?.diskAvailableBytes != null ? tx`${formatSize(m.diskAvailableBytes)} free` : "–"; + const diskSub = hasDiskIo + ? `R ${formatBytes(m?.diskReadBytesPerSec)}/s · W ${formatBytes(m?.diskWriteBytesPerSec)}/s` + : m?.diskTotalBytes != null && diskPct != null + ? tx`${formatPercent(diskPct)} of ${formatSize(m.diskTotalBytes)} used` + : "–"; + + return ( +
+
+
+ {hostLabel} + {m?.uptimeMs != null && {tx`up ${formatUptime(m.uptimeMs)}`}} +
+ {rttMs != null && ( + + {tx`RTT ${formatMs(rttMs)}`} + + )} +
+ +
+
+
+ + CPU + + + {formatPercent(m?.cpuPercent)} + +
+ {cpuSub} + s.cpuPercent)} level={pressure.cpuLevel} fixedMax={100} /> +
+ +
+
+ + Memory + + + {memValue} + +
+ {memSub} + s.memoryPercent)} level={pressure.memoryLevel} fixedMax={100} /> +
+ +
+
+ + Network + + {netValue} +
+ {netSub} + s.netBytesPerSec)} + level={pressure.rttLevel} + minCeiling={MIN_NET_CEILING_BPS} + /> +
+ +
+
+ + Disk + + + {diskValue} + +
+ {diskSub} + {hasDiskIo ? ( + s.diskBytesPerSec)} + level={pressure.diskLevel} + minCeiling={MIN_DISK_CEILING_BPS} + /> + ) : ( + +
+ + {(sections.length > 0 || external.length > 0) && ( +
+
+ + Processes + + + CPU + + + Memory + + +
+ {sections.map((sec) => ( +
+
+ {tx(sec.title)} + {sec.cpu} + {sec.total} + +
+ {sec.rows.map((r) => ( + + ))} +
+ ))} + {external.length > 0 && ( +
+
+ + Other host processes + + + + +
+ {external.map((proc) => ( + + ))} +
+ )} +
+ )} + + {error &&
{error}
} + +
+ + +
+ + setConfirmingRow(null)} + buttons={[ + { + label: tx("End Process"), + role: "default", + autoFocus: true, + onClick: () => { + const target = confirmingRow; + setConfirmingRow(null); + if (target) void endRemoteProcess(target.pid); + }, + }, + { label: t("common.cancel"), role: "cancel" }, + ]} + > + {confirmingRow && + (confirmingRow.processes > 1 + ? tx`End '${confirmingRow.label}' (PID ${confirmingRow.pid}) and its child processes on the remote host?` + : tx`End '${confirmingRow.label}' (PID ${confirmingRow.pid}) on the remote host?`)} + +
+ ); +} diff --git a/src/features/remote-dev/RemoteStatus.tsx b/src/features/remote-dev/RemoteStatus.tsx index 4d0d2ddb64..75ace9134d 100644 --- a/src/features/remote-dev/RemoteStatus.tsx +++ b/src/features/remote-dev/RemoteStatus.tsx @@ -3,6 +3,7 @@ import { tx } from "@/platform/i18n"; import type { RemoteSession } from "@/platform/ipc"; import { useRemote } from "@/platform/remote"; import { BarButton, Icon, showContextMenu, Spinner } from "@/ui"; +import { canMonitorRemoteHost } from "./resources"; import styles from "./RemoteDev.module.css"; const BADGE: Record = { @@ -52,6 +53,7 @@ export function RemoteStatus() { e.preventDefault(); showContextMenu(e, [ { kind: "action", action: "remote.connect" }, + ...(canMonitorRemoteHost(session) ? [{ kind: "action" as const, action: "remote.showResources" }] : []), { kind: "action", action: "remote.reloadEnvironment" }, { kind: "separator" }, { kind: "action", action: "remote.disconnect" }, diff --git a/src/features/remote-dev/index.ts b/src/features/remote-dev/index.ts index 4c26ea054d..de2d217574 100644 --- a/src/features/remote-dev/index.ts +++ b/src/features/remote-dev/index.ts @@ -7,17 +7,20 @@ import { registerActions } from "@/platform/actions"; import { disconnectRemote, provideBackendBusyPrompt, stopRemoteBackend, useRemote } from "@/platform/remote"; import { lazyComponent } from "@/ui"; import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions"; +import { isStatusItemVisible, setStatusWidgetAvailable, setStatusWidgetVisible } from "@/workbench/statusBarWidgets"; import { confirm } from "@/workbench/messages"; import { tx } from "@/platform/i18n"; -import { confirmLeaveProject } from "@/platform/project"; +import { confirmLeaveProject, useProject } from "@/platform/project"; import { ConnectHost } from "./ConnectDialog"; import { installConnectHandoff, showConnect } from "./connectWindow"; import { reopenInContainer } from "./container"; import { installDirenvNotifications, reloadEnvironment } from "./environment"; +import { REMOTE_RESOURCES_WIDGET, RemoteResources } from "./RemoteResources"; import { RemoteStatus } from "./RemoteStatus"; import { closeConnectDialog } from "./model"; import { restorePorts, usePorts } from "./ports"; import { installReconnect, reconnectNow } from "./reconnect"; +import { canMonitorRemoteHost, refreshRemoteResources, useRemoteResources } from "./resources"; /** Forwarded ports are available while this window is connected to an SSH host, a WSL distribution or a dev container. */ function trackPortsWindow(): () => void { @@ -57,7 +60,21 @@ function trackPortsWindow(): () => void { } export function activate(): () => void { + const syncResourcesWidget = () => { + const { session, lost } = useRemote.getState(); + setStatusWidgetAvailable( + REMOTE_RESOURCES_WIDGET.id, + Boolean(session && lost === null && canMonitorRemoteHost(session)), + ); + }; + syncResourcesWidget(); + const offResourcesAvailability = useRemote.subscribe(syncResourcesWidget); + const disposers = [ + () => { + offResourcesAvailability(); + setStatusWidgetAvailable(REMOTE_RESOURCES_WIDGET.id, false); + }, provideBackendBusyPrompt(() => confirm({ title: tx("Stop Remote Backend"), @@ -80,7 +97,30 @@ export function activate(): () => void { priority: 100, component: RemoteStatus, }), + registerStatusItem({ + ...REMOTE_RESOURCES_WIDGET, + align: "left", + priority: 99, + component: RemoteResources, + }), registerActions([ + { + id: "remote.showResources", + title: "Show Remote Host Resources", + description: "Shows CPU, memory, network, disk and running processes of the remote host.", + category: "View", + icon: "info", + keywords: ["ssh", "remote", "cpu", "memory", "ram", "network", "disk", "processes", "metrics", "resources"], + when: "projectRemote && !remoteConnectionLost", + run: async () => { + const overrides = useProject.getState().settings?.appearance?.statusBarWidgets; + if (!isStatusItemVisible(REMOTE_RESOURCES_WIDGET, overrides)) { + await setStatusWidgetVisible(REMOTE_RESOURCES_WIDGET.id, true); + } + await refreshRemoteResources(true); + useRemoteResources.setState({ popupOpen: true }); + }, + }, { id: "remote.connect", title: "Remote Development…", diff --git a/src/features/remote-dev/resources.test.tsx b/src/features/remote-dev/resources.test.tsx new file mode 100644 index 0000000000..dbc3784a1f --- /dev/null +++ b/src/features/remote-dev/resources.test.tsx @@ -0,0 +1,231 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { clearMocks, mockIPC } from "@tauri-apps/api/mocks"; +import { afterEach, describe, expect, it } from "vitest"; +import type { HostMetrics, RemoteSession } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { disableRemote, enableRemote, useRemote } from "@/platform/remote"; +import { RemoteResources, RemoteResourcesDashboard } from "./RemoteResources"; +import { + compactResourceText, + diskUsedPercent, + formatRate, + memoryPercent, + refreshRemoteResources, + sparklineGeometry, + summarizePressure, + syncRemoteResourcesSession, + useRemoteResources, +} from "./resources"; + +const MB = 1024 * 1024; +const GB = 1024 * MB; + +const sampleMetrics: HostMetrics = { + cpuPercent: 34.2, + cpuCores: 16, + loadAverage: [1.42, 1.18, 0.95], + memoryUsedBytes: 6 * GB, + memoryTotalBytes: 16 * GB, + netRxBytesPerSec: 1.5 * MB, + netTxBytesPerSec: 256 * 1024, + diskReadBytesPerSec: 4 * MB, + diskWriteBytesPerSec: 12 * MB, + diskAvailableBytes: 84 * GB, + diskTotalBytes: 200 * GB, + uptimeMs: 7_620_000, + processes: [ + { category: "app", label: "Backend", detail: null, pid: 100, processes: 1, bytes: 52 * MB, cpuPercent: 1.8 }, + { + category: "languageServer", + label: "rust-analyzer", + detail: "openidea", + pid: 200, + processes: 2, + bytes: 1400 * MB, + cpuPercent: 42, + }, + { + category: "process", + label: "pnpm run dev", + detail: "Run", + pid: 300, + processes: 4, + bytes: 380 * MB, + cpuPercent: 15, + }, + ], + externalProcesses: [{ pid: 900, name: "dockerd", cpuPercent: 6.4, memoryBytes: 820 * MB }], +}; + +const sshSession = (host = "me@devbox", commands = ["host_metrics", "host_end_process"]): RemoteSession => ({ + target: { kind: "ssh", config: host }, + root: "/home/me/openidea", + host, + os: "linux", + commands, + idlePolicy: null, + takenOver: false, +}); + +afterEach(() => { + disableRemote(); + useRemote.setState({ session: null, lost: null, takenOver: false, reconnecting: false }); + syncRemoteResourcesSession(null); + clearMocks(); +}); + +describe("remote resource calculations", () => { + it("keeps network and disk badges hidden when healthy and surfaces them on saturation", () => { + const calm = summarizePressure(sampleMetrics, 18); + expect(calm.level).toBe("normal"); + expect(calm.netSaturated).toBe(false); + expect(calm.diskSaturated).toBe(false); + + const highRtt = summarizePressure(sampleMetrics, 320); + expect(highRtt.level).toBe("warn"); + expect(highRtt.netSaturated).toBe(true); + + const lowDisk = summarizePressure({ ...sampleMetrics, diskAvailableBytes: 800 * MB, diskTotalBytes: 100 * GB }, 18); + expect(lowDisk.diskLevel).toBe("danger"); + expect(lowDisk.diskSaturated).toBe(true); + }); + + it("formats compact pill text, percentages and transfer rates", () => { + expect(compactResourceText(sampleMetrics)).toBe("34% · 6G"); + expect(memoryPercent(sampleMetrics)).toBe(37.5); + expect(diskUsedPercent(sampleMetrics)).toBeCloseTo(58); + expect(formatRate(0)).toBe("0 B/s"); + expect(formatRate(512 * 1024)).toBe("512 KB/s"); + expect(formatRate(null)).toBe("–"); + }); + + it("builds bounded sparkline SVG paths and keeps idle noise flat under minCeiling", () => { + expect(sparklineGeometry([null, null], 100, 24)).toBeNull(); + const single = sparklineGeometry([50], 100, 23, { fixedMax: 100 }); + expect(single?.line).toBe("M0,11.5 L100,11.5"); + + // 100 B/s idle traffic against a 256 KB/s ceiling stays near the bottom edge (y ≈ 21.5 of 23). + const idle = sparklineGeometry([100, 120], 100, 23, { minCeiling: 256 * 1024 }); + expect(idle?.line).toBe("M0,21.5 L100,21.5"); + }); +}); + +describe("remote resources widget and dashboard", () => { + it("stays inactive for local windows and legacy servers without host_metrics", async () => { + let metricCalls = 0; + mockIPC((cmd) => { + if (cmd === "host_metrics") metricCalls += 1; + return sampleMetrics; + }); + + const { container, rerender } = render(); + expect(container.textContent).toBe(""); + + act(() => enableRemote(sshSession("me@legacy", ["doc_close"]))); + rerender(); + await act(async () => refreshRemoteResources(false)); + expect(container.textContent).toBe(""); + expect(metricCalls).toBe(0); + }); + + it("polls via remote_invoke, opens the dashboard and ends only OpenIDEA child processes", async () => { + const remoteCalls: Array<{ cmd: string; args: Record }> = []; + useProject.setState((s) => ({ + project: s.project + ? { ...s.project, trusted: true } + : ({ name: "openidea", displayName: "openidea", root: "/home/me/openidea", trusted: true } as never), + })); + mockIPC((cmd, payload) => { + if (cmd === "remote_invoke") { + const p = payload as { cmd: string; args: string }; + const parsed = JSON.parse(p.args) as Record; + remoteCalls.push({ cmd: p.cmd, args: parsed }); + if (p.cmd === "host_metrics") return JSON.stringify(sampleMetrics); + if (p.cmd === "host_end_process") return JSON.stringify(true); + } + return null; + }); + + act(() => enableRemote(sshSession("deng@thinkpad"))); + render(); + + await act(async () => { + await refreshRemoteResources(false); + }); + expect(remoteCalls[0]).toEqual({ cmd: "host_metrics", args: { includeProcesses: false } }); + const pill = screen.getByRole("button", { name: /Remote host resources:/ }); + expect(pill.textContent).toContain("34% · 6G"); + expect(pill.textContent).not.toContain("Net"); + expect(pill.textContent).not.toContain("Disk"); + + await act(async () => { + fireEvent.click(pill); + await refreshRemoteResources(true); + }); + + expect(screen.getByText("SSH: deng@thinkpad")).toBeTruthy(); + expect(screen.getByText("16 cores · load 1.42 · 1.18 · 0.95")).toBeTruthy(); + expect(screen.getByText("6G / 16G")).toBeTruthy(); + expect(screen.getByText("84 GB free")).toBeTruthy(); + expect(screen.getByRole("group", { name: "Language servers" }).textContent).toContain("rust-analyzer"); + expect(screen.getByRole("group", { name: "Other host processes" }).textContent).toContain("dockerd"); + + // Backend and external host processes are never endable; child processes confirm before ending. + expect(screen.queryByRole("button", { name: "End Process Backend" })).toBeNull(); + expect(screen.queryByRole("button", { name: "End Process dockerd" })).toBeNull(); + const endLsp = screen.getByRole("button", { name: "End Process rust-analyzer" }); + await act(async () => { + fireEvent.click(endLsp); + }); + const confirmDialog = screen.getByRole("dialog", { name: "End Remote Process" }); + expect(confirmDialog.textContent).toContain("End 'rust-analyzer' (PID 200) and its child processes"); + + // Cancelling does not end the process. + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + }); + expect(remoteCalls.some((c) => c.cmd === "host_end_process")).toBe(false); + + // Confirming ends the process via host_end_process. + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "End Process rust-analyzer" })); + }); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "End Process" })); + }); + expect(remoteCalls).toContainEqual({ cmd: "host_end_process", args: { pid: 200 } }); + }); + + it("hides End Process buttons in Restricted Mode and drops stale metrics on host switch", async () => { + useProject.setState((s) => ({ + project: s.project + ? { ...s.project, trusted: false } + : ({ name: "openidea", displayName: "openidea", root: "/home/me/openidea", trusted: false } as never), + })); + render( + , + ); + expect(screen.queryByRole("button", { name: /End Process/ })).toBeNull(); + + let resolveSlow!: (v: string) => void; + mockIPC((cmd) => { + if (cmd === "remote_invoke") { + return new Promise((r) => { + resolveSlow = r; + }); + } + return null; + }); + act(() => enableRemote(sshSession("host-a"))); + const inflight = refreshRemoteResources(false); + act(() => enableRemote(sshSession("host-b"))); + resolveSlow(JSON.stringify(sampleMetrics)); + await act(async () => inflight); + expect(useRemoteResources.getState().metrics).toBeNull(); + }); +}); diff --git a/src/features/remote-dev/resources.ts b/src/features/remote-dev/resources.ts new file mode 100644 index 0000000000..36a61c3b2d --- /dev/null +++ b/src/features/remote-dev/resources.ts @@ -0,0 +1,308 @@ +/** + * Remote Host Resources store, polling, pressure thresholds and sparkline geometry. + * + * Background polling while the status bar pill is at rest asks `host_metrics(false)` + * (O(1) kernel counters, no process scan) so the 60s sparklines stay warm at + * negligible cost; opening the dashboard upgrades polling to `host_metrics(true)` + * to attribute OpenIDEA's remote processes and top external host processes. + */ +import { create } from "zustand"; +import { call, commands, isTauri, type HostMetrics, type RemoteSession } from "@/platform/ipc"; +import { useRemote } from "@/platform/remote"; +import { formatBytes, formatMs, formatPercent, formatSize } from "@/features/perf/format"; + +export const REMOTE_METRICS_POLL_MS = 3000; +export const REMOTE_DASHBOARD_POLL_MS = 2000; +export const MAX_RESOURCE_SAMPLES = 30; + +const KB = 1024; +const MB = KB * 1024; +const GB = MB * 1024; + +export const CPU_WARN_PERCENT = 85; +export const CPU_DANGER_PERCENT = 95; +export const MEM_WARN_PERCENT = 85; +export const MEM_DANGER_PERCENT = 92; +export const DISK_WARN_PERCENT = 88; +export const DISK_DANGER_PERCENT = 95; +export const DISK_WARN_FREE_BYTES = 3 * GB; +export const DISK_DANGER_FREE_BYTES = 1 * GB; +export const RTT_WARN_MS = 250; +export const RTT_DANGER_MS = 500; +export const NET_SATURATED_BPS = 25 * MB; +export const DISK_IO_SATURATED_BPS = 50 * MB; + +export type PressureLevel = "normal" | "warn" | "danger"; + +export interface ResourceSample { + cpuPercent: number | null; + memoryPercent: number | null; + netBytesPerSec: number | null; + diskBytesPerSec: number | null; + rttMs: number | null; +} + +export interface ResourcePressure { + level: PressureLevel; + cpuLevel: PressureLevel; + memoryLevel: PressureLevel; + diskLevel: PressureLevel; + rttLevel: PressureLevel; + /** Show network indicator in the compact pill when throughput or RTT is elevated. */ + netSaturated: boolean; + /** Show disk indicator in the compact pill when disk I/O or capacity is elevated. */ + diskSaturated: boolean; +} + +export interface RemoteResourcesState { + metrics: HostMetrics | null; + rttMs: number | null; + history: ResourceSample[]; + popupOpen: boolean; + error: string | null; +} + +const INITIAL_STATE: RemoteResourcesState = { + metrics: null, + rttMs: null, + history: [], + popupOpen: false, + error: null, +}; + +export const useRemoteResources = create(() => ({ ...INITIAL_STATE })); + +export function canMonitorRemoteHost(session: Pick | null | undefined): boolean { + return Boolean(session?.commands.includes("host_metrics")); +} + +function sessionIdentity(session: RemoteSession | null): string | null { + if (!session || !canMonitorRemoteHost(session)) return null; + return `${JSON.stringify(session.target)}:${session.host}:${session.root}`; +} + +let sessionEpoch = 0; +let activeIdentity: string | null = sessionIdentity(useRemote.getState().session); +let inFlightLight = false; +let inFlightDetailed = false; + +/** Resets state and invalidates in-flight RPCs whenever the window switches or leaves a remote host. */ +export function syncRemoteResourcesSession(session: RemoteSession | null = useRemote.getState().session): void { + const next = sessionIdentity(session); + if (next === activeIdentity) return; + activeIdentity = next; + sessionEpoch += 1; + inFlightLight = false; + inFlightDetailed = false; + useRemoteResources.setState({ ...INITIAL_STATE }); +} + +useRemote.subscribe((state) => syncRemoteResourcesSession(state.session)); + +export function memoryPercent( + m: Pick | null | undefined, +): number | null { + if (!m || m.memoryUsedBytes == null || m.memoryTotalBytes == null || m.memoryTotalBytes <= 0) return null; + return Math.min(100, Math.max(0, (m.memoryUsedBytes / m.memoryTotalBytes) * 100)); +} + +export function diskUsedPercent( + m: Pick | null | undefined, +): number | null { + if (!m || m.diskAvailableBytes == null || m.diskTotalBytes == null || m.diskTotalBytes <= 0) return null; + const used = Math.max(0, m.diskTotalBytes - m.diskAvailableBytes); + return Math.min(100, Math.max(0, (used / m.diskTotalBytes) * 100)); +} + +function sumRates(a: number | null | undefined, b: number | null | undefined): number | null { + if (a == null && b == null) return null; + return (a ?? 0) + (b ?? 0); +} + +/** Formats transfer rate: `0 B/s`, `48 KB/s`, `12.4 MB/s`, `1.2 GB/s`. */ +export function formatRate(bytesPerSec: number | null | undefined): string { + if (bytesPerSec == null || !Number.isFinite(bytesPerSec) || bytesPerSec < 0) return "–"; + if (bytesPerSec < 1) return "0 B/s"; + return `${formatSize(bytesPerSec)}/s`; +} + +function maxLevel(...levels: PressureLevel[]): PressureLevel { + if (levels.includes("danger")) return "danger"; + if (levels.includes("warn")) return "warn"; + return "normal"; +} + +function thresholdLevel(value: number | null, warn: number, danger: number): PressureLevel { + if (value == null || !Number.isFinite(value)) return "normal"; + if (value >= danger) return "danger"; + if (value >= warn) return "warn"; + return "normal"; +} + +export function summarizePressure(m: HostMetrics | null, rttMs: number | null): ResourcePressure { + const cpuLevel = thresholdLevel(m?.cpuPercent ?? null, CPU_WARN_PERCENT, CPU_DANGER_PERCENT); + const memPct = memoryPercent(m); + const memoryLevel = thresholdLevel(memPct, MEM_WARN_PERCENT, MEM_DANGER_PERCENT); + + const diskPct = diskUsedPercent(m); + const avail = m?.diskAvailableBytes ?? null; + const freeLevel: PressureLevel = + avail == null + ? "normal" + : avail <= DISK_DANGER_FREE_BYTES + ? "danger" + : avail <= DISK_WARN_FREE_BYTES + ? "warn" + : "normal"; + const diskLevel = maxLevel(thresholdLevel(diskPct, DISK_WARN_PERCENT, DISK_DANGER_PERCENT), freeLevel); + const rttLevel = thresholdLevel(rttMs, RTT_WARN_MS, RTT_DANGER_MS); + + const netTotal = sumRates(m?.netRxBytesPerSec, m?.netTxBytesPerSec); + const diskIoTotal = sumRates(m?.diskReadBytesPerSec, m?.diskWriteBytesPerSec); + + return { + level: maxLevel(cpuLevel, memoryLevel, diskLevel, rttLevel), + cpuLevel, + memoryLevel, + diskLevel, + rttLevel, + netSaturated: (netTotal != null && netTotal >= NET_SATURATED_BPS) || rttLevel !== "normal", + diskSaturated: (diskIoTotal != null && diskIoTotal >= DISK_IO_SATURATED_BPS) || diskLevel !== "normal", + }; +} + +/** Compact status bar text beside the 2-bar micro-meter: `24% · 6.2G`. */ +export function compactResourceText(m: HostMetrics | null): string { + const cpu = m?.cpuPercent == null ? "–" : formatPercent(m.cpuPercent); + const mem = m?.memoryUsedBytes == null ? "–" : formatBytes(m.memoryUsedBytes); + return `${cpu} · ${mem}`; +} + +/** Status bar tooltip summarizing all four subsystems and RTT. */ +export function resourceTooltip(m: HostMetrics | null, rttMs: number | null): string { + if (!m) return "Remote host resources"; + const parts = [ + `CPU ${formatPercent(m.cpuPercent)}`, + m.memoryTotalBytes != null + ? `Memory ${formatSize(m.memoryUsedBytes)} / ${formatSize(m.memoryTotalBytes)}` + : `Memory ${formatSize(m.memoryUsedBytes)}`, + ]; + const netTotal = sumRates(m.netRxBytesPerSec, m.netTxBytesPerSec); + if (netTotal != null) { + parts.push(`Net ↓ ${formatRate(m.netRxBytesPerSec)} ↑ ${formatRate(m.netTxBytesPerSec)}`); + } + if (m.diskAvailableBytes != null) { + parts.push(`Disk ${formatSize(m.diskAvailableBytes)} free`); + } + if (rttMs != null) { + parts.push(`RTT ${formatMs(rttMs)}`); + } + return parts.join(" · "); +} + +export interface SparklinePaths { + line: string; + area: string; +} + +/** + * Builds SVG `d` paths (`line` and filled `area`) across `width × height`. + * `fixedMax` pins the top of percentage charts to `100`; throughput charts omit + * `fixedMax` and pass `minCeiling` so idle keepalive bytes stay flat along the baseline. + */ +export function sparklineGeometry( + values: ReadonlyArray, + width: number, + height: number, + options: { fixedMax?: number; minCeiling?: number } = {}, +): SparklinePaths | null { + const known = values.map((v, i) => (v != null && Number.isFinite(v) && v >= 0 ? { i, v } : null)).filter(Boolean) as { + i: number; + v: number; + }[]; + if (!known.length || width <= 0 || height <= 2) return null; + + const peak = known.reduce((acc, p) => Math.max(acc, p.v), 0); + const ceiling = options.fixedMax ?? Math.max(peak, options.minCeiling ?? 1); + const pad = 1.5; + const usableH = height - pad * 2; + const slots = Math.max(values.length - 1, 1); + + const coords = + known.length === 1 + ? [ + { x: 0, y: pad + usableH * (1 - Math.min(1, known[0]!.v / ceiling)) }, + { x: width, y: pad + usableH * (1 - Math.min(1, known[0]!.v / ceiling)) }, + ] + : known.map(({ i, v }) => ({ + x: values.length <= 1 ? width : (i / slots) * width, + y: pad + usableH * (1 - Math.min(1, v / ceiling)), + })); + + const fmt = (n: number) => Number(n.toFixed(1)); + const line = coords.map((p, idx) => `${idx === 0 ? "M" : "L"}${fmt(p.x)},${fmt(p.y)}`).join(" "); + const first = coords[0]!; + const last = coords[coords.length - 1]!; + const area = `${line} L${fmt(last.x)},${fmt(height)} L${fmt(first.x)},${fmt(height)} Z`; + return { line, area }; +} + +export async function refreshRemoteResources(includeProcesses: boolean): Promise { + if (!isTauri()) return; + const { session, lost } = useRemote.getState(); + syncRemoteResourcesSession(session); + if (!session || lost !== null || !canMonitorRemoteHost(session)) return; + if (includeProcesses ? inFlightDetailed : inFlightLight || inFlightDetailed) return; + + const epoch = sessionEpoch; + if (includeProcesses) inFlightDetailed = true; + else inFlightLight = true; + + const t0 = performance.now(); + try { + const fresh = await call(commands.hostMetrics(includeProcesses)); + const rttMs = performance.now() - t0; + if (epoch !== sessionEpoch || useRemote.getState().lost !== null) return; + + useRemoteResources.setState((prev) => { + // Preserve previously fetched process breakdown across light background ticks so + // reopening the dashboard renders without an empty-list flash. + const merged: HostMetrics = includeProcesses + ? fresh + : { + ...fresh, + processes: prev.metrics?.processes ?? [], + externalProcesses: prev.metrics?.externalProcesses ?? [], + }; + const sample: ResourceSample = { + cpuPercent: fresh.cpuPercent, + memoryPercent: memoryPercent(fresh), + netBytesPerSec: sumRates(fresh.netRxBytesPerSec, fresh.netTxBytesPerSec), + diskBytesPerSec: sumRates(fresh.diskReadBytesPerSec, fresh.diskWriteBytesPerSec), + rttMs, + }; + const history = [...prev.history.slice(-(MAX_RESOURCE_SAMPLES - 1)), sample]; + return { metrics: merged, rttMs, history, error: null }; + }); + } catch (e) { + if (epoch !== sessionEpoch) return; + useRemoteResources.setState({ error: e instanceof Error ? e.message : String(e) }); + } finally { + if (epoch === sessionEpoch) { + if (includeProcesses) inFlightDetailed = false; + else inFlightLight = false; + } + } +} + +export async function endRemoteProcess(pid: number): Promise { + const epoch = sessionEpoch; + try { + await call(commands.hostEndProcess(pid)); + if (epoch !== sessionEpoch) return; + await refreshRemoteResources(true); + } catch (e) { + if (epoch !== sessionEpoch) return; + useRemoteResources.setState({ error: e instanceof Error ? e.message : String(e) }); + } +} diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 5e40a07aac..dafe5b2ed1 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6073,6 +6073,30 @@ "Cannot open in browser": "无法在浏览器中打开", "Cannot change automatic upload": "无法更改自动上传", "Remote Host": "远程主机", + "Remote Host Resources": "远程主机资源", + "Remote host resources: {tooltip}": "远程主机资源:{tooltip}", + "Net": "网络", + "Disk": "磁盘", + "Sampling…": "采样中…", + "1 core · load {loadText}": "1 核 · 负载 {loadText}", + "{cpuCores} cores · load {loadText}": "{cpuCores} 核 · 负载 {loadText}", + "1 core": "1 核", + "{cpuCores} cores": "{cpuCores} 核", + "{memPct} · {memAvail} free": "{memPct} · 可用 {memAvail}", + "SSH / RPC RTT {rttMs}": "SSH / RPC 往返延迟 {rttMs}", + "{diskAvailableBytes} free": "可用 {diskAvailableBytes}", + "{diskPct} of {diskTotalBytes} used": "已用 {diskTotalBytes} 的 {diskPct}", + "up {uptimeMs}": "已运行 {uptimeMs}", + "Round-trip latency to remote backend": "到远程后端的往返延迟", + "RTT {rttMs}": "延迟 {rttMs}", + "Network": "网络", + "Other host processes": "主机其他进程", + "Show Remote Host Resources": "显示远程主机资源", + "Shows CPU, memory, network, disk and running processes of the remote host.": "显示远程主机的 CPU、内存、网络、磁盘及运行中的进程。", + "End Remote Process": "结束远程进程", + "End '{label}' (PID {pid}) and its child processes on the remote host?": "结束远程主机上的“{label}”(PID {pid})及其子进程?", + "End '{label}' (PID {pid}) on the remote host?": "结束远程主机上的“{label}”(PID {pid})?", + "End Process": "结束进程", "No deployment servers": "没有部署服务器", "Download to Project": "下载到项目", "New Folder…": "新建文件夹…",