diff --git a/plugins/devbox-provider/README.md b/plugins/devbox-provider/README.md
index 08de612a..bb3453d6 100644
--- a/plugins/devbox-provider/README.md
+++ b/plugins/devbox-provider/README.md
@@ -42,6 +42,26 @@ bb (this plugin) ──Bearer──▶ devbox-gate :8081 (in-cluster) ──your
Machines persist (`ephemeral: false`); nothing suspends them on its own.
+## Usage dashboard
+
+**Devbox machines** in the sidebar shows live usage for every instance in
+the connected project, including ones created outside bb (CLI-created
+instances are marked as such by their absence of a bb badge). Each card has
+CPU (with a sparkline), memory, disk, network in/out and uptime, and the
+page marks machines bb manages. The page reads Incus through the same
+connection token the rest of the plugin uses; it polls about every 5 seconds
+while open and stops when you leave it. Project totals are labelled
+**Allocated** because Incus reports the sum of the instances' configured
+limits there, not live usage. Nothing is stored on the server: the
+sparklines are an in-memory ring buffer that starts empty each visit.
+
+CPU percent needs two samples, so the first poll after the server restarts
+(or after an instance restarts) shows no percentage until the next one. A
+stopped instance reports disk only. The memory total falls back to the
+instance's `limits.memory` when Incus reports host memory; an instance with
+no `limits.memory` set has nothing to fall back to and reports whatever
+Incus returns.
+
## Settings
| Setting | Default | Meaning |
diff --git a/plugins/devbox-provider/app.tsx b/plugins/devbox-provider/app.tsx
index 273f7908..12265148 100644
--- a/plugins/devbox-provider/app.tsx
+++ b/plugins/devbox-provider/app.tsx
@@ -1,10 +1,14 @@
// The plugin's settings section: connect or disconnect devbox, and the
// Tailscale sign-in links of machines being created, which are the one step
// a person has to take.
+//
+// It also contributes the Devbox machines nav panel, which shows live usage
+// for every instance in the connected project while it is open.
import { useCallback, useEffect, useState } from "react";
import { definePluginApp, useBbNavigate, useRealtime, useRpc } from "@get-bb/plugin-sdk/app";
-import type { rpcContract } from "./server";
+import type { rpcContract, UsageResult, UsageRow, UsageTotals } from "./server";
import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
interface Status {
connected: boolean;
@@ -178,6 +182,298 @@ function DevboxSection() {
);
}
+// ---- Devbox machines page ------------------------------------------------
+
+const POLL_MS = 5000;
+// Roughly two and a half minutes of history at the poll interval.
+const HISTORY_LENGTH = 30;
+
+function formatBytes(bytes: number | null): string {
+ if (bytes === null) return "—";
+ if (bytes < 1024) return `${bytes} B`;
+ const units = ["KiB", "MiB", "GiB", "TiB", "PiB"];
+ let value = bytes / 1024;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`;
+}
+
+function formatPercent(value: number | null): string {
+ if (value === null) return "—";
+ return `${value.toFixed(value >= 10 ? 0 : 1)}%`;
+}
+
+function formatUptime(seconds: number | null): string {
+ if (seconds === null) return "—";
+ const days = Math.floor(seconds / 86400);
+ const hours = Math.floor((seconds % 86400) / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ if (days > 0) return `${days}d ${hours}h`;
+ if (hours > 0) return `${hours}h ${minutes}m`;
+ return `${minutes}m`;
+}
+
+// A small inline sparkline. Values are already a percentage of `max`, so the
+// chart keeps a fixed 0–100 axis instead of rescaling to the window's peak.
+function Sparkline({ values, max, className }: { values: number[]; max: number; className?: string }) {
+ if (values.length < 2) {
+ return
;
+ }
+ const points = values
+ .map((value, index) => {
+ const x = (index / (values.length - 1)) * 100;
+ const y = 100 - Math.max(0, Math.min(1, value / max)) * 100;
+ return `${x.toFixed(2)},${y.toFixed(2)}`;
+ })
+ .join(" ");
+ return (
+
+
+
+ );
+}
+
+function Meter({ used, total, label }: { used: number | null; total: number | null; label: string }) {
+ const percent = used !== null && total !== null && total > 0 ? Math.min(100, (used / total) * 100) : null;
+ return (
+
+
+ {label}
+
+ {formatBytes(used)} / {formatBytes(total)}
+
+
+
+
+ );
+}
+
+function MachineCard({ row, cpuHistory, memHistory }: { row: UsageRow; cpuHistory: number[]; memHistory: number[] }) {
+ const stopped = row.status !== "Running";
+ return (
+
+
+
+
+ {row.name}
+ {row.bb ? (
+
+ bb
+
+ ) : null}
+
+
{row.status}
+
+
+ {stopped ? (
+
Stopped — only disk is reported.
+ ) : (
+
+
+
+ CPU
+ {formatPercent(row.cpuPercent)}
+
+
+
+ {row.cores} {row.cores === 1 ? "core" : "cores"}
+
+
+
+
+ Memory
+ {formatBytes(row.memoryUsed)}
+
+
+
+ of {formatBytes(row.memoryTotal)}
+ {row.memoryTotalSource === "limit" ? " (limit)" : ""}
+
+
+
+ )}
+
+
+
+ {!stopped ? (
+
+ Net ↓ {formatBytes(row.networkIn)}
+ Net ↑ {formatBytes(row.networkOut)}
+ Up {formatUptime(row.uptimeSeconds)}
+ {row.processes !== null ? {row.processes} proc : null}
+
+ ) : null}
+
+ );
+}
+
+function AllocationBar({ totals }: { totals: UsageTotals }) {
+ const items: Array<{ key: string; label: string; value: UsageTotals["cpu"]; format: (value: number) => string }> = [
+ { key: "cpu", label: "CPU", value: totals.cpu, format: (value) => `${value} ${value === 1 ? "core" : "cores"}` },
+ { key: "memory", label: "Memory", value: totals.memory, format: formatBytes },
+ { key: "disk", label: "Disk", value: totals.disk, format: formatBytes },
+ { key: "instances", label: "Machines", value: totals.instances, format: (value) => `${value}` },
+ ];
+ return (
+
+
+
Project allocation
+ Allocated
+
+
+ {items.map(({ key, label, value, format }) => {
+ const percent = value !== null && value.limit > 0 ? Math.min(100, (value.usage / value.limit) * 100) : null;
+ return (
+
+
+ {label}
+
+ {value === null ? "—" : `${format(value.usage)} / ${format(value.limit)}`}
+
+
+
+
+ );
+ })}
+
+
+ Incus reports the sum of the instances' configured limits, not live usage.
+
+
+ );
+}
+
+function MachinesPage() {
+ const rpc = useRpc();
+ const [data, setData] = useState(null);
+ const [history, setHistory] = useState>({});
+ const [error, setError] = useState(null);
+
+ // Poll while the page is open; the timer clears on unmount, so nothing
+ // keeps polling after the developer leaves the page.
+ useEffect(() => {
+ let active = true;
+ let inFlight = false;
+ const load = () => {
+ if (inFlight) return;
+ inFlight = true;
+ rpc.call("usage").then(
+ (next) => {
+ inFlight = false;
+ if (!active) return;
+ setData(next);
+ setError(null);
+ // In-memory ring buffers, rebuilt from each poll and dropped on
+ // unmount. Nothing is persisted.
+ if (next.connected) {
+ setHistory((previous) => {
+ const updated = { ...previous };
+ const names = new Set(next.instances.map((row) => row.name));
+ for (const name of Object.keys(updated)) {
+ if (!names.has(name)) delete updated[name];
+ }
+ for (const row of next.instances) {
+ const entry = updated[row.name] ?? { cpu: [], mem: [] };
+ if (row.cpuPercent !== null) entry.cpu = [...entry.cpu, row.cpuPercent].slice(-HISTORY_LENGTH);
+ if (row.memoryUsed !== null && row.memoryTotal !== null && row.memoryTotal > 0) {
+ entry.mem = [...entry.mem, (row.memoryUsed / row.memoryTotal) * 100].slice(-HISTORY_LENGTH);
+ }
+ updated[row.name] = entry;
+ }
+ return updated;
+ });
+ }
+ },
+ (e: unknown) => {
+ inFlight = false;
+ if (!active) return;
+ setError(e instanceof Error ? e.message : String(e));
+ },
+ );
+ };
+ load();
+ const timer = setInterval(load, POLL_MS);
+ return () => {
+ active = false;
+ clearInterval(timer);
+ };
+ }, [rpc]);
+
+ if (data === null) {
+ return {error ?? "Loading devbox usage…"}
;
+ }
+
+ if (!data.connected) {
+ return (
+
+
Devbox machines
+
+ devbox is not connected. Open{" "}
+ Settings → Plugins → Devbox machines and choose{" "}
+ Connect devbox to see live usage.
+
+
+ );
+ }
+
+ return (
+
+
+
+
+ Incus · project {data.project}
+
+ Devbox machines
+
+ Live CPU, memory, disk and network for every instance in your devbox project.
+
+
+
+ {data.totals !== null ? (
+
+ ) : null}
+
+ {data.instances.length === 0 ? (
+
+ No machines in this project yet. Create one from the plugin settings or with{" "}
+ bb machine create --provider devbox.
+
+ ) : (
+
+ {data.instances.map((row) => (
+
+ ))}
+
+ )}
+
+ {error !== null ?
{error}
: null}
+
+
+ );
+}
+
export default definePluginApp((app) => {
app.slots.settingsSection({
id: "devbox",
@@ -185,4 +481,11 @@ export default definePluginApp((app) => {
description: "Your devbox project, its machines, and any waiting for Tailscale sign-in.",
component: DevboxSection,
});
+ app.slots.navPanel({
+ id: "machines",
+ title: "Devbox machines",
+ icon: "Server",
+ path: "devbox-machines",
+ component: MachinesPage,
+ });
});
diff --git a/plugins/devbox-provider/incus.test.ts b/plugins/devbox-provider/incus.test.ts
index 292dbf43..4c613517 100644
--- a/plugins/devbox-provider/incus.test.ts
+++ b/plugins/devbox-provider/incus.test.ts
@@ -13,7 +13,9 @@ function fakeIncus() {
let stdinReceived = "";
let stdinEnded = false;
let exitCode = 0;
- const instances = new Map }>();
+ const instances = new Map; state?: unknown }>();
+ let projectState: unknown = {};
+ let lastInstancesQuery: string | null = null;
const reply = (res: any, status: number, body: unknown) => {
res.writeHead(status, { "content-type": "application/json" });
@@ -42,8 +44,12 @@ function fakeIncus() {
return reply(res, 202, asyncOp("create"));
}
if (path === "/1.0/instances" && req.method === "GET") {
+ lastInstancesQuery = url.searchParams.get("recursion");
return reply(res, 200, { type: "sync", metadata: [...instances].map(([name, i]) => ({ name, ...i })) });
}
+ if (path === "/1.0/projects/dylan/state" && req.method === "GET") {
+ return reply(res, 200, { type: "sync", metadata: { resources: projectState } });
+ }
const inst = path.match(/^\/1\.0\/instances\/([^/]+)(\/.*)?$/u);
if (inst) {
const [, name, rest] = inst;
@@ -100,9 +106,19 @@ function fakeIncus() {
server,
seen,
instances,
+ setInstanceState(name: string, state: unknown) {
+ const instance = instances.get(name);
+ if (instance !== undefined) instance.state = state;
+ },
+ setProjectState(state: unknown) {
+ projectState = state;
+ },
get execBody() {
return execBody;
},
+ get lastInstancesQuery() {
+ return lastInstancesQuery;
+ },
get stdin() {
return { received: stdinReceived, ended: stdinEnded };
},
@@ -206,4 +222,40 @@ describe("instances", () => {
const incus = await client("dbx_wrong");
await expect(incus.ping(new AbortController().signal)).rejects.toThrow(/unauthorized|connect devbox again/u);
});
+
+ it("lists instances with their live state and reads the project state", async () => {
+ const incus = await client();
+ const signal = new AbortController().signal;
+ await incus.createInstance({ name: "box", image: "devbox", profiles: [], config: {} }, signal);
+ fake.setInstanceState("box", {
+ status: "Running",
+ cpu: { usage: 1_000_000_000 },
+ memory: { usage: 512, total: 1024 },
+ disk: { root: { usage: 10, total: 100 } },
+ network: { eth0: { counters: { bytes_received: 5, bytes_sent: 7 } } },
+ processes: 9,
+ started_at: "2026-10-20T17:00:00Z",
+ });
+ fake.setProjectState({
+ cpu: { limit: 12, usage: 4 },
+ memory: { limit: 48 * 1024 ** 3, usage: 16 * 1024 ** 3 },
+ disk: { limit: 250 * 1024 ** 3, usage: 40 * 1024 ** 3 },
+ instances: { limit: 6, usage: 2 },
+ });
+
+ const listed = await incus.listInstancesWithState(signal);
+ expect(listed).toHaveLength(1);
+ expect(listed[0].state).toMatchObject({ cpu: { usage: 1_000_000_000 }, processes: 9 });
+ expect(fake.seen.find((s) => s.method === "GET" && s.path === "/1.0/instances")?.path).toBe("/1.0/instances");
+ // recursion=2 is what asks Incus to embed the state.
+ expect(fake.lastInstancesQuery).toBe("2");
+
+ expect(await incus.getProjectState(signal)).toEqual({
+ cpu: { limit: 12, usage: 4 },
+ memory: { limit: 48 * 1024 ** 3, usage: 16 * 1024 ** 3 },
+ disk: { limit: 250 * 1024 ** 3, usage: 40 * 1024 ** 3 },
+ instances: { limit: 6, usage: 2 },
+ });
+ expect(fake.seen.some((s) => s.path === "/1.0/projects/dylan/state")).toBe(true);
+ });
});
diff --git a/plugins/devbox-provider/incus.ts b/plugins/devbox-provider/incus.ts
index cb9bb570..efefaff2 100644
--- a/plugins/devbox-provider/incus.ts
+++ b/plugins/devbox-provider/incus.ts
@@ -18,6 +18,37 @@ export interface Instance {
name: string;
status: string; // "Running", "Stopped", ...
config: Record;
+ // Present only on the recursion=2 listing, which embeds each instance's
+ // live state alongside its config.
+ state?: InstanceState;
+}
+
+// The subset of Incus's instance state this plugin reads. Every field is
+// optional because the shape varies with the instance's status and with the
+// Incus version behind devbox-gate.
+export interface InstanceState {
+ status?: string;
+ status_code?: number;
+ cpu?: { usage?: number };
+ memory?: { usage?: number; usage_peak?: number; total?: number; swap_usage?: number };
+ disk?: Record;
+ network?: Record;
+ processes?: number;
+ started_at?: string;
+}
+
+// A project resource cap as Incus reports it: the sum of the instances'
+// configured limits ("allocated"), not their live usage.
+export interface ProjectResource {
+ limit?: number;
+ usage?: number;
+}
+
+export interface ProjectState {
+ cpu?: ProjectResource;
+ memory?: ProjectResource;
+ disk?: ProjectResource;
+ instances?: ProjectResource;
}
export interface CreateInstance {
@@ -68,6 +99,10 @@ export interface IncusClient {
ping(signal: AbortSignal): Promise;
getInstance(name: string, signal: AbortSignal): Promise;
listInstances(signal: AbortSignal): Promise;
+ // One call that also embeds each instance's live state (recursion=2).
+ listInstancesWithState(signal: AbortSignal): Promise;
+ // The project's allocated resources: resources.{cpu,memory,disk,instances}.{limit,usage}.
+ getProjectState(signal: AbortSignal): Promise;
createInstance(spec: CreateInstance, signal: AbortSignal): Promise;
setState(name: string, action: "start" | "stop", signal: AbortSignal): Promise;
deleteInstance(name: string, signal: AbortSignal): Promise;
@@ -156,6 +191,15 @@ export function createIncusClient(cfg: IncusConfig, fetchImpl: typeof fetch = fe
const env = await call("GET", "/1.0/instances", signal, undefined, { recursion: "1" });
return Array.isArray(env.metadata) ? env.metadata.map(toInstance) : [];
},
+ async listInstancesWithState(signal) {
+ const env = await call("GET", "/1.0/instances", signal, undefined, { recursion: "2" });
+ return Array.isArray(env.metadata) ? env.metadata.map(toInstance) : [];
+ },
+ async getProjectState(signal) {
+ const env = await call("GET", `/1.0/projects/${encodeURIComponent(cfg.project)}/state`, signal);
+ const metadata = (env.metadata ?? {}) as { resources?: ProjectState };
+ return metadata.resources ?? {};
+ },
async createInstance(spec, signal) {
const env = await call("POST", "/1.0/instances", signal, {
name: spec.name,
@@ -219,8 +263,15 @@ export function createIncusClient(cfg: IncusConfig, fetchImpl: typeof fetch = fe
}
function toInstance(raw: unknown): Instance {
- const m = (raw ?? {}) as { name?: string; status?: string; config?: Record };
- return { name: m.name ?? "", status: m.status ?? "", config: m.config ?? {} };
+ const m = (raw ?? {}) as {
+ name?: string;
+ status?: string;
+ config?: Record;
+ state?: InstanceState;
+ };
+ const instance: Instance = { name: m.name ?? "", status: m.status ?? "", config: m.config ?? {} };
+ if (m.state !== undefined) instance.state = m.state;
+ return instance;
}
// Runs the four exec websockets until stdout and stderr have both closed,
diff --git a/plugins/devbox-provider/server.test.ts b/plugins/devbox-provider/server.test.ts
index fa1e3cfc..bbe20755 100644
--- a/plugins/devbox-provider/server.test.ts
+++ b/plugins/devbox-provider/server.test.ts
@@ -3,8 +3,8 @@ import type { PluginMachineProviderProgress } from "@get-bb/plugin-sdk/machine-p
import { createFakePluginHost } from "@get-bb/plugin-sdk/testing";
import { Hono } from "hono";
import { describe, expect, it, vi } from "vitest";
-import type { ExecOptions, IncusClient, Instance } from "./incus.js";
-import { createDevboxProviderPlugin, defaultMachineName, KEY_CONFIG, PROVIDER_ID } from "./server.js";
+import type { ExecOptions, IncusClient, Instance, ProjectState } from "./incus.js";
+import { chooseMemoryTotal, deriveUsage, parseCores, parseMemoryBytes, createDevboxProviderPlugin, defaultMachineName, KEY_CONFIG, PROVIDER_ID } from "./server.js";
const APP_URL = "https://bb.example";
const CALLBACK = "https://bb.example/api/v1/plugins/devbox-provider/http/connect/callback";
@@ -14,10 +14,13 @@ function fakeIncus(tailscale: Array>) {
const instances = new Map();
const execs: Array<{ name: string; options: ExecOptions }> = [];
let ts = 0;
+ const projectState: ProjectState = {};
const client: IncusClient = {
ping: vi.fn(async () => {}),
getInstance: vi.fn(async (name: string) => instances.get(name) ?? null),
listInstances: vi.fn(async () => [...instances.values()]),
+ listInstancesWithState: vi.fn(async () => [...instances.values()]),
+ getProjectState: vi.fn(async () => projectState),
createInstance: vi.fn(async (spec) => {
instances.set(spec.name, { name: spec.name, status: "Running", config: spec.config });
}),
@@ -38,7 +41,7 @@ function fakeIncus(tailscale: Array>) {
return { exitCode: 0 };
}),
};
- return { client, instances, execs };
+ return { client, instances, execs, projectState };
}
const report = (): PluginMachineProviderProgress & { lines: string[] } => {
@@ -329,3 +332,172 @@ describe("machines", () => {
expect((bootstrap.mock.calls.at(-1) as unknown[])[0]).toMatchObject({ key: "k" });
});
});
+
+describe("usage derivation", () => {
+ const instance = (over: Partial = {}): Instance => ({
+ name: "box",
+ status: "Running",
+ config: { "limits.cpu": "4" },
+ ...over,
+ });
+ const running = (cpuUsage: number): Instance =>
+ instance({
+ state: {
+ status: "Running",
+ cpu: { usage: cpuUsage },
+ memory: { usage: 1_000, total: 2_000 },
+ disk: { root: { usage: 10, total: 100 } },
+ network: { eth0: { counters: { bytes_received: 5, bytes_sent: 7 } } },
+ processes: 3,
+ started_at: "2026-10-20T17:00:00.000Z",
+ },
+ });
+
+ it("parses cores from a count, a cpuset or a list", () => {
+ expect(parseCores("4")).toBe(4);
+ expect(parseCores("0-3")).toBe(4);
+ expect(parseCores("0,2,3")).toBe(3);
+ expect(parseCores(undefined)).toBe(4);
+ expect(parseCores("junk")).toBe(4);
+ });
+
+ it("parses the memory quantities Incus accepts", () => {
+ expect(parseMemoryBytes("16GiB")).toBe(16 * 1024 ** 3);
+ expect(parseMemoryBytes("512MiB")).toBe(512 * 1024 ** 2);
+ expect(parseMemoryBytes("1073741824")).toBe(1_073_741_824);
+ expect(parseMemoryBytes("nonsense")).toBeNull();
+ expect(parseMemoryBytes(undefined)).toBeNull();
+ });
+
+ it("derives CPU percent from the delta over wall time and cores", () => {
+ const samples = new Map();
+ // First sample: no percent yet.
+ expect(deriveUsage([running(1_000_000_000)], new Set(), samples, 1_000_000)[0].cpuPercent).toBeNull();
+ // +2 CPU-seconds over 1 wall second across 4 cores = 50%.
+ const second = deriveUsage([running(3_000_000_000)], new Set(), samples, 1_001_000)[0];
+ expect(second.cpuPercent).toBeCloseTo(50);
+ expect(second.cores).toBe(4);
+ });
+
+ it("reports no percent on a counter reset rather than a negative one", () => {
+ const samples = new Map();
+ deriveUsage([running(5_000_000_000)], new Set(), samples, 1_000_000);
+ const reset = deriveUsage([running(1_000)], new Set(), samples, 1_001_000)[0];
+ expect(reset.cpuPercent).toBeNull();
+ });
+
+ it("falls back to limits.memory when memory.total looks like host memory", () => {
+ const withTotal = (total: number, limits: string) =>
+ deriveUsage(
+ [instance({ config: { "limits.cpu": "4", "limits.memory": limits }, state: { status: "Running", memory: { usage: 100, total } } })],
+ new Set(),
+ new Map(),
+ 1_000_000,
+ )[0];
+ const hostLooking = withTotal(64 * 1024 ** 3, "16GiB");
+ expect(hostLooking.memoryTotal).toBe(16 * 1024 ** 3);
+ expect(hostLooking.memoryTotalSource).toBe("limit");
+ const within = withTotal(8 * 1024 ** 3, "16GiB");
+ expect(within.memoryTotal).toBe(8 * 1024 ** 3);
+ expect(within.memoryTotalSource).toBe("state");
+ expect(chooseMemoryTotal(null, 1024)).toEqual({ total: 1024, source: "limit" });
+ expect(chooseMemoryTotal(null, null)).toEqual({ total: null, source: null });
+ });
+
+ it("gives a stopped instance disk only", () => {
+ const stopped = instance({
+ status: "Stopped",
+ state: { status: "Stopped", disk: { root: { usage: 40, total: 100 } } },
+ });
+ const row = deriveUsage([stopped], new Set(), new Map(), 1_000_000)[0];
+ expect(row.status).toBe("Stopped");
+ expect(row.cpuPercent).toBeNull();
+ expect(row.memoryUsed).toBeNull();
+ expect(row.memoryTotal).toBeNull();
+ expect(row.networkIn).toBe(0);
+ expect(row.networkOut).toBe(0);
+ expect(row.uptimeSeconds).toBeNull();
+ expect(row.diskUsed).toBe(40);
+ expect(row.diskTotal).toBe(100);
+ });
+
+ it("marks bb machines by key or by the host list", () => {
+ const byKey = instance({ name: "mine", config: { [KEY_CONFIG]: "k" } });
+ const byHost = instance({ name: "box", config: {} });
+ const foreign = instance({ name: "cli", config: {} });
+ const rows = deriveUsage([byKey, byHost, foreign], new Set(["box"]), new Map(), 1_000_000);
+ expect(rows.map((row) => row.bb)).toEqual([true, true, false]);
+ });
+
+ it("prunes samples for instances that left the listing", () => {
+ const samples = new Map([["gone", { usage: 1, at: 1 }]]);
+ deriveUsage([instance({ name: "kept" })], new Set(), samples, 2);
+ expect(samples.has("gone")).toBe(false);
+ });
+});
+
+describe("usage rpc", () => {
+ it("reports not connected when there is no token", async () => {
+ const { harness } = await setup();
+ expect(await harness.callRpc("usage", null)).toEqual({ connected: false, project: null, instances: [], totals: null });
+ });
+
+ it("returns one row per instance, bb marking, and allocated totals", async () => {
+ const { harness, incus } = await setup({ token: "dbx_abc" });
+ incus.instances.set("mine", {
+ name: "mine",
+ status: "Running",
+ config: { [KEY_CONFIG]: "k" },
+ state: {
+ status: "Running",
+ cpu: { usage: 1_000_000_000 },
+ memory: { usage: 1_000, total: 2_000 },
+ disk: { root: { usage: 10, total: 100 } },
+ network: { eth0: { counters: { bytes_received: 5, bytes_sent: 7 } } },
+ processes: 3,
+ },
+ });
+ // A CLI-created instance is listed too, and marked via the host list.
+ incus.instances.set("box", { name: "box", status: "Stopped", config: {}, state: { status: "Stopped", disk: { root: { usage: 1, total: 2 } } } });
+ Object.assign(incus.projectState, {
+ cpu: { limit: 12, usage: 4 },
+ memory: { limit: 48 * 1024 ** 3, usage: 16 * 1024 ** 3 },
+ disk: { limit: 250 * 1024 ** 3, usage: 40 * 1024 ** 3 },
+ instances: { limit: 6, usage: 2 },
+ } satisfies ProjectState);
+
+ const result = (await harness.callRpc("usage", null)) as {
+ connected: boolean;
+ project: string;
+ instances: Array<{ name: string; bb: boolean; status: string; cpuPercent: number | null }>;
+ totals: unknown;
+ };
+ expect(result.connected).toBe(true);
+ expect(result.project).toBe("dylan");
+ expect(result.instances.map((row) => row.name).sort()).toEqual(["box", "mine"]);
+ expect(result.instances.find((row) => row.name === "mine")!.bb).toBe(true);
+ expect(result.instances.find((row) => row.name === "box")!.bb).toBe(true);
+ // The first sample has no CPU percent.
+ expect(result.instances.find((row) => row.name === "mine")!.cpuPercent).toBeNull();
+ expect(result.totals).toEqual({
+ cpu: { limit: 12, usage: 4 },
+ memory: { limit: 48 * 1024 ** 3, usage: 16 * 1024 ** 3 },
+ disk: { limit: 250 * 1024 ** 3, usage: 40 * 1024 ** 3 },
+ instances: { limit: 6, usage: 2 },
+ });
+ });
+
+ it("still returns the rows when the project state read fails", async () => {
+ const { harness, incus } = await setup({ token: "dbx_abc" });
+ incus.instances.set("mine", {
+ name: "mine",
+ status: "Running",
+ config: { [KEY_CONFIG]: "k" },
+ state: { status: "Running", disk: { root: { usage: 1, total: 2 } } },
+ });
+ vi.mocked(incus.client.getProjectState).mockRejectedValueOnce(new Error("forbidden"));
+ const result = (await harness.callRpc("usage", null)) as { instances: unknown[]; totals: unknown };
+ expect(result.instances).toHaveLength(1);
+ expect(result.totals).toBeNull();
+ });
+});
diff --git a/plugins/devbox-provider/server.ts b/plugins/devbox-provider/server.ts
index 060e1254..9b1373e0 100644
--- a/plugins/devbox-provider/server.ts
+++ b/plugins/devbox-provider/server.ts
@@ -21,7 +21,7 @@ import {
revokeToken,
type PendingConnect,
} from "./connect.js";
-import { createIncusClient, type IncusClient, type IncusConfig } from "./incus.js";
+import { createIncusClient, type IncusClient, type IncusConfig, type Instance, type ProjectState } from "./incus.js";
import {
LOGOUT_COMMAND,
parseTailscaleStatus,
@@ -60,6 +60,215 @@ const machineSummarySchema = z.object({
status: z.string(),
});
+// The devbox profile caps a machine at four cores unless it says otherwise.
+const DEFAULT_CORES = 4;
+const USAGE_TIMEOUT_MS = 10_000;
+
+const projectResourceSchema = z.object({ limit: z.number(), usage: z.number() });
+
+const usageRowSchema = z.object({
+ name: z.string(),
+ bb: z.boolean(),
+ status: z.string(),
+ // null until a second sample exists, or after a restart/counter reset.
+ cpuPercent: z.number().nullable(),
+ cores: z.number(),
+ memoryUsed: z.number().nullable(),
+ memoryTotal: z.number().nullable(),
+ // "state" when Incus reported it, "limit" when limits.memory stood in.
+ memoryTotalSource: z.enum(["state", "limit"]).nullable(),
+ diskUsed: z.number().nullable(),
+ diskTotal: z.number().nullable(),
+ networkIn: z.number(),
+ networkOut: z.number(),
+ uptimeSeconds: z.number().nullable(),
+ processes: z.number().nullable(),
+});
+export type UsageRow = z.infer;
+
+const usageTotalsSchema = z.object({
+ cpu: projectResourceSchema.nullable(),
+ memory: projectResourceSchema.nullable(),
+ disk: projectResourceSchema.nullable(),
+ instances: projectResourceSchema.nullable(),
+});
+export type UsageTotals = z.infer;
+
+export interface UsageResult {
+ connected: boolean;
+ project: string | null;
+ instances: UsageRow[];
+ totals: UsageTotals | null;
+}
+
+export interface CpuSample {
+ usage: number;
+ at: number;
+}
+
+// limits.cpu is a count ("4"), a cpuset ("0-3") or a list ("0,2,3").
+export function parseCores(value: string | undefined): number {
+ const text = value?.trim() ?? "";
+ if (/^\d+$/u.test(text)) {
+ const count = Number(text);
+ return count > 0 ? count : DEFAULT_CORES;
+ }
+ let count = 0;
+ for (const part of text.split(",")) {
+ const range = /^(\d+)-(\d+)$/u.exec(part.trim());
+ if (range !== null) {
+ const from = Number(range[1]);
+ const to = Number(range[2]);
+ if (to >= from) count += to - from + 1;
+ } else if (/^\d+$/u.test(part.trim())) {
+ count += 1;
+ }
+ }
+ return count > 0 ? count : DEFAULT_CORES;
+}
+
+const MEMORY_UNITS: Record = {
+ B: 1,
+ KB: 1000,
+ MB: 1000 ** 2,
+ GB: 1000 ** 3,
+ TB: 1000 ** 4,
+ KIB: 1024,
+ MIB: 1024 ** 2,
+ GIB: 1024 ** 3,
+ TIB: 1024 ** 4,
+};
+
+// Parses the byte quantities Incus accepts for limits.memory ("16GiB", "512MB",
+// or a plain byte count). Returns null for anything else.
+export function parseMemoryBytes(value: string | undefined): number | null {
+ if (value === undefined) return null;
+ const match = /^(\d+(?:\.\d+)?)\s*([a-zA-Z]+)?$/u.exec(value.trim());
+ if (match === null) return null;
+ const amount = Number(match[1]);
+ const unit = (match[2] ?? "B").toUpperCase();
+ const factor = MEMORY_UNITS[unit];
+ if (!Number.isFinite(amount) || amount <= 0 || factor === undefined) return null;
+ return Math.round(amount * factor);
+}
+
+// Incus can report the host's memory in state.memory.total when the instance
+// limit is a soft cap (the profile sets limits.memory: 16GiB). When the
+// reported total exceeds the configured limit, the limit is the truth.
+export function chooseMemoryTotal(
+ stateTotal: number | null,
+ limitBytes: number | null,
+): { total: number | null; source: "state" | "limit" | null } {
+ if (limitBytes !== null && (stateTotal === null || stateTotal > limitBytes)) return { total: limitBytes, source: "limit" };
+ if (stateTotal !== null) return { total: stateTotal, source: "state" };
+ return { total: null, source: null };
+}
+
+function toResource(resource: { limit?: number; usage?: number } | undefined): z.infer | null {
+ if (resource === undefined || typeof resource.limit !== "number" || typeof resource.usage !== "number") return null;
+ return { limit: resource.limit, usage: resource.usage };
+}
+
+// Turns the project state into the four rows the page shows, labelled
+// "allocated": Incus sums the instances' configured limits here, not live use.
+export function projectTotals(state: ProjectState) {
+ return {
+ cpu: toResource(state.cpu),
+ memory: toResource(state.memory),
+ disk: toResource(state.disk),
+ instances: toResource(state.instances),
+ };
+}
+
+// Derives one row per instance from a state listing. CPU percent is the CPU
+// time used between the previous sample and this one, over wall-clock time and
+// the instance's core count; it is null on the first sample and when the
+// counter goes backwards (a restart). Stopped instances contribute disk only.
+// `samples` is the in-memory previous sample per instance and is updated here.
+export function deriveUsage(
+ instances: Instance[],
+ bbNames: ReadonlySet,
+ samples: Map,
+ now: number,
+): UsageRow[] {
+ const rows: UsageRow[] = [];
+ for (const instance of instances) {
+ const state = instance.state;
+ const status = state?.status ?? instance.status;
+ const running = status === "Running";
+ const cores = parseCores(instance.config["limits.cpu"]);
+ const disk = state?.disk?.root;
+ let cpuPercent: number | null = null;
+ let memoryUsed: number | null = null;
+ let memoryTotal: number | null = null;
+ let memoryTotalSource: "state" | "limit" | null = null;
+ let networkIn = 0;
+ let networkOut = 0;
+ let uptimeSeconds: number | null = null;
+ let processes: number | null = null;
+
+ if (running) {
+ const usage = state?.cpu?.usage;
+ if (typeof usage === "number" && Number.isFinite(usage)) {
+ const previous = samples.get(instance.name);
+ if (previous !== undefined && usage >= previous.usage && now > previous.at) {
+ const cpuSeconds = (usage - previous.usage) / 1e9;
+ const wallSeconds = (now - previous.at) / 1000;
+ // Capped at 100% of the allocated cores; a lower clamp guards a
+ // counter that advanced while wall time did not.
+ cpuPercent = Math.max(0, Math.min(100, (cpuSeconds / wallSeconds / cores) * 100));
+ }
+ samples.set(instance.name, { usage, at: now });
+ } else {
+ samples.delete(instance.name);
+ }
+
+ const memory = state?.memory;
+ const stateTotal = typeof memory?.total === "number" && Number.isFinite(memory.total) ? memory.total : null;
+ const chosen = chooseMemoryTotal(stateTotal, parseMemoryBytes(instance.config["limits.memory"]));
+ memoryTotal = chosen.total;
+ memoryTotalSource = chosen.source;
+ memoryUsed = typeof memory?.usage === "number" && Number.isFinite(memory.usage) ? memory.usage : null;
+
+ for (const iface of Object.values(state?.network ?? {})) {
+ if (typeof iface?.counters?.bytes_received === "number") networkIn += iface.counters.bytes_received;
+ if (typeof iface?.counters?.bytes_sent === "number") networkOut += iface.counters.bytes_sent;
+ }
+ if (typeof state?.processes === "number") processes = state.processes;
+ if (typeof state?.started_at === "string") {
+ const started = Date.parse(state.started_at);
+ if (Number.isFinite(started) && started <= now) uptimeSeconds = Math.round((now - started) / 1000);
+ }
+ } else {
+ samples.delete(instance.name);
+ }
+
+ rows.push({
+ name: instance.name,
+ bb: instance.config[KEY_CONFIG] !== undefined || bbNames.has(instance.name),
+ status,
+ cpuPercent,
+ cores,
+ memoryUsed,
+ memoryTotal,
+ memoryTotalSource,
+ diskUsed: typeof disk?.usage === "number" ? disk.usage : null,
+ diskTotal: typeof disk?.total === "number" ? disk.total : null,
+ networkIn,
+ networkOut,
+ uptimeSeconds,
+ processes,
+ });
+ }
+ // Drop samples for instances that left the listing, so the map does not
+ // grow by one name per instance ever seen.
+ const present = new Set(instances.map((instance) => instance.name));
+ for (const name of samples.keys()) {
+ if (!present.has(name)) samples.delete(name);
+ }
+ return rows;
+}
+
export const rpcContract = defineRpcContract({
status: {
input: z.null(),
@@ -86,6 +295,17 @@ export const rpcContract = defineRpcContract({
input: z.null(),
output: z.object({ ok: z.boolean() }),
},
+ // Live usage for every instance in the project, plus the project's
+ // allocated caps. Read-only; the page polls it while open.
+ usage: {
+ input: z.null(),
+ output: z.object({
+ connected: z.boolean(),
+ project: z.string().nullable(),
+ instances: z.array(usageRowSchema),
+ totals: usageTotalsSchema.nullable(),
+ }),
+ },
});
export const SETTING_DESCRIPTORS = {
@@ -224,6 +444,10 @@ export function createDevboxProviderPlugin(deps: DevboxProviderDeps): (bb: BbPlu
return async (bb) => {
const settings = bb.settings.define(SETTING_DESCRIPTORS);
+ // Previous CPU counter per instance, for the delta between polls. In
+ // memory only: a restart resets it, which just costs one sample.
+ const cpuSamples = new Map();
+
// ---- the connection ---------------------------------------------------
const pendingKey = (state: string) => `connect/pending/${state}`;
@@ -338,9 +562,37 @@ export function createDevboxProviderPlugin(deps: DevboxProviderDeps): (bb: BbPlu
}
await settings.experimental_set({ token: null });
await bb.storage.kv.delete(CONNECTION_KEY);
+ cpuSamples.clear();
bb.realtime.publish(CONNECTION_CHANGED, { connected: false });
return { ok: true };
},
+ async usage() {
+ const cfg = await settings.get();
+ if ((cfg.token?.trim() ?? "") === "") {
+ return { connected: false, project: null, instances: [], totals: null };
+ }
+ const signal = AbortSignal.timeout(USAGE_TIMEOUT_MS);
+ const { incus, project } = await connection(signal);
+ const [instances, projectState, hosts] = await Promise.all([
+ incus.listInstancesWithState(signal),
+ // A project-state problem (an endpoint the restricted cert cannot
+ // read, a shape change) must not take the per-machine cards down.
+ incus.getProjectState(signal).catch((error: unknown) => {
+ bb.log.warn(`could not read devbox project state: ${errorMessage(error)}`);
+ return null;
+ }),
+ bb.sdk.hosts.list(),
+ ]);
+ const bbNames = new Set(
+ hosts.filter((host) => host.machineProviderId === PROVIDER_ID).map((host) => host.name),
+ );
+ return {
+ connected: true,
+ project,
+ instances: deriveUsage(instances, bbNames, cpuSamples, deps.now()),
+ totals: projectState === null ? null : projectTotals(projectState),
+ };
+ },
});
// devbox sends the browser here after approval. "none" because the