diff --git a/crates/ide-docker/src/engine.rs b/crates/ide-docker/src/engine.rs index 1ad6159c7..42b675720 100644 --- a/crates/ide-docker/src/engine.rs +++ b/crates/ide-docker/src/engine.rs @@ -557,6 +557,53 @@ fn map_layers(layers: Vec, now: i64) -> Vec { .collect() } +/// Per-volume disk usage (`GET /system/df?type=volume`). +pub(crate) fn volume_sizes(ep: &DockerEndpoint, timeout: Duration) -> Option>> { + let addr = address(ep)?; + Some((|| { + let body = check(request(&addr, "GET", "/system/df?type=volume", timeout)?)?; + map_volume_sizes(&body) + })()) +} + +#[derive(Deserialize, Default)] +#[serde(rename_all = "PascalCase", default)] +struct ApiDiskUsage { + volumes: Option>, +} + +#[derive(Deserialize, Default)] +#[serde(rename_all = "PascalCase", default)] +struct ApiVolumeUsage { + name: String, + usage_data: Option, +} + +const fn unknown_volume_size() -> i64 { + -1 +} + +#[derive(Deserialize, Default)] +#[serde(rename_all = "PascalCase", default)] +struct ApiVolumeUsageData { + #[serde(default = "unknown_volume_size")] + size: i64, +} + +fn map_volume_sizes(body: &str) -> IdeResult> { + let parsed = serde_json::from_str::(body) + .map_err(|e| IdeError::internal(format!("the Docker daemon's disk usage is not JSON: {e}")))?; + Ok(parsed + .volumes + .unwrap_or_default() + .into_iter() + .filter_map(|v| { + let size = v.usage_data?.size; + (!v.name.is_empty() && size >= 0).then(|| (v.name, human_size(size))) + }) + .collect()) +} + fn unix_now() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) } @@ -1158,6 +1205,15 @@ mod tests { (top.titles, top.processes), (vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]]) ); + let sizes = map_volume_sizes( + r#"{"Volumes":[{"Name":"shop_pgdata","UsageData":{"RefCount":1,"Size":145442}},{"Name":"empty","UsageData":{"RefCount":0,"Size":0}},{"Name":"remote","UsageData":{"RefCount":1,"Size":-1}},{"Name":"missing","UsageData":null}]}"#, + ) + .unwrap(); + assert_eq!(sizes.get("shop_pgdata").map(String::as_str), Some("145.442kB")); + assert_eq!(sizes.get("empty").map(String::as_str), Some("0B")); + assert!(!sizes.contains_key("remote")); + assert!(!sizes.contains_key("missing")); + assert!(map_volume_sizes(r#"{"Volumes":null}"#).unwrap().is_empty()); } #[test] diff --git a/crates/ide-docker/src/lib.rs b/crates/ide-docker/src/lib.rs index 8dcb97b94..84f3e5906 100644 --- a/crates/ide-docker/src/lib.rs +++ b/crates/ide-docker/src/lib.rs @@ -315,6 +315,17 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult IdeResult> { + if docker_executable().is_none() + && let Some(sizes) = engine::volume_sizes(ep, QUICK) + { + return sizes; + } + let out = run(ep, &["system", "df", "-v", "--format", "{{json .Volumes}}"], QUICK)?; + Ok(parse_volume_sizes(&out)) +} + /// How long log lines collect before they are handed on together. const LOG_BATCH: Duration = Duration::from_millis(30); diff --git a/crates/ide-docker/src/model.rs b/crates/ide-docker/src/model.rs index ae4ebfdad..8df2202f3 100644 --- a/crates/ide-docker/src/model.rs +++ b/crates/ide-docker/src/model.rs @@ -473,6 +473,33 @@ pub fn parse_container_stats(text: &str) -> Option { }) } +#[derive(Deserialize, Default)] +#[serde(rename_all = "PascalCase", default)] +struct RawVolumeUsage { + name: String, + size: String, +} + +/// `docker system df -v --format '{{json .Volumes}}'` volume name → human size. +pub fn parse_volume_sizes(text: &str) -> BTreeMap { + let trimmed = text.trim(); + let items: Vec = if trimmed.is_empty() || trimmed == "null" { + Vec::new() + } else if let Ok(parsed) = serde_json::from_str::>>(trimmed) { + parsed.unwrap_or_default() + } else { + lines::(text).collect() + }; + items + .into_iter() + .filter(|v| { + let size = v.size.trim(); + !v.name.is_empty() && !size.is_empty() && !size.eq_ignore_ascii_case("n/a") + }) + .map(|v| (v.name, v.size.trim().to_owned())) + .collect() +} + #[derive(Deserialize, Default)] #[serde(default)] struct RawVersion { diff --git a/crates/ide-docker/tests/parse.rs b/crates/ide-docker/tests/parse.rs index 9f2fd0ea6..4b45692c2 100644 --- a/crates/ide-docker/tests/parse.rs +++ b/crates/ide-docker/tests/parse.rs @@ -2,7 +2,7 @@ use ide_docker::{ PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, - parse_networks, parse_volumes, + parse_networks, parse_volume_sizes, parse_volumes, }; const PS: &str = include_str!("fixtures/ps.jsonl"); @@ -113,4 +113,12 @@ fn image_history_top_and_stats() { assert_eq!(stats.net_io, "12kB / 8kB"); assert_eq!(stats.block_io, "1.2MB / 0B"); assert_eq!(stats.pids, "14"); + + let df_volumes = r#"[{"Availability":"N/A","Driver":"local","Links":"4","Mountpoint":"/var/lib/docker/volumes/selfhost_runner-persist/_data","Name":"selfhost_runner-persist","Scope":"local","Size":"145.4kB"},{"Name":"unused_anon","Size":"0B"},{"Name":"remote_nfs","Size":"N/A"}]"#; + let volume_sizes = parse_volume_sizes(df_volumes); + assert_eq!(volume_sizes.get("selfhost_runner-persist").map(String::as_str), Some("145.4kB")); + assert_eq!(volume_sizes.get("unused_anon").map(String::as_str), Some("0B")); + assert!(!volume_sizes.contains_key("remote_nfs")); + assert!(parse_volume_sizes("null\n").is_empty()); + assert!(parse_volume_sizes("").is_empty()); } diff --git a/docs/en/guide/services.mdx b/docs/en/guide/services.mdx index e749e49b0..6c829c1e9 100644 --- a/docs/en/guide/services.mdx +++ b/docs/en/guide/services.mdx @@ -69,10 +69,10 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel* Selecting an item shows tabs in the detail pane: -- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project). -- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON). +- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project with live disk usage). +- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts with live volume disk usage, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON). - **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**. -- **Volume** and **network**: **Dashboard** and **Inspect**. +- **Volume** and **network**: **Dashboard** (including live volume disk usage) and **Inspect**. **Open Log in Editor** opens the log in an editor tab with **Timestamps**, **Soft-wrap**, **Find in Logs** and **Clear**. diff --git a/docs/zh/guide/services.mdx b/docs/zh/guide/services.mdx index 8378c40cc..a79cf8835 100644 --- a/docs/zh/guide/services.mdx +++ b/docs/zh/guide/services.mdx @@ -69,10 +69,10 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的 选中某项后,详情区会显示以下标签页: -- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。 -- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。 +- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷及其实时磁盘占用)。 +- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载及数据卷实时磁盘占用、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。 - **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。 -- **卷** 和 **网络**:**仪表盘** 和 **检查**。 +- **卷** 和 **网络**:**仪表盘**(含数据卷实时磁盘占用)和 **检查**。 **在编辑器中打开日志** 会在编辑器标签页中打开日志,提供 **时间戳**、**软换行**、**在日志中查找** 和 **清除**。 diff --git a/e2e/services.spec.ts b/e2e/services.spec.ts index da092da64..c13aa5587 100644 --- a/e2e/services.spec.ts +++ b/e2e/services.spec.ts @@ -787,3 +787,128 @@ test("Docker Compose dashboard keeps its action row pinned when scrolling", asyn expect(afterDown.y).toBe(beforeDown.y); expect(afterBanner.y).toBeLessThan(beforeBanner.y - 100); }); + +test("Docker volume, Compose, and container dashboards show volume disk usage", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async () => { + (window as unknown as { __volSize: string }).__volSize = "145.4kB"; + const inspectJson = JSON.stringify([ + { + Created: "2026-11-23T02:37:25Z", + State: { Status: "running", Pid: 2048, StartedAt: "2026-11-23T02:37:26Z" }, + HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } }, + Config: { Entrypoint: [], Cmd: ["./bin/Runner.Listener", "run"], Env: [], Labels: {} }, + Mounts: [ + { + Type: "volume", + Name: "selfhost_runner-persist", + Source: "/var/lib/docker/volumes/selfhost_runner-persist/_data", + Destination: "/persist", + Mode: "rw", + RW: true, + }, + ], + NetworkSettings: { Ports: {}, Networks: {} }, + }, + ]); + const snapshot = { + availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" }, + executable: "/usr/bin/docker", + containers: [ + { + id: "runner-1", + name: "selfhost-github-runner-1", + image: "myoung34/github-runner:latest", + command: "./bin/Runner.Listener run", + state: "running", + status: "Up 24 hours", + ports: "", + createdAt: "2026-11-23T02:37:25Z", + composeProject: "selfhost", + composeService: "github-runner-1", + composeWorkingDir: "/work/selfhost", + composeFiles: ["/work/selfhost/docker-compose.yml"], + mounts: ["selfhost_runner-persist"], + networks: ["selfhost_default"], + }, + ], + images: [], + volumes: [ + { + name: "selfhost_runner-persist", + driver: "local", + mountpoint: "/var/lib/docker/volumes/selfhost_runner-persist/_data", + composeProject: "selfhost", + scope: "local", + labels: { + "com.docker.compose.project": "selfhost", + "com.docker.compose.volume": "runner-persist", + }, + }, + ], + networks: [ + { id: "net-1", name: "selfhost_default", driver: "bridge", scope: "local", composeProject: "selfhost" }, + ], + errors: [], + }; + + window.__ipc.handlers.docker_settings = () => ({ + connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], + registries: [], + }); + window.__ipc.handlers.docker_snapshot = () => snapshot; + window.__ipc.handlers.docker_events = () => new Promise(() => {}); + window.__ipc.handlers.docker_inspect = () => inspectJson; + window.__ipc.handlers.docker_container_stats = () => ({ + cpuPerc: "0.02%", + memUsage: "96MiB / 114GiB", + memPerc: "0.08%", + netIo: "1.1MB / 3.8MB", + blockIo: "512kB / 201kB", + pids: "16", + }); + window.__ipc.handlers.docker_volume_sizes = () => ({ + "selfhost_runner-persist": (window as unknown as { __volSize: string }).__volSize, + }); + + const storeMod = "/src/features/services/store.ts"; + const treeMod = "/src/features/services/tree.ts"; + const { useServices } = await import(/* @vite-ignore */ storeMod); + const { useServicesTree } = await import(/* @vite-ignore */ treeMod); + useServices.setState({ + settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] }, + conns: { default: { snapshot, loading: false, error: null } }, + detailTab: "dashboard", + }); + useServicesTree.setState({ + expanded: new Set(["docker:default"]), + selectedKey: "docker:default:compose:selfhost", + selectedKeys: new Set(["docker:default:compose:selfhost"]), + }); + }); + + await page.keyboard.press("Meta+8"); + const services = page.getByRole("region", { name: "Services", exact: true }); + const detail = services.locator("[data-panel][id=services-detail]"); + + // 1. Compose dashboard shows volume disk usage on the chip and the banner. + const volumeChip = detail.getByRole("button", { name: /selfhost_runner-persist/ }); + await expect(volumeChip).toContainText("runner-persist · local · 145.4kB"); + await expect(detail).toContainText("Disk usage: 145.4kB"); + + // 2. Opening the volume samples again; the dashboard shows the current size. + await page.evaluate(() => { + (window as unknown as { __volSize: string }).__volSize = "210.8kB"; + }); + await volumeChip.click(); + await expect(detail.getByText("Volume Overview")).toBeVisible(); + await expect(detail).toContainText("210.8kB"); + + // 3. The container dashboard shows the size beside the volume mount. + await page.evaluate(() => { + (window as unknown as { __volSize: string }).__volSize = "380.2kB"; + }); + await detail.getByRole("button", { name: /selfhost-github-runner-1/ }).click(); + await expect(detail.getByText("Volume & Bind Mounts")).toBeVisible(); + await expect(detail).toContainText("380.2kB"); +}); diff --git a/src-tauri/src/commands/docker.rs b/src-tauri/src/commands/docker.rs index 69828f998..55a60347b 100644 --- a/src-tauri/src/commands/docker.rs +++ b/src-tauri/src/commands/docker.rs @@ -130,6 +130,18 @@ pub async fn docker_container_stats( blocking(move || ide_docker::container_stats(&endpoint, &id)).await } +/// Disk usage per volume name (`docker system df -v`). +#[desktop_command(trust = trusted)] +#[tauri::command] +#[specta::specta] +pub async fn docker_volume_sizes( + state: State<'_, AppState>, + endpoint: DockerEndpoint, +) -> IdeResult> { + let endpoint = resolve(&state, endpoint).await?; + blocking(move || ide_docker::volume_sizes(&endpoint)).await +} + /// Streams a container's log lines, in batches, until it stops or the request is cancelled. #[desktop_command(trust = trusted)] #[tauri::command] @@ -308,4 +320,5 @@ ide_command::desktop_domain!( docker_set_registry_password, docker_settings, docker_snapshot, + docker_volume_sizes, ); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 68dd1a739..dcae03101 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -258,6 +258,7 @@ docker_save_settings always desktop bin docker_set_registry_password always desktop bindings async docker_settings always desktop bindings async docker_snapshot trusted desktop bindings async +docker_volume_sizes trusted desktop bindings async end_process trusted desktop bindings async env_reload always project_host bindings async file_dialog_needs_gtk trusted desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 7917b6793..8d6c56f73 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -637,6 +637,8 @@ export const commands = { dockerSettings: () => typedError(__TAURI_INVOKE("docker_settings")), /** Availability plus containers, images, volumes and networks. */ dockerSnapshot: (endpoint: DockerEndpoint) => typedError(__TAURI_INVOKE("docker_snapshot", { endpoint })), + /** Disk usage per volume name (`docker system df -v`). */ + dockerVolumeSizes: (endpoint: DockerEndpoint) => typedError<{ [key in string]: string }, IdeError>(__TAURI_INVOKE("docker_volume_sizes", { endpoint })), /** * "Clear caches": drops syntax trees and EditorConfig files of the window's * project, shrinks the in-memory index and compacts its on-disk cache. diff --git a/src/features/services/Services.module.css b/src/features/services/Services.module.css index 839f5b089..abbe7b3a0 100644 --- a/src/features/services/Services.module.css +++ b/src/features/services/Services.module.css @@ -260,6 +260,10 @@ .dashboardActions + .sectionBanner { border-top: 0; } +.bannerMeta { + font-weight: 400; + color: var(--fg-secondary); +} .propList { display: flex; flex-direction: column; @@ -517,7 +521,7 @@ button.entityChip:not(:disabled):hover { } .dataRow { display: grid; - grid-template-columns: 72px minmax(120px, 1fr) minmax(140px, 1.3fr) 56px; + grid-template-columns: 72px minmax(120px, 1fr) minmax(120px, 1.2fr) 88px 56px; gap: var(--space-2); align-items: center; padding: 4px 12px; diff --git a/src/features/services/dashboard.tsx b/src/features/services/dashboard.tsx index 7340fc0d6..c4e2bbd08 100644 --- a/src/features/services/dashboard.tsx +++ b/src/features/services/dashboard.tsx @@ -113,6 +113,20 @@ export function bytesToUnits(bytes: number, precision = 1): string { return `${val.toFixed(precision)} ${units[idx]!}`; } +export function bytesToDecimalUnits(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) return "0B"; + const units = ["B", "kB", "MB", "GB", "TB", "PB"]; + let idx = 0; + let val = bytes; + while (val >= 1000 && idx < units.length - 1) { + val /= 1000; + idx++; + } + if (idx === 0) return `${Math.round(val)}B`; + const text = val.toFixed(3).replace(/\.?0+$/, ""); + return `${text}${units[idx]!}`; +} + export function parsePercent(raw: string | undefined | null): number { if (!raw) return 0; const n = Number.parseFloat(raw.replace(/%/g, "").trim()); @@ -816,9 +830,11 @@ function ContainerLinkChip({ conn, container }: { conn: string; container: Docke ); } -function VolumeLinkChip({ conn, volume }: { conn: string; volume: DockerVolume }) { +function VolumeLinkChip({ conn, volume, size }: { conn: string; volume: DockerVolume; size?: string }) { const composeVol = volume.labels?.["com.docker.compose.volume"]; - const meta = composeVol && composeVol !== volume.name ? `${composeVol} · ${volume.driver}` : volume.driver; + const meta = [composeVol && composeVol !== volume.name ? composeVol : null, volume.driver, size] + .filter(Boolean) + .join(" · "); return ( + ) : ( {m} + {mountSize && {mountSize}} ); })} @@ -1669,6 +1784,8 @@ export function VolumeDashboard({ const target: DockerTarget = { conn, node: { kind: "volume", key: `volume:${volume.name}`, volume } }; const usingContainers = useMemo(() => containersUsingVolume(snapshot, volume), [snapshot, volume]); const labels = Object.entries(volume.labels ?? {}).sort((a, b) => a[0].localeCompare(b[0])); + const { byName: volumeSizes, loading: volumeSizesLoading } = useLiveVolumeSizes(conn, volume.name); + const diskUsage = volumeSizes[volume.name]; return (
@@ -1688,6 +1805,17 @@ export function VolumeDashboard({ Name}> {volume.name} + Disk usage}> + {diskUsage ? ( + {diskUsage} + ) : volumeSizesLoading ? ( + + Loading… + + ) : ( + — + )} + Driver}> {volume.driver} @@ -1875,6 +2003,21 @@ export function ComposeProjectDashboard({ const first = containers[0]; const runningCount = containers.filter(isRunning).length; const namedVolumes = useMemo(() => volumesInComposeProject(snapshot, project), [snapshot, project]); + const namedVolumesKey = useMemo( + () => + namedVolumes + .map((v) => v.name) + .sort() + .join("\0"), + [namedVolumes], + ); + const { byName: volumeSizes } = useLiveVolumeSizes(conn, namedVolumesKey, namedVolumes.length > 0); + const totalVolumeSize = useMemo(() => { + const sizes = namedVolumes.map((v) => volumeSizes[v.name]).filter((s): s is string => Boolean(s)); + if (sizes.length === 0) return null; + if (sizes.length === 1) return sizes[0]!; + return bytesToDecimalUnits(sizes.reduce((sum, s) => sum + unitsToBytes(s), 0)); + }, [namedVolumes, volumeSizes]); const runningIdsKey = useMemo( () => @@ -2029,13 +2172,23 @@ export function ComposeProjectDashboard({
- + + Disk usage + {": "} + {totalVolumeSize} + + ) : undefined + } + > Volumes {namedVolumes.length > 0 ? (
{namedVolumes.map((v) => ( - + ))}
) : ( diff --git a/src/features/services/dashboardStats.test.tsx b/src/features/services/dashboardStats.test.tsx index 00978cac9..50742fad4 100644 --- a/src/features/services/dashboardStats.test.tsx +++ b/src/features/services/dashboardStats.test.tsx @@ -1,10 +1,11 @@ import { act, cleanup, render, screen } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { DockerContainer, DockerContainerStats, DockerSnapshot } from "@/platform/ipc"; +import type { DockerContainer, DockerContainerStats, DockerSnapshot, DockerVolume } from "@/platform/ipc"; import { ToolWindowShownProvider } from "@/workbench/contributions"; const backend = vi.hoisted(() => ({ stats: vi.fn(), + volumeSizes: vi.fn(), })); vi.mock("@/platform/ipc", async (original) => { @@ -15,13 +16,21 @@ vi.mock("@/platform/ipc", async (original) => { commands: { ...actual.commands, dockerContainerStats: backend.stats, + dockerVolumeSizes: backend.volumeSizes, }, }; }); -import { ComposeProjectDashboard, CONTAINER_STATS_POLL_MS, ContainerDashboard } from "./dashboard"; +import { + bytesToDecimalUnits, + ComposeProjectDashboard, + CONTAINER_STATS_POLL_MS, + ContainerDashboard, + VOLUME_SIZES_POLL_MS, + VolumeDashboard, +} from "./dashboard"; -const ok = (data: DockerContainerStats) => ({ status: "ok" as const, data }); +const ok = (data: T) => ({ status: "ok" as const, data }); function makeStats(cpuPerc: string): DockerContainerStats { return { @@ -73,6 +82,8 @@ const snapshot: DockerSnapshot = { beforeEach(() => { vi.useFakeTimers(); backend.stats.mockReset(); + backend.volumeSizes.mockReset(); + backend.volumeSizes.mockResolvedValue(ok({})); vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); }); @@ -151,7 +162,7 @@ describe("live container stats polling", () => { }); it("auto-refreshes ContainerDashboard without overlapping slow stats calls", async () => { - let resolvePending: ((v: ReturnType) => void) | undefined; + let resolvePending: ((v: ReturnType>) => void) | undefined; backend.stats .mockImplementationOnce( () => @@ -164,6 +175,8 @@ describe("live container stats polling", () => { render(); expect(backend.stats).toHaveBeenCalledTimes(1); + // Container without volume mounts does not poll dockerVolumeSizes. + expect(backend.volumeSizes).not.toHaveBeenCalled(); // Slow first sample (4.5s > 3s): no overlapping second call starts while in flight. await act(async () => { await vi.advanceTimersByTimeAsync(4500); @@ -184,3 +197,200 @@ describe("live container stats polling", () => { expect(screen.getByText("22.50%")).toBeInTheDocument(); }); }); + +describe("live volume disk usage polling", () => { + const pgVolume: DockerVolume = { + name: "shop_pgdata", + driver: "local", + mountpoint: "/var/lib/docker/volumes/shop_pgdata/_data", + composeProject: "shop", + scope: "local", + labels: { + "com.docker.compose.project": "shop", + "com.docker.compose.volume": "pgdata", + }, + }; + + const cacheVolume: DockerVolume = { + name: "shop_redis", + driver: "local", + mountpoint: "/var/lib/docker/volumes/shop_redis/_data", + composeProject: "shop", + scope: "local", + labels: { + "com.docker.compose.project": "shop", + "com.docker.compose.volume": "redis", + }, + }; + + const snapshotWithVolumes: DockerSnapshot = { + ...snapshot, + volumes: [pgVolume, cacheVolume], + }; + + it("formats decimal byte totals like Docker CLI output", () => { + expect(bytesToDecimalUnits(0)).toBe("0B"); + expect(bytesToDecimalUnits(512)).toBe("512B"); + expect(bytesToDecimalUnits(145_400)).toBe("145.4kB"); + expect(bytesToDecimalUnits(1_500_000_000)).toBe("1.5GB"); + }); + + it("auto-refreshes VolumeDashboard disk usage every 30s while visible and pauses when hidden", async () => { + let sample = 0; + backend.volumeSizes.mockImplementation(async () => { + sample += 1; + return ok({ shop_pgdata: `${sample * 100}kB` }); + }); + + const { rerender } = render( + + + , + ); + + await act(async () => { + await Promise.resolve(); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(1); + expect(backend.volumeSizes).toHaveBeenLastCalledWith({ kind: "default" }); + expect(screen.getByText("100kB")).toBeInTheDocument(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(2); + expect(screen.getByText("200kB")).toBeInTheDocument(); + + // Pauses while hidden and resumes when visible again. + vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden"); + act(() => { + document.dispatchEvent(new Event("visibilitychange")); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS * 3); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(2); + + vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + await act(async () => { + document.dispatchEvent(new Event("visibilitychange")); + await Promise.resolve(); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(3); + expect(screen.getByText("300kB")).toBeInTheDocument(); + + // Stops polling when the Services tool window is closed. + rerender( + + + , + ); + await act(async () => { + await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS * 3); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(3); + }); + + it("refreshes ComposeProjectDashboard per-volume chips and summed banner disk usage every 30s", async () => { + backend.stats.mockResolvedValue(ok(makeStats("1.00%"))); + backend.volumeSizes + .mockResolvedValueOnce(ok({ shop_pgdata: "1.2GB", shop_redis: "300MB" })) + .mockResolvedValueOnce(ok({ shop_pgdata: "1.5GB", shop_redis: "500MB" })); + + render( + + + , + ); + + await act(async () => { + await Promise.resolve(); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(1); + expect(screen.getByText("pgdata · local · 1.2GB")).toBeInTheDocument(); + expect(screen.getByText("redis · local · 300MB")).toBeInTheDocument(); + expect(screen.getByText("1.5GB")).toBeInTheDocument(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(2); + expect(screen.getByText("pgdata · local · 1.5GB")).toBeInTheDocument(); + expect(screen.getByText("redis · local · 500MB")).toBeInTheDocument(); + expect(screen.getByText("2GB")).toBeInTheDocument(); + }); + + it("refreshes ContainerDashboard mounted volume sizes every 30s without overlapping slow calls", async () => { + backend.stats.mockResolvedValue(ok(makeStats("1.00%"))); + let resolveSlow: ((v: ReturnType>>) => void) | undefined; + backend.volumeSizes + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveSlow = resolve; + }), + ) + .mockResolvedValueOnce(ok({ shop_pgdata: "256.8kB" })); + + const inspectJson = JSON.stringify([ + { + Created: "2026-04-20T05:00:00Z", + State: { Status: "running", Pid: 100, StartedAt: "2026-04-20T05:00:01Z" }, + HostConfig: { RestartPolicy: { Name: "no", MaximumRetryCount: 0 } }, + Config: { Entrypoint: [], Cmd: ["postgres"], Env: [], Labels: {} }, + Mounts: [ + { + Type: "volume", + Name: "shop_pgdata", + Source: "/var/lib/docker/volumes/shop_pgdata/_data", + Destination: "/var/lib/postgresql/data", + Mode: "z", + RW: true, + }, + { + Type: "bind", + Source: "/work/shop/init.sql", + Destination: "/docker-entrypoint-initdb.d/init.sql", + Mode: "ro", + RW: false, + }, + ], + NetworkSettings: { Ports: {}, Networks: {} }, + }, + ]); + + render( + + + , + ); + + expect(backend.volumeSizes).toHaveBeenCalledTimes(1); + await act(async () => { + await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS * 1.5); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(1); + + await act(async () => { + resolveSlow!(ok({ shop_pgdata: "145.4kB" })); + await Promise.resolve(); + }); + expect(screen.getByText("145.4kB")).toBeInTheDocument(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(VOLUME_SIZES_POLL_MS); + }); + expect(backend.volumeSizes).toHaveBeenCalledTimes(2); + expect(screen.getByText("256.8kB")).toBeInTheDocument(); + }); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 48a021102..b06633e49 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1678,6 +1678,7 @@ "No image layers": "No image layers", "Instruction": "Instruction", "Volume Overview": "Volume Overview", + "Disk usage": "Disk usage", "Mountpoint": "Mountpoint", "Containers Using Volume": "Containers Using Volume", "No containers are using this volume": "No containers are using this volume", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index bde1f528e..e4359413d 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -7588,6 +7588,7 @@ "No image layers": "無映像層", "Instruction": "指令", "Volume Overview": "資料磁碟區概覽", + "Disk usage": "磁碟用量", "Mountpoint": "掛載點", "Containers Using Volume": "使用此資料磁碟區的容器", "No containers are using this volume": "沒有容器正在使用此資料磁碟區", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 49867e153..141a64627 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8123,6 +8123,7 @@ "No image layers": "无镜像层", "Instruction": "指令", "Volume Overview": "数据卷概览", + "Disk usage": "磁盘占用", "Mountpoint": "挂载点", "Containers Using Volume": "使用此数据卷的容器", "No containers are using this volume": "没有容器正在使用此数据卷",