Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): processor, memory and disk on Home, a Space's page and the menu bar (CUA-1880) (#5458)
Francesco Bonacci46907096b351
diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex 80cde5da48..7fe350bc33 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -28,6 +28,7 @@ import { notificationsMethods } from "./notifications";import { onboardingMethods } from "./onboarding";import { presenceMethods } from "./presence";import { relayUsageMethods } from "./relay-usage";+import { resourcesMethods } from "./resources";import { sessionMethods, sessionState } from "./session";import { settingsMethods } from "./settings";import { sharingMethods } from "./sharing";@@ -69,6 +70,7 @@ export const AREAS = [streamMethods,onboardingMethods,relayUsageMethods,+ resourcesMethods,checklistMethods,presenceMethods,];diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 5c01aa16a6..3e6dd1bf64 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -44,6 +44,7 @@ export const METHODS = ["window.setBackgroundColor", "window.setDragRegions", "window.setDropTargets","startup.get", "startup.act","relay.usage",+ "resources.get","checklist.get", "checklist.send",] as const;diff --git a/apps/cua-spaces-desktop/src/bridge/resources.ts b/apps/cua-spaces-desktop/src/bridge/resources.tsnew file mode 100644index 0000000000..6bb9adea55--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/resources.ts@@ -0,0 +1,96 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// `resources.get` (CUA-1880): this computer's processor, memory and disk,+// read by the app itself, as the SwiftUI host's `HostResourceSampler` does.+// Busy is the share of non-idle processor time since the last read; disk is+// the volume holding the home folder (where Spaces live). Numbers only:+// never file names, paths or process names. The daemon's per-Space numbers+// join these once it serves its `resources` snapshot.+import { statfsSync } from "node:fs";+import * as os from "node:os";+import type { BridgeContext } from "./context";+import type { Handlers } from "./host";++interface Ticks {+ busy: number;+ total: number;+}++function ticks(): Ticks {+ let busy = 0;+ let total = 0;+ for (const c of os.cpus()) {+ const t = c.times;+ busy += t.user + t.nice + t.sys + t.irq;+ total += t.user + t.nice + t.sys + t.irq + t.idle;+ }+ return { busy, total };+}++/** Free and total bytes on the volume holding `dir`; zeros when it can't be read. */+export function diskOf(dir: string): { totalBytes: number; freeBytes: number } {+ try {+ const s = statfsSync(dir);+ return { totalBytes: s.blocks * s.bsize, freeBytes: s.bavail * s.bsize };+ } catch {+ return { totalBytes: 0, freeBytes: 0 };+ }+}++const GB = 1_000_000_000;+const GIB = 1024 ** 3;++/** The daemon's warning rule: `low` under 50 GB or 15% free, whichever line+ * is higher, capped at 100 GB; `critical` under 5 GiB. */+export function diskWarning(free: number, total: number) {+ if (total <= 0) return { level: "ok" as const, free, total, threshold: 0 };+ if (free < 5 * GIB) return { level: "critical" as const, free, total, threshold: 5 * GIB };+ const line = Math.min(Math.max(50 * GB, total * 0.15), 100 * GB);+ return free < line ? { level: "low" as const, free, total, threshold: line } : { level: "ok" as const, free, total, threshold: 0 };+}++/** `resources.get`: the contract's `ResourcesSnapshot` with this computer+ * only (no Space numbers until the daemon serves them). */+export function resourcesMethods(_ctx: BridgeContext, read: { ticks: () => Ticks; now: () => number; home: () => string } = { ticks, now: Date.now, home: os.homedir }): Handlers {+ let last: Ticks | null = null;+ return {+ "resources.get": async () => {+ const now = read.ticks();+ const cpuPercent = last && now.total > last.total ? Math.min(100, Math.max(0, ((now.busy - last.busy) / (now.total - last.total)) * 100)) : 0;+ last = now;+ const memoryTotal = os.totalmem();+ const { totalBytes: diskTotal, freeBytes: diskFree } = diskOf(read.home());+ const warning = diskWarning(diskFree, diskTotal);+ const ms = read.now();+ return {+ sequence: Math.floor(ms / 10_000),+ sampledAtMs: ms,+ thisMac: {+ id: "this-mac",+ name: "",+ online: true,+ sampledAtMs: ms,+ cpuCount: os.cpus().length,+ cpuPercent,+ loadAverage1m: os.loadavg()[0] ?? 0,+ memoryTotal,+ memoryUsed: memoryTotal - os.freemem(),+ diskTotal,+ diskFree,+ spacesCount: 0,+ spacesRunning: 0,+ spacesCpuAllocated: 0,+ spacesMemoryAllocated: 0,+ spacesMemoryUsed: 0,+ spacesDiskBytes: 0,+ spacesDiskExact: true,+ warning,+ },+ spaces: [],+ computers: [],+ warning,+ };+ },+ };+}diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.tsindex ebc1869da2..1c79539228 100644--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts@@ -176,8 +176,8 @@ describe.skipIf(!built)("the bridge on the app core", () => {for (const [method, args] of cases) problems.push(...shapeProblems(method, await call(method, args)));expect(problems).toEqual([]);// Every ported method has its case (or is checked below).- // (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; presence: presence-bridge.test.ts; the Windows runtime fix: below.)- const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);+ // (Teleport and the Keyvault: vault-native.test.ts; This machine, Devices, Settings and the rest: host-bridge.test.ts; the relay allowance: relay-usage.test.ts; resource numbers: resources.test.ts; presence: presence-bridge.test.ts; the Windows runtime fix: below.)+ const elsewhere = new Set(["session.signIn", "spaces.create", "spaces.delete", "spaces.openStream", "relay.usage", "resources.get", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...AGENT_METHODS, ...VAULT_METHODS, ...HOST_METHODS]);const ported = bridge.registry.methods.filter((m) => !NOT_YET.includes(m) && !elsewhere.has(m));expect(ported.filter((m) => !cases.some(([c]) => c === m))).toEqual([]);});@@ -551,7 +551,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {"checklist.send": { action: { type: "done", step: "teleport" } },};// This machine, Devices, Settings and the rest: host-bridge.test.ts reads them with their arguments.- const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...VAULT_OPS, ...(HOST_OPS as OpName[])]);+ const skip = new Set<OpName>(["spaces.create", "spaces.delete", "session.signIn", "session.signOut", "session.openExternal", "spaces.openStream", "relay.usage", "resources.get", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime", ...VAULT_OPS, ...(HOST_OPS as OpName[])]);const problems: string[] = [];const checked: string[] = [];for (const op of OPERATIONS) {diff --git a/apps/cua-spaces-desktop/test/resources.test.ts b/apps/cua-spaces-desktop/test/resources.test.tsnew file mode 100644index 0000000000..e437f90ae8--- /dev/null+++ b/apps/cua-spaces-desktop/test/resources.test.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// `resources.get`: this computer's numbers in the page's shape, checked+// against the web contract; busy from the second read on.+import { describe, expect, it } from "vitest";+import { OP_SHAPES, SHAPE_DEFS } from "../../cua-spaces-web/src/bridge/contracts/shapes";+import { validate } from "../../cua-spaces-web/src/bridge/contracts/schema";+import type { BridgeContext } from "../src/bridge/context";+import { diskWarning, resourcesMethods } from "../src/bridge/resources";++describe("resources.get", () => {+ it("answers this computer's numbers in the contract's shape, busy from the second read", async () => {+ let n = 0;+ const ticks = () => (n++ === 0 ? { busy: 100, total: 1000 } : { busy: 400, total: 2000 });+ const get = resourcesMethods({} as BridgeContext, { ticks, now: () => 42, home: () => process.cwd() })["resources.get"]!;+ const first = (await get({}, {})) as { thisMac: { cpuPercent: number; diskTotal: number; sampledAtMs: number }; spaces: unknown[] };+ expect(validate(OP_SHAPES["resources.get"], first, SHAPE_DEFS)).toEqual([]);+ expect(first.thisMac.cpuPercent).toBe(0);+ expect(first.thisMac.diskTotal).toBeGreaterThan(0);+ expect(first.thisMac.sampledAtMs).toBe(42);+ expect(first.spaces).toEqual([]);+ const second = (await get({}, {})) as typeof first;+ expect(second.thisMac.cpuPercent).toBe(30);+ });++ it("warns as the daemon does", () => {+ const GB = 1e9;+ expect(diskWarning(90 * GB, 1000 * GB).level).toBe("low");+ expect(diskWarning(120 * GB, 1000 * GB).level).toBe("ok");+ expect(diskWarning(45 * GB, 256 * GB).level).toBe("low");+ expect(diskWarning(4 * GB, 1000 * GB).level).toBe("critical");+ });+});diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swiftnew file mode 100644index 0000000000..1a255b7999--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swift@@ -0,0 +1,189 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import Foundation+import Observation++/// This Mac's processor, memory and disk (CUA-1880), read by the app itself:+/// the core count, how busy the cores were since the last read, memory in+/// use, and the free space on the volume that holds your home folder (where+/// Spaces live). Numbers only: never file names, paths or process names.+///+/// The daemon's `resources` snapshot adds each Space's numbers; until a+/// build carries it, the page's `resources.get` and the menu bar warning use+/// this sample.+public struct HostResourceSample: Equatable, Sendable {+ public var cores: Int+ /// 0 to 100 since the last sample; nil on the first.+ public var busyPercent: Double?+ public var memoryTotal: UInt64+ public var memoryUsed: UInt64?+ public var diskTotal: Int64+ public var diskFree: Int64++ public init(cores: Int, busyPercent: Double?, memoryTotal: UInt64, memoryUsed: UInt64?, diskTotal: Int64, diskFree: Int64) {+ self.cores = cores+ self.busyPercent = busyPercent+ self.memoryTotal = memoryTotal+ self.memoryUsed = memoryUsed+ self.diskTotal = diskTotal+ self.diskFree = diskFree+ }++ /// `resources.get`'s snapshot with this Mac only (the "API (as built)"+ /// `ResourcesSnapshot`): no Space numbers until the daemon serves them.+ func snapshot(now: Date = Date()) -> [String: Any] {+ let ms = Int64(now.timeIntervalSince1970 * 1000)+ let warning = DiskWarning(free: diskFree, total: diskTotal).wire(free: diskFree, total: diskTotal)+ let busy = busyPercent ?? 0+ let thisMac: [String: Any] = [+ "id": "this-mac", "name": "", "online": true, "sampledAtMs": ms,+ "cpuCount": cores, "cpuPercent": busy, "loadAverage1m": Self.loadAverage(),+ "memoryTotal": memoryTotal, "memoryUsed": memoryUsed ?? 0,+ "diskTotal": diskTotal, "diskFree": diskFree,+ "spacesCount": 0, "spacesRunning": 0, "spacesCpuAllocated": 0, "spacesMemoryAllocated": 0,+ "spacesMemoryUsed": 0, "spacesDiskBytes": 0, "spacesDiskExact": true,+ "warning": warning,+ ]+ return ["sequence": ms / 10_000, "sampledAtMs": ms, "thisMac": thisMac, "spaces": [Any](), "computers": [Any](), "warning": warning]+ }++ static func loadAverage() -> Double {+ var loads = [Double](repeating: 0, count: 3)+ return getloadavg(&loads, 3) > 0 ? loads[0] : 0+ }+}++/// How close the disk is to full (the web UI's `diskWarningFor`, the spec's+/// thresholds): `low` under 50 GB or 15% free, whichever comes first, never+/// above 100 GB; `critical` under 5 GiB, where new Spaces already fail.+public enum DiskWarning: String, Equatable, Sendable {+ case none, low, critical++ /// The contract's `DiskWarning` (`level` is `ok`, `low` or `critical`).+ func wire(free: Int64, total: Int64) -> [String: Any] {+ let gb: Double = 1_000_000_000+ let threshold: Double+ switch self {+ case .none: threshold = 0+ case .low: threshold = min(max(50 * gb, Double(total) * 0.15), 100 * gb)+ case .critical: threshold = 5 * 1_073_741_824+ }+ return ["level": self == .none ? "ok" : rawValue, "free": free, "total": total, "threshold": Int64(threshold)]+ }++ public init(free: Int64, total: Int64) {+ let gb: Double = 1_000_000_000+ if Double(free) < 5 * 1_073_741_824 { self = .critical; return }+ let line = min(max(50 * gb, Double(total) * 0.15), 100 * gb)+ self = Double(free) < line ? .low : .none+ }++ /// The menu bar's words, or nil when there's room.+ public var menuText: String? {+ switch self {+ case .none: return nil+ case .low: return "This Mac is almost out of space. Delete old Spaces or snapshots."+ case .critical: return "This Mac is out of space. Delete old Spaces or snapshots."+ }+ }+}++/// Reads `HostResourceSample`s; keeps the last processor ticks so each read+/// says how busy the cores were since the one before.+public final class HostResourceSampler: @unchecked Sendable {+ public static let shared = HostResourceSampler()++ private let lock = NSLock()+ private var lastTicks: (busy: UInt64, total: UInt64)?+ private let volume: URL++ public init(volume: URL = FileManager.default.homeDirectoryForCurrentUser) {+ self.volume = volume+ }++ public func sample() -> HostResourceSample {+ let disk = Self.disk(volume)+ return HostResourceSample(+ cores: ProcessInfo.processInfo.activeProcessorCount,+ busyPercent: busy(),+ memoryTotal: ProcessInfo.processInfo.physicalMemory,+ memoryUsed: Self.memoryUsed(),+ diskTotal: disk.total,+ diskFree: disk.free+ )+ }++ /// Free and total bytes on the volume holding `url`.+ public static func disk(_ url: URL) -> (total: Int64, free: Int64) {+ let keys: Set<URLResourceKey> = [.volumeTotalCapacityKey, .volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey]+ guard let v = try? url.resourceValues(forKeys: keys) else { return (0, 0) }+ let free = v.volumeAvailableCapacityForImportantUsage ?? Int64(v.volumeAvailableCapacity ?? 0)+ return (Int64(v.volumeTotalCapacity ?? 0), free)+ }++ /// Active, wired and compressed memory.+ static func memoryUsed() -> UInt64? {+ var stats = vm_statistics64()+ var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size)+ let result = withUnsafeMutablePointer(to: &stats) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) }+ }+ guard result == KERN_SUCCESS else { return nil }+ let page = UInt64(sysconf(_SC_PAGESIZE))+ return (UInt64(stats.active_count) + UInt64(stats.wire_count) + UInt64(stats.compressor_page_count)) * page+ }++ private func busy() -> Double? {+ var info = host_cpu_load_info()+ var count = mach_msg_type_number_t(MemoryLayout<host_cpu_load_info>.size / MemoryLayout<integer_t>.size)+ let result = withUnsafeMutablePointer(to: &info) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &count) }+ }+ guard result == KERN_SUCCESS else { return nil }+ let t = info.cpu_ticks+ let user = UInt64(t.0), system = UInt64(t.1), idle = UInt64(t.2), nice = UInt64(t.3)+ let now = (busy: user + system + nice, total: user + system + idle + nice)+ lock.lock()+ defer { lock.unlock() }+ let before = lastTicks+ lastTicks = now+ guard let before, now.total > before.total else { return nil }+ return min(100, max(0, Double(now.busy - before.busy) / Double(now.total - before.total) * 100))+ }+}++/// The menu bar's low-disk warning: This Mac's free space, read every 5+/// minutes (statvfs is cheap) whether or not a window is open. Nothing+/// when there's room.+@MainActor+@Observable+public final class LowDiskMonitor {+ public static let shared = LowDiskMonitor()++ public private(set) var warning: DiskWarning = .none+ @ObservationIgnored private var timer: Timer?+ @ObservationIgnored private let read: () -> (total: Int64, free: Int64)++ public init(read: @escaping () -> (total: Int64, free: Int64) = { HostResourceSampler.disk(FileManager.default.homeDirectoryForCurrentUser) }) {+ self.read = read+ }++ public static let interval: TimeInterval = 5 * 60++ /// Reads now, then every 5 minutes.+ public func start() {+ guard timer == nil else { return }+ refresh()+ timer = Timer.scheduledTimer(withTimeInterval: Self.interval, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.refresh() }+ }+ }++ public func refresh() {+ let disk = read()+ // A volume that can't be read says nothing.+ warning = disk.total > 0 ? DiskWarning(free: disk.free, total: disk.total) : .none+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex 9c8d36a0e6..a27a9c46a4 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -169,10 +169,25 @@ struct GettingStartedCommand: View {/// The menu bar item's menu: the core's items in order.struct MenuBarContent: View {let model: AppModel+ var disk: LowDiskMonitor = .shared@Environment(\.openWindow) private var openWindow@Environment(\.openSettings) private var openSettingsvar body: some View {+ // This Mac is short of space: the warning, with the Cua key, first.+ // Nothing when there's room. It opens the Spaces, biggest first.+ if let text = disk.warning.menuText {+ Button {+ MainUIRouter(model: model).open(.path("/spaces?sort=size")) { activate(); openWindow(id: "main") }+ } label: {+ if let key = MenuBarKey.image {+ Label { Text(text) } icon: { Image(nsImage: key) }+ } else {+ Text(text)+ }+ }+ Divider()+ }ForEach(Array(model.menuBar.enumerated()), id: \.offset) { _, item inswitch item.id {case .status: Text(item.label)@@ -216,6 +231,15 @@ struct MenuBarContent: View {private func activate() { NSApp.activate() }}+/// The Cua key at menu item size, for the low-disk warning.+enum MenuBarKey {+ static let image: NSImage? = {+ guard let key = CuaKey.image?.copy() as? NSImage else { return nil }+ key.size = NSSize(width: 16, height: 16)+ return key+ }()+}+/// The Cua mark as a template image (from apps/cua-spaces/src-tauri/icons,/// copied into the bundle by scripts/build-app.sh).enum MenuBarIcon {@@ -274,6 +298,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {func applicationDidFinishLaunching(_ notification: Notification) {start(Self.model)+ // The menu bar's low-disk warning: read now, then every 5 minutes.+ LowDiskMonitor.shared.start()}/// The Dock icon (or opening the app again) with no window up: the maindiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 8a8c6194ab..ef9e9d4dae 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -139,6 +139,12 @@ extension WebUIBridge {guard let usage = try await relay.relayUsage(), usage.metered else { return NSNull() }return BridgeValue.encode(usage)+ // Processor, memory and disk for Home and a Space's page: This+ // Mac's own numbers (`HostResourceSampler`), read on each call. The+ // daemon's per-Space numbers join them once it serves `resources`.+ case "resources.get":+ return HostResourceSampler.shared.sample().snapshot()+// Settings, Storagecase "storage.get":let storage = model.storagediff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex a4d6e20a6a..e7fb661a3c 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -112,6 +112,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"startup.get", "startup.act",// The relay allowance this month (WebUIBridge+Pages.swift)."relay.usage",+ // Processor, memory and disk (WebUIBridge+Pages.swift).+ "resources.get",// The getting-started checklist: the app's one copy (`ChecklistModel`)."checklist.get", "checklist.send",]diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex bb9289872a..cc743855fb 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -200,7 +200,7 @@ struct BridgeContractTests {func cases(space: String) -> [(String, [String: Any])] {[// The relay allowance before the sign-out below (signed out, it is null).- ("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("session.signOut", [:]),+ ("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("resources.get", ["visible": true]), ("session.signOut", [:]),("checklist.get", [:]), ("checklist.send", ["action": ["type": "done", "step": "teleport"]]),("spaces.list", [:]),("spaces.createOptions", [:]), ("spaces.cancelCreate", ["pendingId": "pending:none"]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swiftnew file mode 100644index 0000000000..dda05b2a02--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swift@@ -0,0 +1,63 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation+import Testing+@testable import CuaSpacesMacKit++@Suite("Host resources and the low-disk warning")+struct HostResourcesTests {+ let gb: Int64 = 1_000_000_000++ @Test("warns under 50 GB or 15% free, capped at 100 GB; critical under 5 GiB")+ func thresholds() {+ // 1 TB: 15% is 150 GB, capped at 100 GB.+ #expect(DiskWarning(free: 120 * gb, total: 1000 * gb) == .none)+ #expect(DiskWarning(free: 90 * gb, total: 1000 * gb) == .low)+ // 256 GB: 15% is 38 GB, so the 50 GB line comes first.+ #expect(DiskWarning(free: 45 * gb, total: 256 * gb) == .low)+ #expect(DiskWarning(free: 60 * gb, total: 256 * gb) == .none)+ // 500 GB: 15% is 75 GB.+ #expect(DiskWarning(free: 70 * gb, total: 500 * gb) == .low)+ #expect(DiskWarning(free: 4 * gb, total: 1000 * gb) == .critical)+ }++ @Test("the menu bar says nothing when there's room")+ func menuText() {+ #expect(DiskWarning.none.menuText == nil)+ #expect(DiskWarning.low.menuText == "This Mac is almost out of space. Delete old Spaces or snapshots.")+ #expect(DiskWarning.critical.menuText?.hasPrefix("This Mac is out of space") == true)+ }++ @Test @MainActor+ func monitorReadsTheDisk() {+ var free: Int64 = 300 * gb+ let monitor = LowDiskMonitor(read: { (1000 * gb, free) })+ monitor.refresh()+ #expect(monitor.warning == .none)+ free = 41 * gb+ monitor.refresh()+ #expect(monitor.warning == .low)+ // A volume it can't read: no warning.+ let unreadable = LowDiskMonitor(read: { (0, 0) })+ unreadable.refresh()+ #expect(unreadable.warning == .none)+ }++ @Test("a sample reads real numbers, and the second says how busy")+ func sample() {+ let sampler = HostResourceSampler()+ let first = sampler.sample()+ #expect(first.cores > 0)+ #expect(first.memoryTotal > 0)+ #expect(first.diskTotal > 0 && first.diskFree >= 0)+ #expect(first.busyPercent == nil)+ let second = sampler.sample()+ if let busy = second.busyPercent { #expect(busy >= 0 && busy <= 100) }+ let snap = second.snapshot()+ let thisMac = snap["thisMac"] as? [String: Any]+ #expect(thisMac?["id"] as? String == "this-mac")+ #expect((snap["spaces"] as? [Any])?.isEmpty == true)+ #expect(["ok", "low", "critical"].contains((snap["warning"] as? [String: Any])?["level"] as? String ?? ""))+ }+}diff --git a/apps/cua-spaces-web/src/__tests__/resources.test.tsx b/apps/cua-spaces-web/src/__tests__/resources.test.tsxnew file mode 100644index 0000000000..ada334614f--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/resources.test.tsx@@ -0,0 +1,159 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Processor, memory and disk on Home and a Space's page (CUA-1880): the+// numbers' store, the strips, the low-disk warning and its "See what's+// using space" (real routes, wasm core, the demo host).++import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { BridgeProvider, HostError, RESOURCES_HIDDEN_MS, RESOURCES_VISIBLE_MS, useResources, type DataAdapter, type ResourcesSnapshot } from "@/bridge";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { DEMO_DISK_FREE, demoDiskWarning } from "@/bridge/adapters/demo/resources";+import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { mountApp, stubBrowserApis } from "./app-harness";++afterEach(cleanup);+stubBrowserApis();++const lowDisk = (op: string, out: unknown) => {+ if (op !== "resources.get" || !out) return out;+ const snap = out as ResourcesSnapshot;+ const warning = demoDiskWarning(DEMO_DISK_FREE.low, snap.thisMac.diskTotal);+ return { ...snap, thisMac: { ...snap.thisMac, diskFree: DEMO_DISK_FREE.low, warning }, warning };+};++describe("the resources store", () => {+ function Probe({ seen }: { seen: { snap?: ResourcesSnapshot | null } }) {+ seen.snap = useResources();+ return null;+ }++ it("reads every 10 s while visible and every 5 minutes while hidden, saying which", async () => {+ vi.useFakeTimers();+ try {+ const demo = createDemoAdapter({ latencyMs: 0 });+ const calls: boolean[] = [];+ const adapter: DataAdapter = { ...demo, call: (op, args) => (op === "resources.get" && calls.push((args as { visible: boolean }).visible), demo.call(op, args)) };+ const seen: { snap?: ResourcesSnapshot | null } = {};+ render(+ <BridgeProvider adapter={adapter}>+ <Probe seen={seen} />+ </BridgeProvider>,+ );+ await act(() => vi.advanceTimersByTimeAsync(10));+ expect(calls).toEqual([true]);+ expect(seen.snap?.thisMac.id).toBe("this-mac");+ await act(() => vi.advanceTimersByTimeAsync(RESOURCES_VISIBLE_MS));+ expect(calls.length).toBe(2);+ // Hidden: the slow pace, and the read says so.+ Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });+ document.dispatchEvent(new Event("visibilitychange"));+ await act(() => vi.advanceTimersByTimeAsync(RESOURCES_VISIBLE_MS * 3));+ expect(calls.length).toBe(2);+ await act(() => vi.advanceTimersByTimeAsync(RESOURCES_HIDDEN_MS));+ expect(calls.at(-1)).toBe(false);+ // Back: at once.+ Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });+ const before = calls.length;+ document.dispatchEvent(new Event("visibilitychange"));+ await act(() => vi.advanceTimersByTimeAsync(5));+ expect(calls.length).toBe(before + 1);+ expect(calls.at(-1)).toBe(true);+ } finally {+ Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true });+ vi.useRealTimers();+ }+ });++ it("a host without the operation reads as null, and is not asked again", async () => {+ vi.useFakeTimers();+ try {+ const demo = createDemoAdapter({ latencyMs: 0 });+ let asked = 0;+ const adapter: DataAdapter = {+ ...demo,+ call: (op, args) => {+ if (op !== "resources.get") return demo.call(op, args);+ asked += 1;+ return Promise.reject(new HostError("resources.get", "unimplemented"));+ },+ };+ const seen: { snap?: ResourcesSnapshot | null } = {};+ render(+ <BridgeProvider adapter={adapter}>+ <Probe seen={seen} />+ </BridgeProvider>,+ );+ await act(() => vi.advanceTimersByTimeAsync(RESOURCES_VISIBLE_MS * 3));+ expect(seen.snap).toBeNull();+ expect(asked).toBe(1);+ } finally {+ vi.useRealTimers();+ }+ });+});++describe.skipIf(!wasmBuilt)("resources on Home and a Space's page", () => {+ it("Home: This Mac's strip, the Mac mini's summary, and each Space's meters; no warning with room", async () => {+ await mountApp("/spaces", { failsCreates: false, listsGhost: false });+ const mac = await waitFor(() => {+ const el = document.querySelector<HTMLElement>('[data-computer-resources="this-mac"]');+ if (!el) throw new Error("no This Mac strip");+ return el;+ });+ expect(mac.textContent).toContain("Processor");+ expect(mac.textContent).toContain("12 cores");+ expect(mac.textContent).toContain("Space for files");+ expect(mac.textContent).toContain("Your extra Spaces use 6 cores, 12 GB of memory and about 25 GB for files.");+ expect(document.querySelector('[data-computer-resources="mac-mini"]')?.textContent).toMatch(/Updated .* ago\. Your extra Spaces there use/);+ // The Linux box sent no summary.+ expect(document.querySelector('[data-computer-resources="linux-box"]')).toBeNull();+ expect(document.querySelector("[data-low-disk]")).toBeNull();+ const tile = document.querySelector('[data-space-id="local:agent-sandbox"]')!;+ await waitFor(() => expect(tile.querySelector("[data-space-meters]")?.textContent).toBe("StoppedOffAbout 6 GB"));+ // Other computers' Spaces have no per-Space numbers.+ expect(document.querySelector('[data-space-id="relay:mac-mini/qa-windows"] [data-space-meters]')).toBeNull();+ });++ it("low disk: the warning on This Mac, and See what's using space lists the Spaces biggest first", async () => {+ const { router } = await mountApp("/spaces", { failsCreates: false, listsGhost: false, answer: lowDisk });+ const warning = await waitFor(() => {+ const el = document.querySelector<HTMLElement>('[data-computer-resources="this-mac"] [data-low-disk="low"]');+ if (!el) throw new Error("no warning");+ return el;+ });+ expect(warning.textContent).toContain("This Mac is almost out of space. Delete old Spaces or snapshots.");+ fireEvent.click(warning.querySelector("[data-see-space-use]")!);+ await waitFor(() => expect(router.state.location.search).toEqual({ sort: "size" }));+ await waitFor(() => expect(document.querySelector("[data-sorted-by-size]")).not.toBeNull());+ const ids = Array.from(document.querySelectorAll("[data-space-id]")).map((t) => t.getAttribute("data-space-id"));+ expect(ids.slice(0, 2)).toEqual(["local:design-review", "local:agent-sandbox"]);+ });++ it("a Space's page: given vs in use, how it fits on this Mac, and the warning", async () => {+ await mountApp(`/spaces/${encodeURIComponent("local:design-review")}`, { failsCreates: false, listsGhost: false, answer: lowDisk });+ const panel = await waitFor(() => {+ const el = document.querySelector<HTMLElement>("[data-space-resources]");+ if (!el) throw new Error("no panel");+ return el;+ });+ const card = (label: string) => panel.querySelector(`[data-resource-card="${label}"]`)?.textContent ?? "";+ expect(card("Processor")).toContain("Given 4 of this Mac’s 12 cores");+ expect(card("Memory")).toContain("Given 8 GB of this Mac’s 64 GB");+ expect(card("Space for files")).toContain("34 of 80 GB");+ expect(card("Space for files")).toContain("Uses about 19 GB on this Mac (shares space with other copies).");+ const fit = panel.querySelector("[data-disk-fit]")!;+ expect(fit.textContent).toContain("How it fits on this Mac");+ expect(fit.querySelector('[data-disk-part="own"]')?.textContent).toBe("Your own files and apps · 934 GB");+ expect(fit.querySelector('[data-disk-part="free"]')?.textContent).toBe("Free · 41 GB");+ expect(fit.querySelector("[data-low-disk]")).not.toBeNull();+ });++ it("another computer's Space has no panel without its numbers", async () => {+ await mountApp(`/spaces/${encodeURIComponent("relay:mac-mini/qa-windows")}`, { failsCreates: false, listsGhost: false });+ await waitFor(() => expect(document.querySelector("[data-detail-title]")).not.toBeNull());+ await act(() => new Promise((r) => setTimeout(r, 50)));+ expect(document.querySelector("[data-space-resources]")).toBeNull();+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex e828be3030..85a8ccc1d7 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -95,6 +95,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"agents.setupDriver": { agents: ["codex"] },"spaces.openStream": { spaceId: SPACE, tier: "tile" },"relay.usage": {},+ "resources.get": { visible: true },"checklist.get": {},"checklist.send": { action: { type: "done", step: "teleport" } },"presence.join": { spaceId: SPACE },diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 429ea54135..d6bdae8d47 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -15,6 +15,7 @@ import { KEYVAULT_MANAGE_ARGS } from "../ops/keyvault-manage";import { KEYVAULT_SETUP_ARGS } from "../ops/keyvault-setup";import { STREAM_ARGS } from "../ops/stream";import { RELAY_USAGE_ARGS } from "../ops/relay-usage";+import { RESOURCES_ARGS } from "../ops/resources";import { CHECKLIST_ARGS } from "../ops/checklist";import { PRESENCE_ARGS } from "../ops/presence";import { RUNTIME_FIX_ARGS } from "../ops/runtime-fix";@@ -127,6 +128,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"startup.act": { action: "allowAccess" },...STREAM_ARGS,...RELAY_USAGE_ARGS,+ ...RESOURCES_ARGS,...CHECKLIST_ARGS,...PRESENCE_ARGS,...RUNTIME_FIX_ARGS,diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex b4302272ec..76411c0937 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -50,6 +50,7 @@ import { demoVolumeHandlers, demoVolumeState, type DemoVolumeState } from "./demimport { demoHostSetupHandlers, demoHostSetupState, type DemoHostSetupState } from "./demo/host-setup";import { demoSpaceDetailHandlers, demoSpaceDetailState, type DemoSpaceDetailState } from "./demo/space-detail";import { demoTelemetryHandlers, demoTelemetryState, type DemoTelemetryState } from "./demo/telemetry";+import { demoResourcesHandlers, demoResourcesState, type DemoResourcesState } from "./demo/resources";import { demoRelayUsageHandlers, demoRelayUsageNamed, demoRelayUsageState, type DemoRelayUsageState } from "./demo/relay-usage";import { demoStartupHandlers, demoStartupState, type DemoStartupState } from "./demo/startup";import { demoMachine, MAC_DEMO_PLATFORM, type DemoPlatform } from "./demo/platform";@@ -77,6 +78,8 @@ export interface DemoOptions {/** The relay allowance: `idle` (free, no live session, so prompts can show),* `warn` (80% of the hours), `limit` (used up), `pro` or `teams`. */usage?: "idle" | "warn" | "limit" | "pro" | "teams";+ /** This Mac's free disk: `low` (`?demo=low-disk`) or `full` (`?demo=disk-full`). */+ disk?: "low" | "full";/** The machine the demo runs on: a Mac on Apple silicon unless set (the* Electron shell passes its own system and architecture). */platform?: DemoPlatform;@@ -90,7 +93,8 @@ const DEMO_NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3* `?demo=empty` (no Spaces yet), `?demo=keychain` (the startup screen),* `?demo=mac-host` (New Space options and the Keyvault's Settings rows in the* SwiftUI host's shape), `?demo=unenrolled` (this device not enrolled),- * `?demo=update-ready` (an update is downloaded) and `?demo=update-downloading`. */+ * `?demo=update-ready` (an update is downloaded), `?demo=update-downloading`,+ * and `?demo=low-disk` / `?demo=disk-full` (This Mac almost out of space). */export function demoOptionsFromSearch(search: string): DemoOptions {const flags = new Set((new URLSearchParams(search).get("demo") ?? "").split(",").filter(Boolean));return {@@ -105,6 +109,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {macHost: flags.has("mac-host"),unenrolled: flags.has("unenrolled"),usage: (["idle", "warn", "limit", "pro", "teams"] as const).find((u) => flags.has(`usage-${u}`)),+ disk: flags.has("disk-full") ? "full" : flags.has("low-disk") ? "low" : undefined,...(flags.has("update-ready")? { update: { status: "downloaded" as const, version: "0.9.3", percent: 100, notesUrl: DEMO_NOTES } }: flags.has("update-downloading")@@ -163,6 +168,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { revolume: demoVolumeState(now(), options.onboarded !== false, options.platform),...demoTelemetryState(),...demoRelayUsageState(),+ ...demoResourcesState(options.disk ?? "healthy"),...(options.usage ? { relayUsage: demoRelayUsageNamed(options.usage) } : {}),...demoSpaceDetailState(),...demoHostSetupState(now(), options.onboarded === false),@@ -498,6 +504,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, unenrolled: options.unenrolled, update: options.update, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),...demoTelemetryHandlers(ctx),...demoRelayUsageHandlers(ctx),+ ...demoResourcesHandlers(ctx),...demoSpaceDetailHandlers(ctx),...demoHostSetupHandlers(ctx),...demoKeyvaultSetupHandlers(ctx),@@ -527,7 +534,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re};}-export interface DemoState extends DemoTelemetryState, DemoRelayUsageState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {+export interface DemoState extends DemoTelemetryState, DemoRelayUsageState, DemoResourcesState, DemoSpaceDetailState, DemoHostSetupState, DemoStartupState, DemoNewSpaceState, DemoKeyvaultSetupState, DemoKeyvaultManageState {rows: SpaceRow[];items: KvItem[];keyvaultLocked: boolean;diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/resources.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/resources.tsnew file mode 100644index 0000000000..c805aa419d--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/resources.ts@@ -0,0 +1,134 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The demo host's resource numbers (`resources.get`): This Mac and each of+ * its Spaces, and a summary from the Mac mini (the Linux box sends none).+ * Busy and in-use numbers drift a little with the clock, so the bars move+ * as live ones do. `diskFree` in its state sets This Mac's free disk+ * (`?demo=low-disk`, `?demo=disk-full`).+ */++import type { SpaceRow } from "../../contracts/spaces";+import type { ComputerResources, DiskWarning, ResourcesSnapshot, SpaceResources } from "../../ops/resources";+import type { DemoContext, DemoHandlers } from "./context";++const GB = 1_000_000_000;+const GIB = 1024 ** 3;++export interface DemoResourcesState {+ /** This Mac's free disk, in bytes. */+ diskFree: number;+}++export const DEMO_DISK_FREE = { healthy: 310 * GB, low: 41 * GB, full: 3.2 * GB } as const;++export const demoResourcesState = (disk: keyof typeof DEMO_DISK_FREE = "healthy"): DemoResourcesState => ({ diskFree: DEMO_DISK_FREE[disk] });++/** The daemon's warning rule (without its 2 GiB hysteresis): `low` under+ * 50 GB or 15%, whichever line is higher, capped at 100 GB; `critical`+ * under 5 GiB. */+export function demoDiskWarning(free: number, total: number): DiskWarning {+ if (free < 5 * GIB) return { level: "critical", free, total, threshold: 5 * GIB };+ const line = Math.min(Math.max(50 * GB, total * 0.15), 100 * GB);+ return free < line ? { level: "low", free, total, threshold: line } : { level: "ok", free, total, threshold: 0 };+}++/** A small, smooth wobble around `base` (±`by`), from the clock. */+const drift = (now: number, base: number, by: number, phase = 0) => Math.max(0, base + Math.sin(now / 9000 + phase) * by);++const running = (row: SpaceRow) => row.powerState === "running" || (row.powerState === undefined && row.reachable);++/** What each demo Space was given (cores, GB of memory, GB of disk at most) and takes on its host. */+const ALLOCATION: Record<string, { cores: number; memory: number; disk: number; onHost: number; inside: number; shared: boolean }> = {+ "local:design-review": { cores: 4, memory: 8, disk: 80, onHost: 19, inside: 34, shared: true },+ "local:agent-sandbox": { cores: 2, memory: 4, disk: 40, onHost: 6, inside: 6, shared: false },+};++function spaceResources(row: SpaceRow, now: number, index: number): SpaceResources {+ const a = ALLOCATION[row.id] ?? (row.os === "linux" ? { cores: 2, memory: 4, disk: 40, onHost: 6, inside: 5, shared: false } : { cores: 4, memory: 8, disk: 80, onHost: 22, inside: 30, shared: true });+ const on = running(row);+ const cpu = Math.round(drift(now, 18 + index * 4, 7, index) * 10) / 10;+ return {+ id: row.id,+ powerState: on ? "running" : "stopped",+ cpuAllocated: a.cores,+ memoryAllocated: a.memory * GB,+ diskAllocated: a.disk * GB,+ usage: on+ ? {+ cpuCount: a.cores,+ cpuPercent: cpu,+ loadAverage1m: (cpu / 100) * a.cores,+ memoryUsed: Math.round(drift(now, a.memory * 0.38, 0.2, index) * GB),+ memoryTotal: a.memory * GB,+ memoryLimited: true,+ diskUsed: a.inside * GB,+ diskTotal: a.disk * GB,+ diskLimited: true,+ }+ : null,+ diskOnHost: { bytes: a.onHost * GB, allocated: (a.shared ? a.inside : a.onHost) * GB, sharesSpace: a.shared },+ };+}++function computer(c: Omit<ComputerResources, "warning">): ComputerResources {+ return { ...c, warning: demoDiskWarning(c.diskFree, c.diskTotal) };+}++export function demoResources(rows: readonly SpaceRow[], now: number, diskFree: number = DEMO_DISK_FREE.healthy): ResourcesSnapshot {+ // Only this Mac's own Spaces: other computers send a summary, not each Space.+ const spaces = rows.filter((r) => r.provider === "local").map((r, i) => spaceResources(r, now, i));+ const on = spaces.filter((s) => s.powerState === "running");+ const sum = (list: SpaceResources[], f: (s: SpaceResources) => number | null | undefined) => list.reduce((n, s) => n + (f(s) ?? 0), 0);+ const cpuPercent = Math.round(drift(now, 34, 6) * 10) / 10;+ const thisMac = computer({+ id: "this-mac",+ name: "",+ online: true,+ sampledAtMs: now,+ cpuCount: 12,+ cpuPercent,+ loadAverage1m: (cpuPercent / 100) * 12,+ memoryTotal: 64 * GB,+ memoryUsed: Math.round(drift(now, 41, 1.5) * GB),+ diskTotal: 1000 * GB,+ diskFree,+ spacesCount: spaces.length,+ spacesRunning: on.length,+ // The demo counts stopped Spaces' allocation too, as frame 14 shows it.+ spacesCpuAllocated: sum(spaces, (s) => s.cpuAllocated),+ spacesMemoryAllocated: sum(spaces, (s) => s.memoryAllocated),+ spacesMemoryUsed: sum(on, (s) => s.usage?.memoryUsed),+ spacesDiskBytes: sum(spaces, (s) => s.diskOnHost?.bytes),+ spacesDiskExact: false,+ });+ // The Mac mini's summary through the relay, a couple of minutes old.+ const macMini = computer({+ id: "mac-mini",+ name: "Mac mini",+ online: true,+ sampledAtMs: now - 2 * 60_000,+ cpuCount: 8,+ cpuPercent: 12,+ loadAverage1m: 1,+ memoryTotal: 16 * GB,+ memoryUsed: 7 * GB,+ diskTotal: 512 * GB,+ diskFree: 212 * GB,+ spacesCount: 2,+ spacesRunning: 1,+ spacesCpuAllocated: 6,+ spacesMemoryAllocated: 12 * GB,+ spacesMemoryUsed: 5 * GB,+ spacesDiskBytes: 46 * GB,+ spacesDiskExact: false,+ });+ return { sequence: Math.floor(now / 10_000), sampledAtMs: now, thisMac, spaces, computers: [macMini], warning: thisMac.warning };+}++export function demoResourcesHandlers({ state, now }: DemoContext): DemoHandlers<"resources.get"> {+ return {+ "resources.get": () => demoResources(state.rows, now(), state.diskFree),+ };+}diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 050e9e608e..7a6f634b41 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -57,6 +57,7 @@ import { tauriHostSetupOps } from "../ops/host-setup";import { TAURI_SPACE_DETAIL_UNSUPPORTED, tauriSpaceDetailOps } from "../ops/space-detail";import { STREAM_OPERATIONS } from "../ops/stream";import { RELAY_USAGE_OPERATIONS } from "../ops/relay-usage";+import { RESOURCES_OPERATIONS } from "../ops/resources";import { CHECKLIST_OPERATIONS } from "../ops/checklist";import { PRESENCE_OPERATIONS } from "../ops/presence";import { RUNTIME_FIX_OPERATIONS } from "../ops/runtime-fix";@@ -92,6 +93,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [...TAURI_SPACE_DETAIL_UNSUPPORTED,...STREAM_OPERATIONS,...RELAY_USAGE_OPERATIONS,+ ...RESOURCES_OPERATIONS,...CHECKLIST_OPERATIONS,...PRESENCE_OPERATIONS,...RUNTIME_FIX_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex ee46e97223..1fea21e8a2 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -58,6 +58,7 @@ import { webkitSettingsOps } from "../ops/settings";import { startupFromHost, webkitStartupOps } from "../ops/startup";import { unsupportedStreamOps, type StreamTicket } from "../ops/stream";import type { RelayUsage } from "../ops/relay-usage";+import type { ResourcesSnapshot } from "../ops/resources";import type { HostChecklistState } from "../ops/checklist";import { unsupportedPresenceOps, type PresenceJoinInfo } from "../ops/presence";import { unsupportedRuntimeFixOps } from "../ops/runtime-fix";@@ -643,6 +644,7 @@ export function createWebkitAdapter(? { "spaces.openStream": (target: OpArgs<"spaces.openStream">) => request<StreamTicket>("spaces.openStream", { ...target }) }: unsupportedStreamOps("webkit")),"relay.usage": () => request<RelayUsage | null>("relay.usage"),+ "resources.get": ({ visible }) => request<ResourcesSnapshot | null>("resources.get", { visible }),"checklist.get": () => request<{ state: HostChecklistState }>("checklist.get"),"checklist.send": ({ action }) => request<{ state: HostChecklistState }>("checklist.send", { action }),// Presence over the page's own video: the Mac app draws it natively.diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex 17b0c84c5b..f171322708 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -562,6 +562,89 @@"connected"]},+ "ComputerResources": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "online": {+ "type": "boolean"+ },+ "sampledAtMs": {+ "type": "number"+ },+ "cpuCount": {+ "type": "number"+ },+ "cpuPercent": {+ "type": "number"+ },+ "loadAverage1m": {+ "type": "number"+ },+ "memoryTotal": {+ "type": "number"+ },+ "memoryUsed": {+ "type": "number"+ },+ "diskTotal": {+ "type": "number"+ },+ "diskFree": {+ "type": "number"+ },+ "spacesCount": {+ "type": "number"+ },+ "spacesRunning": {+ "type": "number"+ },+ "spacesCpuAllocated": {+ "type": "number"+ },+ "spacesMemoryAllocated": {+ "type": "number"+ },+ "spacesMemoryUsed": {+ "type": "number"+ },+ "spacesDiskBytes": {+ "type": "number"+ },+ "spacesDiskExact": {+ "type": "boolean"+ },+ "warning": {+ "$ref": "#/$defs/DiskWarning"+ }+ },+ "required": [+ "id",+ "name",+ "online",+ "sampledAtMs",+ "cpuCount",+ "cpuPercent",+ "loadAverage1m",+ "memoryTotal",+ "memoryUsed",+ "diskTotal",+ "diskFree",+ "spacesCount",+ "spacesRunning",+ "spacesCpuAllocated",+ "spacesMemoryAllocated",+ "spacesMemoryUsed",+ "spacesDiskBytes",+ "spacesDiskExact",+ "warning"+ ]+ },"DevicesInput": {"type": "object","properties": {@@ -682,6 +765,33 @@}}},+ "DiskWarning": {+ "type": "object",+ "properties": {+ "level": {+ "enum": [+ "ok",+ "low",+ "critical"+ ]+ },+ "free": {+ "type": "number"+ },+ "total": {+ "type": "number"+ },+ "threshold": {+ "type": "number"+ }+ },+ "required": [+ "level",+ "free",+ "total",+ "threshold"+ ]+ },"DriveCheckInput": {"type": "object","properties": {@@ -2400,6 +2510,111 @@"label"]},+ "SpaceResources": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "powerState": {+ "enum": [+ "running",+ "stopped",+ "suspended",+ ""+ ]+ },+ "cpuAllocated": {+ "type": "number"+ },+ "memoryAllocated": {+ "type": "number"+ },+ "diskAllocated": {+ "type": "number"+ },+ "usage": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "cpuCount": {+ "type": "number"+ },+ "cpuPercent": {+ "type": "number"+ },+ "loadAverage1m": {+ "type": "number"+ },+ "memoryUsed": {+ "type": "number"+ },+ "memoryTotal": {+ "type": "number"+ },+ "memoryLimited": {+ "type": "boolean"+ },+ "diskUsed": {+ "type": "number"+ },+ "diskTotal": {+ "type": "number"+ },+ "diskLimited": {+ "type": "boolean"+ }+ },+ "required": [+ "cpuCount",+ "cpuPercent",+ "loadAverage1m",+ "memoryUsed",+ "memoryTotal",+ "memoryLimited",+ "diskUsed",+ "diskTotal",+ "diskLimited"+ ]+ },+ "diskOnHost": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "bytes": {+ "type": [+ "number",+ "null"+ ]+ },+ "allocated": {+ "type": "number"+ },+ "sharesSpace": {+ "type": "boolean"+ }+ },+ "required": [+ "bytes",+ "allocated",+ "sharesSpace"+ ]+ }+ },+ "required": [+ "id",+ "powerState",+ "cpuAllocated",+ "memoryAllocated",+ "diskAllocated",+ "usage",+ "diskOnHost"+ ]+ },"SpaceRow": {"type": "object","properties": {@@ -4766,6 +4981,46 @@"upgradeUrl"]},+ "resources.get": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "sequence": {+ "type": "number"+ },+ "sampledAtMs": {+ "type": "number"+ },+ "thisMac": {+ "$ref": "#/$defs/ComputerResources"+ },+ "spaces": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/SpaceResources"+ }+ },+ "computers": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/ComputerResources"+ }+ },+ "warning": {+ "$ref": "#/$defs/DiskWarning"+ }+ },+ "required": [+ "sequence",+ "sampledAtMs",+ "thisMac",+ "spaces",+ "computers",+ "warning"+ ]+ },"session.completeOnboarding": {"type": "null"},@@ -6260,6 +6515,46 @@"upgradeUrl"]},+ "resources.get": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "sequence": {+ "type": "number"+ },+ "sampledAtMs": {+ "type": "number"+ },+ "thisMac": {+ "$ref": "#/$defs/ComputerResources"+ },+ "spaces": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/SpaceResources"+ }+ },+ "computers": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/ComputerResources"+ }+ },+ "warning": {+ "$ref": "#/$defs/DiskWarning"+ }+ },+ "required": [+ "sequence",+ "sampledAtMs",+ "thisMac",+ "spaces",+ "computers",+ "warning"+ ]+ },"session.get": {"$ref": "#/$defs/WkSession"},diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 7b14281b4b..7676d44848 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -60,6 +60,7 @@ import type { AgentSetupOutcome, DriveGrantInput, DriveMountInput, DriveRequestIimport type { AgentKeysReport } from "../ops/agent-keys";import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";import type { RelayUsage } from "../ops/relay-usage";+import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SpaceResources } from "../ops/resources";import type { HostChecklistState } from "../ops/checklist";import type { PresenceCursorWire, PresenceJoinInfo, PresenceParticipantWire } from "../ops/presence";import type { StartupState } from "../ops/startup";@@ -76,6 +77,34 @@ const os = oneOf("macos", "windows", "linux", "unknown");/* ---- Spaces and machines --------------------------------------------------- */+const DiskWarningShape = ref("DiskWarning", obj<DiskWarning>()({ level: oneOf("ok", "low", "critical"), free: num, total: num, threshold: num }));++/** `resources.get`'s computers (CUA-1880). */+const ComputerResourcesShape = ref(+ "ComputerResources",+ obj<ComputerResources>()({+ id: str,+ name: str,+ online: bool,+ sampledAtMs: num,+ cpuCount: num,+ cpuPercent: num,+ loadAverage1m: num,+ memoryTotal: num,+ memoryUsed: num,+ diskTotal: num,+ diskFree: num,+ spacesCount: num,+ spacesRunning: num,+ spacesCpuAllocated: num,+ spacesMemoryAllocated: num,+ spacesMemoryUsed: num,+ spacesDiskBytes: num,+ spacesDiskExact: bool,+ warning: DiskWarningShape,+ }),+);+const SpaceProgressShape = ref("SpaceProgress",obj<SpaceProgress>()({ phase: str, permille: num, label: str, error: opt(str), transfer: opt(str), cancellable: opt(bool), cancelling: opt(bool) }),@@ -839,6 +868,41 @@ export const OP_SHAPES: Record<OpName, Schema> = {upgradeUrl: nullable(str),}),),+ "resources.get": nullable(+ obj<ResourcesSnapshot>()({+ sequence: num,+ sampledAtMs: num,+ thisMac: ComputerResourcesShape,+ spaces: list(+ ref(+ "SpaceResources",+ obj<SpaceResources>()({+ id: str,+ powerState: oneOf("running", "stopped", "suspended", ""),+ cpuAllocated: num,+ memoryAllocated: num,+ diskAllocated: num,+ usage: nullable(+ obj<GuestUsage>()({+ cpuCount: num,+ cpuPercent: num,+ loadAverage1m: num,+ memoryUsed: num,+ memoryTotal: num,+ memoryLimited: bool,+ diskUsed: num,+ diskTotal: num,+ diskLimited: bool,+ }),+ ),+ diskOnHost: nullable(obj<DiskOnHost>()({ bytes: nullable(num), allocated: num, sharesSpace: bool })),+ }),+ ),+ ),+ computers: list(ComputerResourcesShape),+ warning: DiskWarningShape,+ }),+ ),"checklist.get": ChecklistAnswerShape,"checklist.send": ChecklistAnswerShape,"presence.join": obj<PresenceJoinInfo>()({@@ -1224,6 +1288,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"startup.get": StartupShape,"startup.act": StartupShape,"relay.usage": OP_SHAPES["relay.usage"],+ "resources.get": OP_SHAPES["resources.get"],"checklist.get": OP_SHAPES["checklist.get"],"checklist.send": OP_SHAPES["checklist.send"],};diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 792d24fd11..14fd4705b5 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -40,6 +40,7 @@ import { HOST_SETUP_COVERAGE } from "./ops/host-setup";import { SPACE_DETAIL_COVERAGE } from "./ops/space-detail";import { STREAM_COVERAGE } from "./ops/stream";import { RELAY_USAGE_COVERAGE } from "./ops/relay-usage";+import { RESOURCES_COVERAGE } from "./ops/resources";import { CHECKLIST_COVERAGE } from "./ops/checklist";import { PRESENCE_COVERAGE } from "./ops/presence";import { RUNTIME_FIX_COVERAGE } from "./ops/runtime-fix";@@ -164,6 +165,7 @@ export const HOST_COVERAGE = {...STARTUP_COVERAGE,...STREAM_COVERAGE,...RELAY_USAGE_COVERAGE,+ ...RESOURCES_COVERAGE,...CHECKLIST_COVERAGE,...PRESENCE_COVERAGE,...RUNTIME_FIX_COVERAGE,diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex cecbdf8452..e7b9e702fb 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -141,6 +141,19 @@ export {type RelayUsage,type RelayUsageView,} from "./relay-usage";+export {+ useResources,+ hostResources,+ spaceResources,+ RESOURCES_HIDDEN_MS,+ RESOURCES_VISIBLE_MS,+ type ComputerResources,+ type DiskOnHost,+ type DiskWarning,+ type GuestUsage,+ type ResourcesSnapshot,+ type SpaceResources,+} from "./resources";export {resetUpsellMemory,useQuiet,diff --git a/apps/cua-spaces-web/src/bridge/ops/resources.ts b/apps/cua-spaces-web/src/bridge/ops/resources.tsnew file mode 100644index 0000000000..6df33bdbce--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/resources.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Processor, memory and disk for each computer and each extra Space+ * (CUA-1880, `2026-10-18-space-resources-spec.md`, "API (as built)"): the+ * SDK's `Spaces.resources(visible)` snapshot, as the host answers it.+ *+ * The local daemon samples this Mac and every local Space. `visible: true`+ * counts as "a window is open" for 30 s, so the daemon samples every 10 s+ * then and every 5 minutes otherwise. Other computers publish a summary+ * through the relay machine record; `sampledAtMs` says how old it is.+ *+ * | Operation | Electron | SwiftUI | Tauri |+ * |---|---|---|---|+ * | `resources.get {visible}` | the host method `resources.get` | the host method `resources.get` | unsupported |+ *+ * Null, or a host that doesn't answer it yet: the app shows no numbers.+ * Numbers only: never file names, paths, process names or window titles.+ */++import type { OpCoverage } from "../coverage";++/**+ * The disk warning (`cua_spaces::resources::DiskWarning`). `low`: free is+ * under 50 GB or 15% of the volume, whichever line is higher, capped at+ * 100 GB. `critical`: under 5 GiB, where creates already fail. It clears+ * 2 GiB above the line, so it doesn't flicker.+ */+export interface DiskWarning {+ level: "ok" | "low" | "critical";+ free: number;+ total: number;+ /** The line that was crossed (0 when ok). */+ threshold: number;+}++/** One computer (`ComputerResources`): this Mac, or another computer's relay summary. */+export interface ComputerResources {+ /** `this-mac`, or the relay machine id (`machines.list`). */+ id: string;+ /** Empty for this Mac. */+ name: string;+ online: boolean;+ /** When the computer measured it, unix ms (another computer's: up to 5 minutes old). */+ sampledAtMs: number;+ cpuCount: number;+ /** Busy now, 0 to 100. */+ cpuPercent: number;+ loadAverage1m: number;+ memoryTotal: number;+ /** Without reclaimable cache. */+ memoryUsed: number;+ /** The volume that holds Spaces. */+ diskTotal: number;+ diskFree: number;+ spacesCount: number;+ spacesRunning: number;+ /** Cores given to running Spaces. */+ spacesCpuAllocated: number;+ /** Bytes given to running Spaces. */+ spacesMemoryAllocated: number;+ spacesMemoryUsed: number;+ /** What all extra Spaces take on this computer's disk. */+ spacesDiskBytes: number;+ /** False: some Spaces could only be estimated. */+ spacesDiskExact: boolean;+ warning: DiskWarning;+}++/** What the guest reports (`SystemService.Metrics`, with CPU). */+export interface GuestUsage {+ cpuCount: number;+ cpuPercent: number;+ loadAverage1m: number;+ memoryUsed: number;+ memoryTotal: number;+ memoryLimited: boolean;+ diskUsed: number;+ diskTotal: number;+ diskLimited: boolean;+}++/** What a Space costs this Mac's disk. */+export interface DiskOnHost {+ /** Bytes only this Space holds (what deleting it frees); null: couldn't measure. */+ bytes: number | null;+ /** Blocks its files occupy, clones counted in full (an upper bound). */+ allocated: number;+ /** Part of it is shared with other copies. */+ sharesSpace: boolean;+}++/** One extra Space on this Mac (`SpaceResources`). */+export interface SpaceResources {+ /** `local:aurora`. */+ id: string;+ powerState: "running" | "stopped" | "suspended" | "";+ /** Cores; 0: unknown. */+ cpuAllocated: number;+ /** Bytes; 0: unknown. */+ memoryAllocated: number;+ /** The disk's size limit ("up to 80 GB"); 0: unknown. */+ diskAllocated: number;+ /** Null while stopped or unreachable. */+ usage: GuestUsage | null;+ /** Null: nothing to say (a container). */+ diskOnHost: DiskOnHost | null;+}++/** `cua_spaces::resources::ResourcesSnapshot` (the SDK's `Spaces.resources(visible)`). */+export interface ResourcesSnapshot {+ /** Grows by 1 per sample. */+ sequence: number;+ sampledAtMs: number;+ thisMac: ComputerResources;+ /** Extra Spaces on this Mac (local Spaces only). */+ spaces: SpaceResources[];+ /** Your other computers, from their relay summary. */+ computers: ComputerResources[];+ /** Same as `thisMac.warning`, for the menu bar. */+ warning: DiskWarning;+}++export interface ResourcesOps {+ "resources.get": { args: { visible: boolean }; result: ResourcesSnapshot | null };+}++export const RESOURCES_OPERATIONS = ["resources.get"] as const satisfies readonly (keyof ResourcesOps)[];++export const RESOURCES_COVERAGE = {+ "resources.get": {+ webkit: { methods: ["resources.get"] },+ tauri: [],+ unsupported: {+ tauri: "the Tauri app does not read resource numbers",+ },+ },+} as const satisfies Record<keyof ResourcesOps, OpCoverage>;++/** Arguments that take it down its usual path (coverage tests). */+export const RESOURCES_ARGS = { "resources.get": { visible: true } };diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex efd5e52497..f3fb0c84de 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -45,6 +45,7 @@ import type { HostSetupOps } from "./ops/host-setup";import type { SpaceDetailOps } from "./ops/space-detail";import { STREAM_OPERATIONS, type StreamOps } from "./ops/stream";import { RELAY_USAGE_OPERATIONS, type RelayUsageOps } from "./ops/relay-usage";+import { RESOURCES_OPERATIONS, type ResourcesOps } from "./ops/resources";import { CHECKLIST_OPERATIONS, type ChecklistOps } from "./ops/checklist";import { PRESENCE_OPERATIONS, type PresenceOps } from "./ops/presence";import { RUNTIME_FIX_OPERATIONS, type RuntimeFixOps } from "./ops/runtime-fix";@@ -186,6 +187,7 @@ export interface HostOperationsStartupOps,StreamOps,RelayUsageOps,+ ResourcesOps,ChecklistOps,PresenceOps,RuntimeFixOps {@@ -290,6 +292,7 @@ export const OPERATIONS = [...VOLUME_OPERATIONS,...STREAM_OPERATIONS,...RELAY_USAGE_OPERATIONS,+ ...RESOURCES_OPERATIONS,...CHECKLIST_OPERATIONS,...PRESENCE_OPERATIONS,...RUNTIME_FIX_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/resources.ts b/apps/cua-spaces-web/src/bridge/resources.tsnew file mode 100644index 0000000000..724cb763c5--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/resources.ts@@ -0,0 +1,129 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Processor, memory and disk numbers (`resources.get`), read while a screen+ * shows them: every 10 s while the window is visible, every 5 minutes while+ * it is hidden, at once when it comes back, and when the Spaces change. The+ * read says whether the window is visible, so the daemon samples at the+ * same pace. A host that doesn't answer the operation reads as null, and+ * the app shows no numbers.+ */++import { useContext, useSyncExternalStore } from "react";+import { HostError, isUnsupported, type DataAdapter } from "./adapter";+import { BridgeContext } from "./BridgeProvider";+import type { ComputerResources, ResourcesSnapshot, SpaceResources } from "./ops/resources";++export type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SpaceResources } from "./ops/resources";++export const RESOURCES_VISIBLE_MS = 10_000;+export const RESOURCES_HIDDEN_MS = 5 * 60_000;++const hidden = () => typeof document !== "undefined" && document.visibilityState === "hidden";++/** A host built before the operation: it never will answer. */+const notThere = (e: unknown) => isUnsupported(e) || (e instanceof HostError && e.code === "unimplemented");++class ResourcesStore {+ private snap: ResourcesSnapshot | null = null;+ private unsupported = false;+ private reading = false;+ private listeners = new Set<() => void>();+ private stop: (() => void) | null = null;++ constructor(private readonly adapter: DataAdapter) {}++ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ if (this.listeners.size === 1) this.start();+ return () => {+ this.listeners.delete(listener);+ if (this.listeners.size === 0) {+ this.stop?.();+ this.stop = null;+ }+ };+ };++ snapshot = (): ResourcesSnapshot | null => this.snap;++ async read(): Promise<void> {+ if (this.unsupported || this.reading) return;+ this.reading = true;+ try {+ this.set(await this.adapter.call("resources.get", { visible: !hidden() }));+ } catch (e) {+ // Not there: never again. Anything else keeps the last numbers.+ if (notThere(e)) {+ this.unsupported = true;+ this.set(null);+ }+ } finally {+ this.reading = false;+ }+ }++ private set(snap: ResourcesSnapshot | null) {+ this.snap = snap;+ for (const l of [...this.listeners]) l();+ }++ private start() {+ let timer: ReturnType<typeof setTimeout> | null = null;+ const schedule = () => {+ if (timer) clearTimeout(timer);+ timer = setTimeout(tick, hidden() ? RESOURCES_HIDDEN_MS : RESOURCES_VISIBLE_MS);+ };+ const tick = () => {+ void this.read();+ schedule();+ };+ tick();+ const onVisibility = () => {+ // Back in front: fresh numbers now, then the faster pace.+ if (!hidden()) tick();+ else schedule();+ };+ const doc = typeof document !== "undefined" ? document : null;+ doc?.addEventListener("visibilitychange", onVisibility);+ const unsubscribe = this.adapter.subscribe((e) => {+ if (e.type === "spaces.changed") void this.read();+ });+ this.stop = () => {+ if (timer) clearTimeout(timer);+ doc?.removeEventListener("visibilitychange", onVisibility);+ unsubscribe();+ };+ }+}++const stores = new WeakMap<DataAdapter, ResourcesStore>();++function storeFor(adapter: DataAdapter): ResourcesStore {+ let s = stores.get(adapter);+ if (!s) stores.set(adapter, (s = new ResourcesStore(adapter)));+ return s;+}++const none = () => () => {};+const nothing = () => null;++/** The latest numbers, or null (nothing to show). */+export function useResources(): ResourcesSnapshot | null {+ const adapter = useContext(BridgeContext)?.adapter ?? null;+ const store = adapter ? storeFor(adapter) : null;+ return useSyncExternalStore(store?.subscribe ?? none, store?.snapshot ?? nothing, nothing);+}++/** One computer's numbers, when it sent any: this Mac's, or another+ * computer's relay summary by its `machines.list` id. */+export function hostResources(snap: ResourcesSnapshot | null, machine: { id: string; current?: boolean } | undefined): ComputerResources | null {+ if (!machine || !snap) return null;+ return machine.current ? snap.thisMac : (snap.computers.find((c) => c.id === machine.id) ?? null);+}++/** One of this Mac's Spaces' numbers. */+export function spaceResources(snap: ResourcesSnapshot | null, spaceId: string): SpaceResources | null {+ return snap?.spaces.find((s) => s.id === spaceId) ?? null;+}diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 2fc9a663fd..58a4769a6c 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -154,6 +154,7 @@ export const WEBKIT_METHODS = ["startup.get","startup.act","relay.usage",+ "resources.get","checklist.get","checklist.send",] as const;diff --git a/apps/cua-spaces-web/src/components/resources/computer-resources.tsx b/apps/cua-spaces-web/src/components/resources/computer-resources.tsxnew file mode 100644index 0000000000..831a1442ef--- /dev/null+++ b/apps/cua-spaces-web/src/components/resources/computer-resources.tsx@@ -0,0 +1,45 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { hostResources, type Machine, type ResourcesSnapshot } from "@/bridge";+import { thisComputerLabel, thisComputerText } from "@/lib/host-labels";+import { extraSpacesLine, hostMeters, lowDiskWarning, updatedAgo } from "@/lib/resources";++import { LowDiskWarning, MeterRow } from "./meters";++/**+ * Home's strip for each computer that sent numbers: This Mac first (with+ * the low-disk warning on top when it's short of space), then your other+ * computers' summaries with how old they are. Nothing when no computer+ * sent any.+ */+export function ComputersResources({ snapshot, machines, now = Date.now() }: { snapshot: ResourcesSnapshot | null; machines: readonly Machine[]; now?: number }) {+ const shown = machines.map((m) => ({ machine: m, host: hostResources(snapshot, m) })).filter((x) => x.host);+ if (!shown.length) return null;+ return (+ <section data-computers-resources="" aria-label="Computers" className="mb-6 space-y-3">+ {shown.map(({ machine, host }) => {+ const here = machine.current;+ const name = here ? thisComputerLabel() : machine.name;+ const warning = lowDiskWarning(host!, name);+ const extra = extraSpacesLine(host!, here ? "here" : "there");+ const line = here ? extra : [`Updated ${updatedAgo(host!.sampledAtMs, now)}.`, extra].filter(Boolean).join(" ");+ return (+ <div key={machine.id} data-computer-resources={machine.id} className="overflow-hidden rounded-xl border bg-card shadow-xs">+ <div className="flex items-baseline justify-between gap-3 px-4 pt-3">+ <h2 className="truncate text-[13px] font-semibold">{here && machine.name !== name ? `${machine.name} (${thisComputerText()})` : machine.name}</h2>+ <span className="shrink-0 text-xs text-muted-foreground">{machine.online ? "Online" : "Offline"}</span>+ </div>+ {warning ? <LowDiskWarning warning={warning} className="mt-3 border-y" /> : null}+ <div className="grid gap-x-8 gap-y-3 px-4 pt-3 sm:grid-cols-3">+ {hostMeters(host!).map((m) => (+ <MeterRow key={m.label} meter={m} />+ ))}+ </div>+ {line ? <p className="px-4 pt-2.5 pb-3 text-xs text-muted-foreground">{line}</p> : <div className="pb-3" />}+ </div>+ );+ })}+ </section>+ );+}diff --git a/apps/cua-spaces-web/src/components/resources/meters.tsx b/apps/cua-spaces-web/src/components/resources/meters.tsxnew file mode 100644index 0000000000..2f7849e062--- /dev/null+++ b/apps/cua-spaces-web/src/components/resources/meters.tsx@@ -0,0 +1,77 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { Link } from "@tanstack/react-router";++import { CuaKey } from "@/components/cua-key";+import { Button } from "@/components/ui/button";+import type { Meter } from "@/lib/resources";+import { cn } from "@/lib/utils";++/** A thin bar, 0 to 1. Blue; amber when the disk runs low; red when it's out. */+export function Bar({ fill, tone, className }: { fill: number; tone?: Meter["tone"]; className?: string }) {+ return (+ <div className={cn("h-1 overflow-hidden rounded-full bg-foreground/10", className)}>+ <div+ data-bar-fill={Math.round(fill * 100)}+ className={cn("h-full rounded-full transition-[width] duration-500 ease-out", tone === "critical" ? "bg-destructive" : tone === "warning" ? "bg-warning" : "bg-brand-strong")}+ style={{ width: `${Math.max(fill > 0 ? 2 : 0, fill * 100)}%` }}+ />+ </div>+ );+}++/** "Processor 12 cores · 38% busy", with its bar under it. */+export function MeterRow({ meter }: { meter: Meter }) {+ return (+ <div data-meter={meter.label} className="min-w-0">+ <div className="flex items-baseline justify-between gap-3 text-xs">+ <span className="shrink-0 text-muted-foreground">{meter.label}</span>+ <span className="truncate font-medium tabular-nums">{meter.value}</span>+ </div>+ <Bar fill={meter.fill} tone={meter.tone} className="mt-1.5" />+ </div>+ );+}++/** Three short meters in a row, value over bar, for a Space's tile. */+export function CompactMeters({ meters, className }: { meters: Meter[]; className?: string }) {+ return (+ <div data-space-meters="" className={cn("grid grid-cols-3 gap-2.5", className)}>+ {meters.map((m) => (+ <div key={m.label} data-meter={m.label} title={`${m.label}: ${m.help ?? m.value}`} className="min-w-0">+ <div className="truncate text-2xs text-muted-foreground tabular-nums">{m.value}</div>+ <Bar fill={m.fill} tone={m.tone} className="mt-1" />+ </div>+ ))}+ </div>+ );+}++/**+ * "This Mac is almost out of space. Delete old Spaces or snapshots.", with+ * the Cua key and "See what's using space" (the Spaces list, biggest+ * first). `compact` drops the second line, for inside a panel.+ */+export function LowDiskWarning({ warning, compact = false, className }: { warning: { level: "low" | "critical"; title: string; detail: string }; compact?: boolean; className?: string }) {+ return (+ <div+ role="status"+ data-low-disk={warning.level}+ className={cn(+ "flex items-center gap-3 px-4 py-3",+ warning.level === "critical" ? "bg-destructive/10" : "bg-warning/15",+ className,+ )}+ >+ <CuaKey size={24} />+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-semibold">{warning.title}</p>+ {compact ? null : <p className="mt-0.5 text-xs text-muted-foreground">{warning.detail}</p>}+ </div>+ <Button size="sm" variant="outline" data-see-space-use="" render={<Link to="/spaces" search={{ sort: "size" }} />}>+ See what’s using space+ </Button>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/components/resources/space-resources-panel.tsx b/apps/cua-spaces-web/src/components/resources/space-resources-panel.tsxnew file mode 100644index 0000000000..c4efb8798d--- /dev/null+++ b/apps/cua-spaces-web/src/components/resources/space-resources-panel.tsx@@ -0,0 +1,115 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import type { ComputerResources, SpaceResources } from "@/bridge";+import { cores, diskParts, fill, isRunning, LABELS, lowDiskWarning, onHostLine, size, sizeOf } from "@/lib/resources";+import { cn } from "@/lib/utils";++import { Bar, LowDiskWarning } from "./meters";++/**+ * A Space's full numbers on its page: Processor, Memory and Space for+ * files, each what it was given and what it uses now, then "How it fits on+ * this Mac".+ */+export function SpaceResourcesPanel({+ space,+ name,+ host,+ computer,+ siblings,+}: {+ space: SpaceResources;+ /** The Space's name ("macOS 1"). */+ name: string;+ /** Its computer's numbers, when it sent them. */+ host: ComputerResources | null;+ /** "this Mac" (`thisComputerText`), or the other computer's name. */+ computer: string;+ /** Every Space on that computer, with its name, for the disk bar. */+ siblings: { id: string; name: string; bytes: number }[];+}) {+ const u = isRunning(space) ? space.usage : null;+ const whose = `${computer}’s`;+ const memTotal = space.memoryAllocated || u?.memoryTotal || 0;+ const diskTotal = space.diskAllocated || u?.diskTotal || 0;+ const cards = [+ {+ label: LABELS.cpu,+ big: u ? `${Math.round(u.cpuPercent)}% busy` : "Stopped",+ given: space.cpuAllocated ? (host ? `Given ${space.cpuAllocated} of ${whose} ${cores(host.cpuCount)}` : `Given ${cores(space.cpuAllocated)}`) : null,+ fill: u ? fill(u.cpuPercent, 100) : 0,+ note: u ? "Busy means how hard it’s working right now." : "It uses no processor while stopped.",+ },+ {+ label: LABELS.memory,+ big: u ? (memTotal ? sizeOf(u.memoryUsed, memTotal) : size(u.memoryUsed)) : "Off",+ given: space.memoryAllocated ? (host ? `Given ${size(space.memoryAllocated)} of ${whose} ${size(host.memoryTotal)}` : `Given ${size(space.memoryAllocated)}`) : null,+ fill: u ? fill(u.memoryUsed, memTotal) : 0,+ note: u ? "The rest is free for its apps." : "Its memory goes back while it’s stopped.",+ },+ {+ label: LABELS.disk,+ big: u && diskTotal ? sizeOf(u.diskUsed, diskTotal) : diskTotal ? `Up to ${size(diskTotal)}` : "—",+ given: u ? `What ${name} sees inside` : null,+ fill: u ? fill(u.diskUsed, diskTotal) : 0,+ note: onHostLine(space, computer),+ },+ ];+ return (+ <section data-space-resources="" aria-label="Resources" className="mt-6">+ <div className="grid gap-4 md:grid-cols-3">+ {cards.map((c) => (+ <div key={c.label} data-resource-card={c.label} className="rounded-xl border bg-card p-4 shadow-xs">+ <h3 className="text-xs text-muted-foreground">{c.label}</h3>+ <p className="mt-1.5 text-xl leading-tight font-semibold tracking-[-0.01em] tabular-nums">{c.big}</p>+ {c.given ? <p className="mt-1 text-xs text-muted-foreground">{c.given}</p> : null}+ <Bar fill={c.fill} className="mt-3.5" />+ {c.note ? <p className="mt-3 text-xs">{c.note}</p> : null}+ </div>+ ))}+ </div>+ {host ? <DiskFit host={host} computer={computer} spaceId={space.id} siblings={siblings} /> : null}+ <p className="mt-4 px-1 text-xs text-muted-foreground">+ Updates every 10 seconds while this window is open, and every 5 minutes in the background. Cua reads numbers only. It never looks at your file names.+ </p>+ </section>+ );+}++/** "How it fits on this Mac": your own files, each Space, and free space, on one bar. */+function DiskFit({ host, computer, spaceId, siblings }: { host: ComputerResources; computer: string; spaceId: string; siblings: { id: string; name: string; bytes: number }[] }) {+ const parts = diskParts(host, siblings);+ const total = host.diskTotal || 1;+ const warning = lowDiskWarning(host, computer.charAt(0).toUpperCase() + computer.slice(1));+ const segments = [+ { key: "own", label: "Your own files and apps", bytes: parts.own, className: "bg-muted-foreground/60" },+ ...siblings.map((s) => ({ key: s.id, label: s.name, bytes: s.bytes, className: s.id === spaceId ? "bg-brand-strong" : "bg-brand" })),+ ];+ return (+ <div data-disk-fit="" className="mt-4 rounded-xl border bg-card p-4 shadow-xs">+ <div className="flex items-baseline justify-between gap-3">+ <h3 className="text-[13px] font-semibold">How it fits on {computer}</h3>+ <span className="text-xs text-muted-foreground">{size(host.diskTotal)}</span>+ </div>+ <div className="mt-3 flex h-2 overflow-hidden rounded-full bg-foreground/10" role="img" aria-label={`${size(host.diskFree)} free of ${size(host.diskTotal)}`}>+ {segments.map((s) => (+ <div key={s.key} className={cn("h-full", s.className)} style={{ width: `${(s.bytes / total) * 100}%` }} />+ ))}+ </div>+ <ul className="mt-3 flex flex-wrap gap-x-5 gap-y-1.5 text-xs">+ {segments.map((s) => (+ <li key={s.key} data-disk-part={s.key} className="flex items-center gap-1.5">+ <span className={cn("size-2 rounded-xs", s.className)} aria-hidden />+ {s.label} · {size(s.bytes)}+ </li>+ ))}+ <li data-disk-part="free" className="flex items-center gap-1.5">+ <span className="size-2 rounded-xs border bg-foreground/10" aria-hidden />+ Free · {size(parts.free)}+ </li>+ </ul>+ {warning ? <LowDiskWarning warning={warning} compact className="mt-4 rounded-lg border" /> : null}+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/lib/resources.test.ts b/apps/cua-spaces-web/src/lib/resources.test.tsnew file mode 100644index 0000000000..6b8526b02a--- /dev/null+++ b/apps/cua-spaces-web/src/lib/resources.test.ts@@ -0,0 +1,130 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";++import type { ComputerResources, SpaceResources } from "@/bridge";+import { DEMO_DISK_FREE, demoDiskWarning, demoResources } from "@/bridge/adapters/demo/resources";+import { demoSpaceRows } from "@/bridge/adapters/demo-data";+import { diskParts, extraSpacesLine, hostMeters, lowDiskWarning, onHostLine, size, sizeOf, spaceMeters, updatedAgo } from "./resources";++const GB = 1_000_000_000;++const host = (free: number, total = 1000 * GB): ComputerResources => ({+ id: "this-mac",+ name: "",+ online: true,+ sampledAtMs: 0,+ cpuCount: 12,+ cpuPercent: 38,+ loadAverage1m: 4,+ memoryTotal: 64 * GB,+ memoryUsed: 41 * GB,+ diskTotal: total,+ diskFree: free,+ spacesCount: 2,+ spacesRunning: 1,+ spacesCpuAllocated: 6,+ spacesMemoryAllocated: 12 * GB,+ spacesMemoryUsed: 3 * GB,+ spacesDiskBytes: 25 * GB,+ spacesDiskExact: false,+ warning: demoDiskWarning(free, total),+});++const space = (over: Partial<SpaceResources> = {}): SpaceResources => ({+ id: "local:macos-1",+ powerState: "running",+ cpuAllocated: 4,+ memoryAllocated: 8 * GB,+ diskAllocated: 80 * GB,+ usage: { cpuCount: 4, cpuPercent: 22, loadAverage1m: 1, memoryUsed: 3.1 * GB, memoryTotal: 8 * GB, memoryLimited: true, diskUsed: 34 * GB, diskTotal: 80 * GB, diskLimited: true },+ diskOnHost: { bytes: 19 * GB, allocated: 34 * GB, sharesSpace: true },+ ...over,+});++describe("sizes", () => {+ it("reads as people say them", () => {+ expect(size(41 * GB)).toBe("41 GB");+ expect(size(3.1 * GB)).toBe("3.1 GB");+ expect(size(8 * GB)).toBe("8 GB");+ expect(size(1000 * GB)).toBe("1 TB");+ expect(size(1500 * GB)).toBe("1.5 TB");+ expect(sizeOf(3.1 * GB, 8 * GB)).toBe("3.1 of 8 GB");+ expect(sizeOf(800 * GB, 1000 * GB)).toBe("800 GB of 1 TB");+ });+});++describe("the low-disk line", () => {+ it("the demo follows the daemon's rule: 50 GB or 15%, whichever is higher, capped at 100 GB", () => {+ const level = (free: number, total: number) => demoDiskWarning(free * GB, total * GB).level;+ expect(level(120, 1000)).toBe("ok");+ expect(level(90, 1000)).toBe("low");+ expect(level(45, 256)).toBe("low");+ expect(level(60, 256)).toBe("ok");+ expect(level(70, 500)).toBe("low");+ expect(level(4, 1000)).toBe("critical");+ });++ it("follows the host's level, and says it in plain words", () => {+ expect(lowDiskWarning({ ...host(300 * GB), warning: { level: "low", free: 300 * GB, total: 1000 * GB, threshold: 100 * GB } }, "This Mac")?.level).toBe("low");+ expect(lowDiskWarning({ ...host(41 * GB), warning: { level: "ok", free: 41 * GB, total: 1000 * GB, threshold: 0 } }, "This Mac")).toBeNull();+ expect(lowDiskWarning(host(41 * GB), "This Mac")).toEqual({+ level: "low",+ title: "This Mac is almost out of space. Delete old Spaces or snapshots.",+ detail: "41 GB free of 1 TB. New Spaces may not fit, and apps can slow down.",+ });+ expect(lowDiskWarning(host(3 * GB), "This Mac")?.title).toBe("This Mac is out of space. Delete old Spaces or snapshots.");+ expect(lowDiskWarning(host(300 * GB), "This Mac")).toBeNull();+ });+});++describe("meters", () => {+ it("This Mac: processor, memory and space for files", () => {+ const [cpu, mem, disk] = hostMeters(host(41 * GB));+ expect([cpu!.label, cpu!.value]).toEqual(["Processor", "12 cores · 38% busy"]);+ expect([mem!.label, mem!.value]).toEqual(["Memory", "41 of 64 GB in use"]);+ expect([disk!.label, disk!.value, disk!.tone]).toEqual(["Space for files", "41 GB free of 1 TB", "warning"]);+ expect(hostMeters(host(300 * GB))[2]!.tone).toBeUndefined();+ expect(extraSpacesLine(host(41 * GB), "here")).toBe("Your extra Spaces use 6 cores, 12 GB of memory and about 25 GB for files.");+ expect(extraSpacesLine({ ...host(41 * GB), spacesCount: 0 }, "here")).toBeNull();+ });++ it("a Space: in use now, and a stopped one keeps its disk", () => {+ expect(spaceMeters(space()).map((m) => m.value)).toEqual(["22% busy", "3.1 of 8 GB", "About 19 GB"]);+ expect(spaceMeters(space())[2]!.help).toBe("Uses about 19 GB on this Mac (shares space with other copies).");+ const stopped = spaceMeters(space({ powerState: "stopped", usage: null }));+ expect(stopped.map((m) => m.value)).toEqual(["Stopped", "Off", "About 19 GB"]);+ expect(stopped[0]!.fill).toBe(0);+ });++ it("is honest about shared disk", () => {+ expect(onHostLine(space())).toBe("Uses about 19 GB on this Mac (shares space with other copies).");+ expect(onHostLine(space({ diskOnHost: { bytes: 6 * GB, allocated: 6 * GB, sharesSpace: false } }))).toBe("Uses about 6 GB on this Mac.");+ // Couldn't measure, but shared; a container: nothing.+ expect(onHostLine(space({ diskOnHost: { bytes: null, allocated: 30 * GB, sharesSpace: true } }))).toBe("Shares space with other copies.");+ expect(onHostLine(space({ diskOnHost: null }))).toBeNull();+ });++ it("splits the disk into your files, each Space, and free", () => {+ const parts = diskParts(host(41 * GB), [{ name: "macOS 1", bytes: 19 * GB }, { name: "Linux 1", bytes: 6 * GB }]);+ expect(parts.own).toBe(934 * GB);+ expect(parts.free).toBe(41 * GB);+ });++ it("says how old another computer's summary is", () => {+ expect(updatedAgo(0, 30_000)).toBe("just now");+ expect(updatedAgo(0, 2 * 60_000)).toBe("2 min ago");+ expect(updatedAgo(0, 3 * 3_600_000)).toBe("3 hours ago");+ });+});++describe("the demo host's numbers", () => {+ it("cover This Mac's Spaces and sum what they use", () => {+ const snap = demoResources(demoSpaceRows(0), 0, DEMO_DISK_FREE.low);+ expect([snap.thisMac.id, ...snap.computers.map((c) => c.id)]).toEqual(["this-mac", "mac-mini"]);+ expect(snap.spaces.every((s) => s.id.startsWith("local:"))).toBe(true);+ expect(snap.thisMac.spacesDiskBytes).toBe(25 * GB);+ expect(snap.warning.level).toBe("low");+ });+});diff --git a/apps/cua-spaces-web/src/lib/resources.ts b/apps/cua-spaces-web/src/lib/resources.tsnew file mode 100644index 0000000000..60494a15dd--- /dev/null+++ b/apps/cua-spaces-web/src/lib/resources.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The words and bar fills for processor, memory and disk numbers+ * (CUA-1880). Plain labels only: "Processor", "Memory", "Space for files",+ * "busy", "in use", "free". Never vCPU, RSS, APFS, sparse or cgroup.+ */++import type { ComputerResources, SpaceResources } from "@/bridge";++export const LABELS = { cpu: "Processor", memory: "Memory", disk: "Space for files" } as const;++const GB = 1_000_000_000;++/** A number of GB as people read it: "3.1", "41", "8". */+function gbNumber(bytes: number): string {+ const tenths = Math.round((bytes / GB) * 10) / 10;+ return tenths >= 9.95 || Number.isInteger(tenths) ? String(Math.round(tenths)) : tenths.toFixed(1);+}++/** "41 GB", "3.1 GB", "1 TB", "1.5 TB". */+export function size(bytes: number): string {+ if (bytes >= 999.5 * GB) {+ const tb = Math.round(bytes / (GB * 100)) / 10;+ return `${Number.isInteger(tb) ? tb.toFixed(0) : tb.toFixed(1)} TB`;+ }+ return `${gbNumber(bytes)} GB`;+}++/** "3.1 of 8 GB" (same unit) or "800 GB of 1 TB". */+export function sizeOf(used: number, total: number): string {+ const whole = size(total);+ const unit = whole.split(" ")[1];+ const part = size(used);+ return part.endsWith(` ${unit}`) ? `${part.split(" ")[0]} of ${whole}` : `${part} of ${whole}`;+}++export const cores = (n: number) => `${n} ${n === 1 ? "core" : "cores"}`;++/** A bar's fill, 0 to 1. */+export const fill = (part: number | null | undefined, whole: number | null | undefined) =>+ part == null || !whole ? 0 : Math.min(1, Math.max(0, part / whole));++/** How long ago another computer measured: "just now", "2 min ago", "3 hours ago". */+export function updatedAgo(sampledAtMs: number, now: number): string {+ const min = Math.floor((now - sampledAtMs) / 60_000);+ if (min < 1) return "just now";+ if (min < 60) return `${min} min ago`;+ const h = Math.floor(min / 60);+ if (h < 24) return `${h} ${h === 1 ? "hour" : "hours"} ago`;+ const d = Math.floor(h / 24);+ return `${d} ${d === 1 ? "day" : "days"} ago`;+}++export interface Meter {+ label: string;+ value: string;+ /** 0 to 1. */+ fill: number;+ tone?: "warning" | "critical";+ /** The longer words, for a tooltip. */+ help?: string;+}++const tone = (c: ComputerResources): Meter["tone"] => (c.warning.level === "critical" ? "critical" : c.warning.level === "low" ? "warning" : undefined);++/** A computer's three meters: "12 cores · 38% busy", "41 of 64 GB in use", "41 GB free of 1 TB". */+export function hostMeters(c: ComputerResources): Meter[] {+ return [+ { label: LABELS.cpu, value: `${cores(c.cpuCount)} · ${Math.round(c.cpuPercent)}% busy`, fill: fill(c.cpuPercent, 100) },+ { label: LABELS.memory, value: `${sizeOf(c.memoryUsed, c.memoryTotal)} in use`, fill: fill(c.memoryUsed, c.memoryTotal) },+ { label: LABELS.disk, value: `${size(c.diskFree)} free of ${size(c.diskTotal)}`, fill: fill(c.diskTotal - c.diskFree, c.diskTotal), tone: tone(c) },+ ];+}++/** "Your extra Spaces use 6 cores, 12 GB of memory and about 25 GB for files." Null with none. */+export function extraSpacesLine(c: ComputerResources, where: "here" | "there"): string | null {+ if (!c.spacesCount) return null;+ return `Your extra Spaces${where === "there" ? " there" : ""} use ${cores(c.spacesCpuAllocated)}, ${size(c.spacesMemoryAllocated)} of memory and about ${size(c.spacesDiskBytes)} for files.`;+}++export const isRunning = (s: SpaceResources) => s.powerState === "running";++/**+ * What a Space costs this Mac's disk, by the contract's rule: "Uses about+ * 19 GB on this Mac", plus "(shares space with other copies)" when it does;+ * "Shares space with other copies" when it couldn't be measured; null when+ * there's nothing to say.+ */+export function onHostLine(s: SpaceResources, computer = "this Mac"): string | null {+ const d = s.diskOnHost;+ if (!d) return null;+ if (d.bytes == null) return d.sharesSpace ? "Shares space with other copies." : null;+ return `Uses about ${size(d.bytes)} on ${computer}${d.sharesSpace ? " (shares space with other copies)" : ""}.`;+}++/** A Space's three short meters on its tile: "22% busy", "3.1 of 8 GB", "About 19 GB" (the+ * tooltip and the Space's page say the rest). */+export function spaceMeters(s: SpaceResources): Meter[] {+ const on = isRunning(s) && s.usage !== null;+ const u = s.usage;+ const memTotal = s.memoryAllocated || u?.memoryTotal || 0;+ const onHost = s.diskOnHost?.bytes ?? null;+ return [+ {+ label: LABELS.cpu,+ value: on ? `${Math.round(u!.cpuPercent)}% busy` : "Stopped",+ fill: on ? fill(u!.cpuPercent, 100) : 0,+ help: s.cpuAllocated ? (on ? `${cores(s.cpuAllocated)} · ${Math.round(u!.cpuPercent)}% busy` : `Given ${cores(s.cpuAllocated)}`) : undefined,+ },+ {+ label: LABELS.memory,+ value: on && memTotal ? sizeOf(u!.memoryUsed, memTotal) : on ? size(u!.memoryUsed) : "Off",+ fill: on ? fill(u!.memoryUsed, memTotal) : 0,+ help: s.memoryAllocated ? `Given ${size(s.memoryAllocated)}` : undefined,+ },+ {+ label: LABELS.disk,+ value: onHost != null ? `About ${size(onHost)}` : s.diskAllocated ? `Up to ${size(s.diskAllocated)}` : "—",+ fill: fill(onHost, s.diskAllocated),+ help: onHostLine(s) ?? undefined,+ },+ ];+}++/** The low-disk warning's words, or null when there's room. */+export function lowDiskWarning(c: ComputerResources, computer: string): { level: "low" | "critical"; title: string; detail: string } | null {+ const level = c.warning.level;+ if (level === "ok") return null;+ const free = `${size(c.diskFree)} free of ${size(c.diskTotal)}.`;+ return level === "critical"+ ? { level, title: `${computer} is out of space. Delete old Spaces or snapshots.`, detail: `${free} New Spaces can’t start until there’s more room.` }+ : { level, title: `${computer} is almost out of space. Delete old Spaces or snapshots.`, detail: `${free} New Spaces may not fit, and apps can slow down.` };+}++/** The pieces of "How it fits on this Mac": your own files, each Space, and free. */+export function diskParts(c: ComputerResources, spaces: { name: string; bytes: number }[]): { own: number; free: number } {+ const used = c.diskTotal - c.diskFree;+ const inSpaces = spaces.reduce((n, s) => n + s.bytes, 0);+ return { own: Math.max(0, used - inSpaces), free: c.diskFree };+}diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsxindex 1bf04fe9a6..bf02dbec3c 100644--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx@@ -5,19 +5,21 @@ import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";import { ArrowDownCircleIcon, ChevronLeftIcon, MonitorIcon, PictureInPicture2Icon, PlayIcon, SquareIcon, Trash2Icon, UserPlusIcon } from "lucide-react";import { useEffect, useRef, useState, type ReactNode } from "react";-import { parseDropped, useBridge, useDevices, useExperiments, useMachines, useSession, useShareSheet, useSpaceDetail, useSpaceFiles, useSpaces, useTeleport, type CreateReport, type Space, type StreamRow } from "@/bridge";+import { hostResources, parseDropped, spaceResources, useBridge, useResources, useDevices, useExperiments, useMachines, useSession, useShareSheet, useSpaceDetail, useSpaceFiles, useSpaces, useTeleport, type CreateReport, type Machine, type ResourcesSnapshot, type Space, type StreamRow } from "@/bridge";import { DiagnosticReportDialog } from "@/components/diagnostic-report-dialog";import { OsIcon } from "@/components/os-icon";import { EmptyState, Page } from "@/components/page";import { AgentsSection } from "@/components/space-detail/agents-section";import { DropWell } from "@/components/space-detail/drop-well";import { FactList } from "@/components/space-detail/facts";+import { SpaceResourcesPanel } from "@/components/resources/space-resources-panel";import { StreamSection } from "@/components/space-detail/stream-section";import { StreamSurface } from "@/components/space-detail/stream-surface";import { StateLabel } from "@/components/state-dot";import { ConfirmDialog } from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import { toast } from "@/components/ui/toast";+import { thisComputerText } from "@/lib/host-labels";import { useSpaceVolumeError } from "@/lib/space-volume";import { volumeUnavailableNote } from "@/lib/volume-notes";import { canDelete, canPower, createError, createProgress, machineName, powerLabel, powerPending, spacePlace, spaceState } from "@/lib/spaces";@@ -58,6 +60,7 @@ function SpaceDetailPage() {const [report, setReport] = useState<CreateReport | null>(null);const [reportOpen, setReportOpen] = useState(false);const { data: machines = [] } = useMachines();+ const resources = useResources();const [confirm, setConfirm] = useState<Confirm>(null);const teleport = useTeleport();const sharing = useShareSheet();@@ -283,6 +286,8 @@ function SpaceDetailPage() {</StreamSurface>)}+ <SpaceResources space={space} spaces={spaces ?? []} snapshot={resources} machines={machines} />+<div className="mt-8 grid items-start gap-x-6 md:grid-cols-2"><div><FactList title="Details" facts={detail.facts} />@@ -479,3 +484,21 @@ function surfaceState(}return undefined;}++/** Processor, memory and disk for this Space, when its computer sends them. */+function SpaceResources({ space, spaces, snapshot, machines }: { space: Space; spaces: Space[]; snapshot: ResourcesSnapshot | null; machines: Machine[] }) {+ const mine = spaceResources(snapshot, space.id);+ const state = spaceState(space);+ if (!mine || (state !== "running" && state !== "stopped")) return null;+ const local = space.provider === "local";+ const machine = local ? machines.find((m) => m.current) : machines.find((m) => m.id === space.host || m.spaceIds.includes(space.id));+ const host = hostResources(snapshot, machine);+ const computer = local ? thisComputerText() : (machine?.name ?? space.hostName ?? "its computer");+ // The Spaces on the same computer, with the numbers it sent, for the disk bar.+ const sameComputer = (s: Space) => (local ? s.provider === "local" : s.host === space.host);+ const siblings = spaces.flatMap((s) => {+ const bytes = sameComputer(s) ? spaceResources(snapshot, s.id)?.diskOnHost?.bytes : null;+ return bytes != null ? [{ id: s.id, name: s.name, bytes }] : [];+ });+ return <SpaceResourcesPanel space={mine} name={space.name} host={host} computer={computer} siblings={siblings} />;+}diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsxindex 2f214a674c..80bf2ee9a1 100644--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx@@ -5,12 +5,14 @@ import { createFileRoute, Link } from "@tanstack/react-router";import { ArrowDownCircleIcon, KeyRoundIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, PowerIcon, SearchIcon } from "lucide-react";import { useEffect, useRef, useState, type DragEvent } from "react";-import { emptyHome, useBridge, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, useWindowDropTarget, type Space } from "@/bridge";+import { emptyHome, spaceResources, useBridge, useResources, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, useWindowDropTarget, type Space, type SpaceResources } from "@/bridge";import { EmptyHome } from "@/components/empty-home";import { GettingStarted } from "@/components/getting-started";import { FirstRunTodosCard, useFirstRunTodosShown } from "@/components/first-run-todos";import { OsIcon } from "@/components/os-icon";import { EmptyState, Page, PageHeader } from "@/components/page";+import { ComputersResources } from "@/components/resources/computer-resources";+import { CompactMeters } from "@/components/resources/meters";import { SpaceCanvas } from "@/components/space-canvas";import { StateLabel } from "@/components/state-dot";import { useTileVideo } from "@/components/video/tile-video";@@ -21,10 +23,15 @@ import { Segmented } from "@/components/ui/segmented";import { toast, toastError } from "@/components/ui/toast";import { creatingLine, thisComputerText } from "@/lib/host-labels";import { plural } from "@/lib/plural";+import { spaceMeters } from "@/lib/resources";import { cn } from "@/lib/utils";import { createError, createProgress, machineName, matchesQuery, powerButton, powerError, realSpaces, spacePlace, spaceState, visibleSpaces, type SpaceFilter } from "@/lib/spaces";-export const Route = createFileRoute("/spaces/")({ component: SpacesPage });+export const Route = createFileRoute("/spaces/")({+ component: SpacesPage,+ // `?sort=size`: biggest on this Mac's disk first (the low-disk warning's "See what's using space").+ validateSearch: (s: Record<string, unknown>): { sort?: "size" } => (s.sort === "size" ? { sort: "size" } : {}),+});const FILTERS: { value: SpaceFilter; label: string }[] = [{ value: "all", label: "All" },@@ -38,6 +45,8 @@ function SpacesPage() {// Machines' own desktops are on Machines, not here.const spaces = realSpaces(all);const { data: machines = [] } = useMachines();+ const { sort } = Route.useSearch();+ const resources = useResources();const [filter, setFilter] = useState<SpaceFilter>("all");const [query, setQuery] = useState("");const newSpace = useNewSpace();@@ -47,7 +56,9 @@ function SpacesPage() {const { core } = useBridge();const { env } = useNewSpaceWizard();const home = emptyHome(core, env.hostArch);- const shown = visibleSpaces(spaces, filter, (s) => matchesQuery(core, s, machineName(machines, s), query));+ const visible = visibleSpaces(spaces, filter, (s) => matchesQuery(core, s, machineName(machines, s), query));+ const onDisk = (s: Space) => spaceResources(resources, s.id)?.diskOnHost?.bytes ?? -1;+ const shown = sort === "size" ? [...visible].sort((a, b) => onDisk(b) - onDisk(a)) : visible;const access = useSpaceAccess(spaces);const running = spaces.filter((s) => spaceState(s) === "running").length;// After the first run's Finish later, its to-do list stands in for the checklist.@@ -66,6 +77,15 @@ function SpacesPage() {/><FirstRunTodosCard />{firstRunTodos ? null : <GettingStarted />}+ <ComputersResources snapshot={resources} machines={machines} />+ {sort === "size" ? (+ <p data-sorted-by-size="" className="mb-3 flex items-center gap-2 px-1 text-xs text-muted-foreground">+ Biggest first, by how much space each one uses on its computer.+ <Link to="/spaces" search={{}} className="font-medium text-foreground underline-offset-2 hover:underline">+ Show the usual order+ </Link>+ </p>+ ) : null}<div className="mb-4 flex items-center gap-3"><Segmented aria-label="Filter by state" value={filter} options={FILTERS} onValueChange={setFilter} />{/* Find a Space by name, detail, id or machine (the SwiftUI sidebar's search). */}@@ -120,7 +140,7 @@ function SpacesPage() {<ul className="grid grid-cols-[repeat(auto-fill,minmax(232px,1fr))] gap-4">{shown.map((space) => (<li key={space.id}>- <SpaceTile space={space} machine={machineName(machines, space)} accessKey={access.signedIn.has(space.id) ? access.accessKey(space.id) : undefined} />+ <SpaceTile space={space} machine={machineName(machines, space)} resources={spaceResources(resources, space.id)} accessKey={access.signedIn.has(space.id) ? access.accessKey(space.id) : undefined} /></li>))}</ul>@@ -129,7 +149,7 @@ function SpacesPage() {);}-function SpaceTile({ space, machine, accessKey }: { space: Space; machine: string; accessKey?: string | null }) {+function SpaceTile({ space, machine, resources, accessKey }: { space: Space; machine: string; resources: SpaceResources | null; accessKey?: string | null }) {const drop = useTileDrop(space);// A real window dragged over this tile (the host hit-tests the tiles' boxes and says which; macOS only).const windowOver = useWindowDropTarget() === space.id;@@ -142,7 +162,7 @@ function SpaceTile({ space, machine, accessKey }: { space: Space; machine: strindata-window-over={windowOver || undefined}{...drop.handlers}>- <SpaceLink space={space} machine={machine} windowOver={windowOver} />+ <SpaceLink space={space} machine={machine} resources={resources} windowOver={windowOver} />{drop.over ? <DropOverlay space={space} accepts={drop.over === "accept"} /> : null}{/* A drop on the tile still going in: the core's "Sending …" line. */}{drop.status?.kind === "working" && !drop.over ? (@@ -263,7 +283,7 @@ function TilePower({ space }: { space: Space }) {);}-function SpaceLink({ space, machine, windowOver = false }: { space: Space; machine: string; windowOver?: boolean }) {+function SpaceLink({ space, machine, resources = null, windowOver = false }: { space: Space; machine: string; resources?: SpaceResources | null; windowOver?: boolean }) {return (<Linkto="/spaces/$spaceId"@@ -303,6 +323,8 @@ function SpaceLink({ space, machine, windowOver = false }: { space: Space; machi</div><StateLabel state={spaceState(space)} space={space} className="mt-px shrink-0" /></div>+ {/* What it was given and uses now, when its computer says. */}+ {resources && (spaceState(space) === "running" || spaceState(space) === "stopped") ? <CompactMeters meters={spaceMeters(resources)} className="px-1.5 pt-1 pb-1.5" /> : null}</Link>);}