Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(spaces): honest numbers in a Space's resources dialog (#6058)

ddupont9c7d8b5c4a4e
diff --git a/apps/cua-spaces-desktop/src/bridge/resources.ts b/apps/cua-spaces-desktop/src/bridge/resources.ts
index e001784fb7..418d2cd773 100644
--- a/apps/cua-spaces-desktop/src/bridge/resources.ts
+++ b/apps/cua-spaces-desktop/src/bridge/resources.ts
@@ -107,11 +107,15 @@ function spaceJson(s: SdkSpace) {
memoryTotal: num(u.memoryTotal),
memoryLimited: u.memoryLimited,
diskUsed: num(u.diskUsed),
- diskTotal: num(u.diskTotal),
+ // Absent: no size of its own. Never a sentinel (the SDK says none).
+ diskTotal: u.diskTotal === undefined || u.diskTotal === null ? null : num(u.diskTotal),
diskLimited: u.diskLimited,
}
: null,
diskOnHost: d ? { bytes: d.bytes === undefined ? null : num(d.bytes), allocated: num(d.allocated), sharesSpace: d.sharesSpace } : null,
+ base: s.base
+ ? { key: s.base.key, image: s.base.image, bytes: s.base.bytes === undefined || s.base.bytes === null ? null : num(s.base.bytes), sharedWith: s.base.sharedWith }
+ : null,
};
}
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
index b9c07e02c9..eb5aef1e8f 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts
@@ -11519,9 +11519,10 @@ export type GuestUsage = {
*/
diskUsed: bigint,
/**
- * Disk size, bytes.
+ * Disk size, bytes; absent when the guest's file system has no size
+ * of its own (gVisor's root overlay) or did not say. Never a sentinel.
*/
- diskTotal: bigint,
+ diskTotal?: bigint,
/**
* `disk_total` is the guest's own disk.
*/
@@ -11556,7 +11557,7 @@ const FfiConverterTypeGuestUsage = (() => {
memoryTotal: FfiConverterUInt64.read(from),
memoryLimited: FfiConverterBool.read(from),
diskUsed: FfiConverterUInt64.read(from),
- diskTotal: FfiConverterUInt64.read(from),
+ diskTotal: FfiConverterOptionalUInt64.read(from),
diskLimited: FfiConverterBool.read(from)
};
}
@@ -11568,7 +11569,7 @@ const FfiConverterTypeGuestUsage = (() => {
FfiConverterUInt64.write(value.memoryTotal, into);
FfiConverterBool.write(value.memoryLimited, into);
FfiConverterUInt64.write(value.diskUsed, into);
- FfiConverterUInt64.write(value.diskTotal, into);
+ FfiConverterOptionalUInt64.write(value.diskTotal, into);
FfiConverterBool.write(value.diskLimited, into);
}
allocationSize(value: TypeName): number {
@@ -11579,7 +11580,7 @@ const FfiConverterTypeGuestUsage = (() => {
FfiConverterUInt64.allocationSize(value.memoryTotal) +
FfiConverterBool.allocationSize(value.memoryLimited) +
FfiConverterUInt64.allocationSize(value.diskUsed) +
- FfiConverterUInt64.allocationSize(value.diskTotal) +
+ FfiConverterOptionalUInt64.allocationSize(value.diskTotal) +
FfiConverterBool.allocationSize(value.diskLimited);
}
@@ -15852,6 +15853,74 @@ const FfiConverterTypeResolvedImage = (() => {
return new FFIConverter();
})();
+/**
+ * A base image several Spaces share copy-on-write (a container image's
+ * layers, the image a VM disk was cloned from).
+ */
+export type SharedBase = {
+ /**
+ * Which base: Spaces with the same key share the same blocks.
+ */
+ key: string,
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */
+ image: string,
+ /**
+ * What it takes on this computer, once for all its Spaces; absent when
+ * the runtime cannot tell it apart from the Spaces' own data.
+ */
+ bytes?: bigint,
+ /**
+ * Local Spaces that use it, this one included.
+ */
+ sharedWith: number
+}
+
+/**
+ * Generated factory for {@link SharedBase} record objects.
+ */
+export const SharedBase = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SharedBase, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SharedBase>,
+ });
+})();
+
+const FfiConverterTypeSharedBase = (() => {
+ type TypeName = SharedBase;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ key: FfiConverterString.read(from),
+ image: FfiConverterString.read(from),
+ bytes: FfiConverterOptionalUInt64.read(from),
+ sharedWith: FfiConverterUInt32.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.key, into);
+ FfiConverterString.write(value.image, into);
+ FfiConverterOptionalUInt64.write(value.bytes, into);
+ FfiConverterUInt32.write(value.sharedWith, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.key) +
+ FfiConverterString.allocationSize(value.image) +
+ FfiConverterOptionalUInt64.allocationSize(value.bytes) +
+ FfiConverterUInt32.allocationSize(value.sharedWith);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One extra Space on this Mac.
*/
@@ -15881,9 +15950,16 @@ export type SpaceResources = {
*/
usage?: GuestUsage,
/**
- * What it costs this Mac; absent for a container.
+ * What it costs this Mac: its own data only, never the base it
+ * shares; absent when there is nothing to measure.
*/
- diskOnHost?: DiskOnHost
+ diskOnHost?: DiskOnHost,
+ /**
+ * The base image it is a copy-on-write copy of, counted once for all
+ * the Spaces that share it; absent when it has none or the runtime
+ * cannot tell it apart.
+ */
+ base?: SharedBase
}
/**
@@ -15913,7 +15989,8 @@ const FfiConverterTypeSpaceResources = (() => {
memoryAllocated: FfiConverterUInt64.read(from),
diskAllocated: FfiConverterUInt64.read(from),
usage: FfiConverterOptionalTypeGuestUsage.read(from),
- diskOnHost: FfiConverterOptionalTypeDiskOnHost.read(from)
+ diskOnHost: FfiConverterOptionalTypeDiskOnHost.read(from),
+ base: FfiConverterOptionalTypeSharedBase.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -15924,6 +16001,7 @@ const FfiConverterTypeSpaceResources = (() => {
FfiConverterUInt64.write(value.diskAllocated, into);
FfiConverterOptionalTypeGuestUsage.write(value.usage, into);
FfiConverterOptionalTypeDiskOnHost.write(value.diskOnHost, into);
+ FfiConverterOptionalTypeSharedBase.write(value.base, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.id) +
@@ -15932,7 +16010,8 @@ const FfiConverterTypeSpaceResources = (() => {
FfiConverterUInt64.allocationSize(value.memoryAllocated) +
FfiConverterUInt64.allocationSize(value.diskAllocated) +
FfiConverterOptionalTypeGuestUsage.allocationSize(value.usage) +
- FfiConverterOptionalTypeDiskOnHost.allocationSize(value.diskOnHost);
+ FfiConverterOptionalTypeDiskOnHost.allocationSize(value.diskOnHost) +
+ FfiConverterOptionalTypeSharedBase.allocationSize(value.base);
}
};
@@ -45571,6 +45650,9 @@ const FfiConverterOptionalTypeGuestUsage = new FfiConverterOptional(FfiConverter
// FfiConverter for DiskOnHost | undefined
const FfiConverterOptionalTypeDiskOnHost = new FfiConverterOptional(FfiConverterTypeDiskOnHost);
+// FfiConverter for SharedBase | undefined
+const FfiConverterOptionalTypeSharedBase = new FfiConverterOptional(FfiConverterTypeSharedBase);
+
// FfiConverter for Array<SpaceResources>
const FfiConverterSequenceTypeSpaceResources = new FfiConverterArray(FfiConverterTypeSpaceResources);
@@ -47587,6 +47669,7 @@ export default Object.freeze({
FfiConverterTypeShare,
FfiConverterTypeShareAccess,
FfiConverterTypeShareCheck,
+ FfiConverterTypeSharedBase,
FfiConverterTypeSiteLoginOptions,
FfiConverterTypeSiteLoginReport,
FfiConverterTypeSnapshotFallbackOptions,
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index 656add5ed3..da689322ed 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -26035,9 +26035,11 @@ export type AppGuestUsage = {
*/
diskUsed: bigint,
/**
- * Disk size, bytes.
+ * Disk size, bytes; none when the guest's file system has no size of
+ * its own. A sentinel (`i64::MAX`, `u64::MAX`, -1) or 0 reads as none
+ * ([`known_size`]), so no shell ever shows one.
*/
- diskTotal: bigint,
+ diskTotal?: bigint,
/**
* `disk_total` is the guest's own disk.
*/
@@ -26072,7 +26074,7 @@ const FfiConverterTypeAppGuestUsage = (() => {
memoryTotal: FfiConverterUInt64.read(from),
memoryLimited: FfiConverterBool.read(from),
diskUsed: FfiConverterUInt64.read(from),
- diskTotal: FfiConverterUInt64.read(from),
+ diskTotal: FfiConverterOptionalUInt64.read(from),
diskLimited: FfiConverterBool.read(from)
};
}
@@ -26084,7 +26086,7 @@ const FfiConverterTypeAppGuestUsage = (() => {
FfiConverterUInt64.write(value.memoryTotal, into);
FfiConverterBool.write(value.memoryLimited, into);
FfiConverterUInt64.write(value.diskUsed, into);
- FfiConverterUInt64.write(value.diskTotal, into);
+ FfiConverterOptionalUInt64.write(value.diskTotal, into);
FfiConverterBool.write(value.diskLimited, into);
}
allocationSize(value: TypeName): number {
@@ -26095,7 +26097,7 @@ const FfiConverterTypeAppGuestUsage = (() => {
FfiConverterUInt64.allocationSize(value.memoryTotal) +
FfiConverterBool.allocationSize(value.memoryLimited) +
FfiConverterUInt64.allocationSize(value.diskUsed) +
- FfiConverterUInt64.allocationSize(value.diskTotal) +
+ FfiConverterOptionalUInt64.allocationSize(value.diskTotal) +
FfiConverterBool.allocationSize(value.diskLimited);
}
@@ -38669,6 +38671,70 @@ const FfiConverterTypeAppResourceEditView = (() => {
return new FFIConverter();
})();
+export type AppSharedBase = {
+ /**
+ * Spaces with the same key share the same blocks.
+ */
+ key: string,
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */
+ image: string,
+ /**
+ * What it takes on this Mac, once; none when the runtime cannot tell
+ * it apart from the Spaces' own data.
+ */
+ bytes?: bigint,
+ /**
+ * Local Spaces that use it, this one included.
+ */
+ sharedWith: number
+}
+
+/**
+ * Generated factory for {@link AppSharedBase} record objects.
+ */
+export const AppSharedBase = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppSharedBase, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppSharedBase>,
+ });
+})();
+
+const FfiConverterTypeAppSharedBase = (() => {
+ type TypeName = AppSharedBase;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ key: FfiConverterString.read(from),
+ image: FfiConverterString.read(from),
+ bytes: FfiConverterOptionalUInt64.read(from),
+ sharedWith: FfiConverterUInt32.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.key, into);
+ FfiConverterString.write(value.image, into);
+ FfiConverterOptionalUInt64.write(value.bytes, into);
+ FfiConverterUInt32.write(value.sharedWith, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.key) +
+ FfiConverterString.allocationSize(value.image) +
+ FfiConverterOptionalUInt64.allocationSize(value.bytes) +
+ FfiConverterUInt32.allocationSize(value.sharedWith);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type AppSpaceResources = {
/**
* `local:<name>`.
@@ -38695,9 +38761,13 @@ export type AppSpaceResources = {
*/
usage?: AppGuestUsage,
/**
- * What it costs this Mac; none for a container.
+ * What it costs this Mac: its own data only, never the base it shares.
*/
- diskOnHost?: AppDiskOnHost
+ diskOnHost?: AppDiskOnHost,
+ /**
+ * The base image it is a copy-on-write copy of, counted once.
+ */
+ base?: AppSharedBase
}
/**
@@ -38727,7 +38797,8 @@ const FfiConverterTypeAppSpaceResources = (() => {
memoryAllocated: FfiConverterUInt64.read(from),
diskAllocated: FfiConverterUInt64.read(from),
usage: FfiConverterOptionalTypeAppGuestUsage.read(from),
- diskOnHost: FfiConverterOptionalTypeAppDiskOnHost.read(from)
+ diskOnHost: FfiConverterOptionalTypeAppDiskOnHost.read(from),
+ base: FfiConverterOptionalTypeAppSharedBase.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -38738,6 +38809,7 @@ const FfiConverterTypeAppSpaceResources = (() => {
FfiConverterUInt64.write(value.diskAllocated, into);
FfiConverterOptionalTypeAppGuestUsage.write(value.usage, into);
FfiConverterOptionalTypeAppDiskOnHost.write(value.diskOnHost, into);
+ FfiConverterOptionalTypeAppSharedBase.write(value.base, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.id) +
@@ -38746,7 +38818,8 @@ const FfiConverterTypeAppSpaceResources = (() => {
FfiConverterUInt64.allocationSize(value.memoryAllocated) +
FfiConverterUInt64.allocationSize(value.diskAllocated) +
FfiConverterOptionalTypeAppGuestUsage.allocationSize(value.usage) +
- FfiConverterOptionalTypeAppDiskOnHost.allocationSize(value.diskOnHost);
+ FfiConverterOptionalTypeAppDiskOnHost.allocationSize(value.diskOnHost) +
+ FfiConverterOptionalTypeAppSharedBase.allocationSize(value.base);
}
};
@@ -44311,7 +44384,7 @@ export type AppStreamRow = {
*/
kind: AppStreamRowKind,
/**
- * The one line ("Desktop (1280×800)", a window's title).
+ * The one line ("Desktop", a window's title).
*/
label: string,
/**
@@ -69633,6 +69706,9 @@ const FfiConverterOptionalTypeAppGuestUsage = new FfiConverterOptional(FfiConver
// FfiConverter for AppDiskOnHost | undefined
const FfiConverterOptionalTypeAppDiskOnHost = new FfiConverterOptional(FfiConverterTypeAppDiskOnHost);
+// FfiConverter for AppSharedBase | undefined
+const FfiConverterOptionalTypeAppSharedBase = new FfiConverterOptional(FfiConverterTypeAppSharedBase);
+
// FfiConverter for Array<AppSpaceResources>
const FfiConverterSequenceTypeAppSpaceResources = new FfiConverterArray(FfiConverterTypeAppSpaceResources);
@@ -71601,6 +71677,7 @@ export default Object.freeze({
FfiConverterTypeAppShareSheetAction,
FfiConverterTypeAppShareSheetState,
FfiConverterTypeAppShareSheetView,
+ FfiConverterTypeAppSharedBase,
FfiConverterTypeAppSidebarRow,
FfiConverterTypeAppSidebarSection,
FfiConverterTypeAppSidebarView,
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swift
index f83c80d675..373a0ad7e3 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostResources.swift
@@ -38,7 +38,9 @@ func resourcesJSON(_ s: CuaSDK.ResourcesSnapshot) -> [String: Any] {
usage = [
"cpuCount": u.cpuCount, "cpuPercent": u.cpuPercent, "loadAverage1m": u.loadAverage1m,
"memoryUsed": u.memoryUsed, "memoryTotal": u.memoryTotal, "memoryLimited": u.memoryLimited,
- "diskUsed": u.diskUsed, "diskTotal": u.diskTotal, "diskLimited": u.diskLimited,
+ // No size of its own is null, never a sentinel.
+ "diskUsed": u.diskUsed, "diskTotal": u.diskTotal.map { $0 as Any } ?? NSNull(),
+ "diskLimited": u.diskLimited,
] as [String: Any]
}
var disk: Any = NSNull()
@@ -46,10 +48,15 @@ func resourcesJSON(_ s: CuaSDK.ResourcesSnapshot) -> [String: Any] {
disk = ["bytes": d.bytes.map { $0 as Any } ?? NSNull(), "allocated": d.allocated,
"sharesSpace": d.sharesSpace] as [String: Any]
}
+ var base: Any = NSNull()
+ if let b = r.base {
+ base = ["key": b.key, "image": b.image, "bytes": b.bytes.map { $0 as Any } ?? NSNull(),
+ "sharedWith": b.sharedWith] as [String: Any]
+ }
return [
"id": r.id, "powerState": r.powerState, "cpuAllocated": r.cpuAllocated,
"memoryAllocated": r.memoryAllocated, "diskAllocated": r.diskAllocated,
- "usage": usage, "diskOnHost": disk,
+ "usage": usage, "diskOnHost": disk, "base": base,
]
}
return [
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swift
index 4baebd6527..db11531ebf 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostResourcesTests.swift
@@ -78,17 +78,26 @@ struct HostResourcesTests {
spaces: [
CuaSDK.SpaceResources(id: "local:design-review", powerState: "running", cpuAllocated: 4,
memoryAllocated: 8 * g, diskAllocated: 80 * g, usage: nil,
- diskOnHost: CuaSDK.DiskOnHost(bytes: 19 * g, allocated: 34 * g, sharesSpace: true)),
+ diskOnHost: CuaSDK.DiskOnHost(bytes: 19 * g, allocated: 34 * g, sharesSpace: true),
+ base: CuaSDK.SharedBase(key: "sha256:m", image: "ghcr.io/trycua/macos:26",
+ bytes: 25 * g, sharedWith: 2)),
// One of yours on the Mac mini: only its size there.
CuaSDK.SpaceResources(id: "relay:space-qa-1234", powerState: "stopped", cpuAllocated: 0,
memoryAllocated: 0, diskAllocated: 0, usage: nil,
- diskOnHost: CuaSDK.DiskOnHost(bytes: 21 * g, allocated: 21 * g, sharesSpace: false)),
+ diskOnHost: CuaSDK.DiskOnHost(bytes: 21 * g, allocated: 21 * g, sharesSpace: false),
+ base: nil),
// Only an upper bound, and a container with no disk at all.
CuaSDK.SpaceResources(id: "local:clone", powerState: "stopped", cpuAllocated: 2, memoryAllocated: 0,
diskAllocated: 0, usage: nil,
- diskOnHost: CuaSDK.DiskOnHost(bytes: nil, allocated: 30 * g, sharesSpace: true)),
+ diskOnHost: CuaSDK.DiskOnHost(bytes: nil, allocated: 30 * g, sharesSpace: true),
+ base: nil),
+ // A gVisor container: its guest's root has no size of its own.
CuaSDK.SpaceResources(id: "local:box", powerState: "running", cpuAllocated: 2, memoryAllocated: 0,
- diskAllocated: 0, usage: nil, diskOnHost: nil),
+ diskAllocated: 0,
+ usage: CuaSDK.GuestUsage(cpuCount: 2, cpuPercent: 13, loadAverage1m: 0,
+ memoryUsed: 1 * g, memoryTotal: 4 * g, memoryLimited: true,
+ diskUsed: 249_856, diskTotal: nil, diskLimited: false),
+ diskOnHost: nil, base: nil),
],
computers: [computer("mac-mini", "Mac mini")], warning: warning)
let json = resourcesJSON(snapshot)
@@ -108,9 +117,15 @@ struct HostResourcesTests {
#expect((spaces[2]["diskOnHost"] as? [String: Any])?["bytes"] is NSNull)
#expect((spaces[2]["diskOnHost"] as? [String: Any])?["sharesSpace"] as? Bool == true)
#expect(spaces[3]["diskOnHost"] is NSNull)
+ // No size of its own is null, never a sentinel number.
+ #expect((spaces[3]["usage"] as? [String: Any])?["diskTotal"] is NSNull)
+ let base = try #require(spaces[0]["base"] as? [String: Any])
+ #expect(base["image"] as? String == "ghcr.io/trycua/macos:26")
+ #expect(base["sharedWith"] as? Int == 2)
+ #expect(spaces[1]["base"] is NSNull)
#expect((back["computers"] as? [[String: Any]])?.map { $0["id"] as? String } == ["mac-mini"])
// Every field the page's contract names, no more.
- #expect(Set(spaces[0].keys) == ["id", "powerState", "cpuAllocated", "memoryAllocated", "diskAllocated", "usage", "diskOnHost"])
+ #expect(Set(spaces[0].keys) == ["id", "powerState", "cpuAllocated", "memoryAllocated", "diskAllocated", "usage", "diskOnHost", "base"])
#expect(Set(thisMac.keys) == Set((HostResourceSampler().sample().snapshot()["thisMac"] as? [String: Any] ?? [:]).keys))
}
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/StreamRowsTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/StreamRowsTests.swift
index cf6c2625e4..0ae6e901f5 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/StreamRowsTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/StreamRowsTests.swift
@@ -105,7 +105,7 @@ struct StreamRowsTests {
let m = StreamFixture.model()
await m.refresh()
let s = m.section()
- #expect(s.rows.map(\.label) == ["Desktop (1280\u{d7}800)", "Mozilla Firefox", "Release notes", "xterm",
+ #expect(s.rows.map(\.label) == ["Desktop", "Mozilla Firefox", "Release notes", "xterm",
StreamFixture.longTitle])
#expect(s.rows[0].resolution == "1280\u{d7}800")
#expect(s.rows[0].icon == .os(id: "os-ubuntu"))
diff --git a/apps/cua-spaces-web/src/__tests__/resources.test.tsx b/apps/cua-spaces-web/src/__tests__/resources.test.tsx
index 0c6c2ab8c1..376ea43105 100644
--- a/apps/cua-spaces-web/src/__tests__/resources.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/resources.test.tsx
@@ -137,15 +137,37 @@ describe.skipIf(!wasmBuilt)("resources on Home and a Space's page", () => {
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).");
+ // Its own data on this Mac, of the size it was given.
+ expect(card("Space for files")).toBe("Space for files19 of 80 GB");
+ // Title, number, the one "Given" line and the bar: no explanations, no footer.
+ expect(panel.textContent).not.toMatch(/Busy means|free for its apps|Uses about|Updates every|file names/);
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="yours"]')?.textContent).toBe("Your own files and apps · 929 GB");
+ expect(fit.querySelector('[data-disk-part="space"]')?.textContent).toMatch(/ · 19 GB$/);
+ expect(fit.querySelector('[data-disk-part="others"]')?.textContent).toBe("Other Spaces · 6 GB");
+ // Each shared base once, with who shares it.
+ const bases = Array.from(fit.querySelectorAll('[data-disk-part="base"]')).map((b) => b.textContent);
+ expect(bases).toHaveLength(2);
+ expect(bases[0]).toMatch(/ image · 25 GB, only this Space uses it$/);
+ expect(bases[1]).toBe("linux 24.04 image · 4.1 GB, used by 1 Space");
expect(fit.querySelector('[data-disk-part="free"]')?.textContent).toBe("Free · 41 GB");
expect(fit.querySelector("[data-low-disk]")).not.toBeNull();
});
+ it("a container's page: its own data with no fake total", async () => {
+ await mountApp(`/spaces/${encodeURIComponent("local:agent-sandbox")}`, { failsCreates: false, listsGhost: false, answer: lowDisk, noThread: true });
+ const panel = await waitFor(() => {
+ const el = document.querySelector<HTMLElement>("[data-space-resources]");
+ if (!el) throw new Error("no panel");
+ return el;
+ });
+ const files = panel.querySelector('[data-resource-card="Space for files"]')!;
+ expect(files.textContent).toBe("Space for files6 GB");
+ expect(files.querySelector("[data-bar-fill]")).toBeNull();
+ expect(panel.querySelector('[data-resource-card="Memory"]')?.textContent).toContain("Given 4 GB of this Mac’s 64 GB");
+ });
+
it("another computer's running Space has no panel with only its size there", async () => {
await mountApp(`/spaces/${encodeURIComponent("relay:mac-mini/qa-windows")}`, { failsCreates: false, listsGhost: false, noThread: true });
await waitFor(() => expect(document.querySelector("[data-detail-title]")).not.toBeNull());
diff --git a/apps/cua-spaces-web/src/__tests__/spaces-page-rules.test.tsx b/apps/cua-spaces-web/src/__tests__/spaces-page-rules.test.tsx
index 8795d15455..b45cec637c 100644
--- a/apps/cua-spaces-web/src/__tests__/spaces-page-rules.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/spaces-page-rules.test.tsx
@@ -15,7 +15,7 @@ import { computerChoices, gridArea, lastUsedText, namesText, nextSearch, shownSp
afterEach(cleanup);
-const GB = 1_000_000_000;
+const GB = 1024 ** 3;
const NOW = 1_800_000_000_000;
const MIN = 60_000;
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/space-disk.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/space-disk.test.ts
index f4ffad6f22..645d2156f2 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/space-disk.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/space-disk.test.ts
@@ -9,7 +9,7 @@ import { spaceDiskBytes, type ResourcesSnapshot } from "@/bridge";
import { demoResources } from "@/bridge/adapters/demo/resources";
import { demoSpaceRows } from "@/bridge/adapters/demo-data";
-const GB = 1_000_000_000;
+const GB = 1024 ** 3;
describe("spaceDiskBytes", () => {
const snap = demoResources(demoSpaceRows(0), 0);
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/resources.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/resources.ts
index 43b5429615..67b8127a1c 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/resources.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/resources.ts
@@ -16,7 +16,8 @@ import type { ComputerResources, DiskWarning, ResourcesSnapshot, SpaceResources
import type { DemoContext, DemoHandlers } from "./context";
import { DEMO_MACHINES } from "../demo-data";
-const GB = 1_000_000_000;
+/** GiB, labelled "GB" the way macOS labels memory (the core's convention). */
+const GB = 1024 ** 3;
const GIB = 1024 ** 3;
export interface DemoResourcesState {
@@ -45,7 +46,14 @@ const running = (row: SpaceRow) => row.powerState === "running" || (row.powerSta
/** 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 },
+ // A container: no disk size of its own (gVisor's root overlay).
+ "local:agent-sandbox": { cores: 2, memory: 4, disk: 0, onHost: 6, inside: 6, shared: false },
+};
+
+/** The base image each demo Space is a copy-on-write copy of. */
+const BASES: Record<string, NonNullable<SpaceResources["base"]>> = {
+ "local:design-review": { key: "demo-macos-26", image: "ghcr.io/trycua/macos:26", bytes: 25 * GB, sharedWith: 1 },
+ "local:agent-sandbox": { key: "demo-linux-24.04", image: "ghcr.io/trycua/linux:24.04", bytes: 4.1 * GB, sharedWith: 1 },
};
function spaceResources(row: SpaceRow, now: number, index: number): SpaceResources {
@@ -67,11 +75,12 @@ function spaceResources(row: SpaceRow, now: number, index: number): SpaceResourc
memoryTotal: a.memory * GB,
memoryLimited: true,
diskUsed: a.inside * GB,
- diskTotal: a.disk * GB,
- diskLimited: true,
+ diskTotal: a.disk ? a.disk * GB : null,
+ diskLimited: a.disk > 0,
}
: null,
diskOnHost: { bytes: a.onHost * GB, allocated: (a.shared ? a.inside : a.onHost) * GB, sharesSpace: a.shared },
+ base: BASES[row.id] ?? null,
};
}
@@ -119,7 +128,7 @@ export function demoResources(rows: readonly SpaceRow[], now: number, diskFree:
loadAverage1m: (cpuPercent / 100) * 12,
memoryTotal: 64 * GB,
memoryUsed: Math.round(drift(now, 41, 1.5) * GB),
- diskTotal: 1000 * GB,
+ diskTotal: 1024 * GB,
diskFree,
spacesCount: spaces.length,
spacesRunning: on.length,
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index bca9856fc6..12be79debc 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -4515,7 +4515,10 @@
"type": "number"
},
"diskTotal": {
- "type": "number"
+ "type": [
+ "number",
+ "null"
+ ]
},
"diskLimited": {
"type": "boolean"
@@ -4557,6 +4560,35 @@
"allocated",
"sharesSpace"
]
+ },
+ "base": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "key": {
+ "type": "string"
+ },
+ "image": {
+ "type": "string"
+ },
+ "bytes": {
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "sharedWith": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "key",
+ "image",
+ "bytes",
+ "sharedWith"
+ ]
}
},
"required": [
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 8a91277a7f..8611318446 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -64,7 +64,7 @@ import type { TelemetryLinkNotice } from "../ops/telemetry";
import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";
import type { RelayUsage } from "../ops/relay-usage";
import type { RiskyRequest } from "../ops/nudges";
-import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SpaceResources } from "../ops/resources";
+import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SharedBase, SpaceResources } from "../ops/resources";
import type { HostChecklistState } from "../ops/checklist";
import type { TipsState } from "./spaces-page";
import type { ShareLink } from "../ops/links";
@@ -1326,11 +1326,12 @@ export const OP_SHAPES: Record<OpName, Schema> = {
memoryTotal: num,
memoryLimited: bool,
diskUsed: num,
- diskTotal: num,
+ diskTotal: nullable(num),
diskLimited: bool,
}),
),
diskOnHost: nullable(obj<DiskOnHost>()({ bytes: nullable(num), allocated: num, sharesSpace: bool })),
+ base: opt(nullable(obj<SharedBase>()({ key: str, image: str, bytes: nullable(num), sharedWith: num }))),
}),
),
),
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 9995f81bbe..d55cd94492 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -198,6 +198,7 @@ export {
type DiskWarning,
type GuestUsage,
type ResourcesSnapshot,
+ type SharedBase,
type SpaceResources,
} from "./resources";
export {
diff --git a/apps/cua-spaces-web/src/bridge/ops/resources.ts b/apps/cua-spaces-web/src/bridge/ops/resources.ts
index 6df33bdbce..14de760e16 100644
--- a/apps/cua-spaces-web/src/bridge/ops/resources.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/resources.ts
@@ -77,7 +77,9 @@ export interface GuestUsage {
memoryTotal: number;
memoryLimited: boolean;
diskUsed: number;
- diskTotal: number;
+ /** Null: the guest's file system has no size of its own (gVisor's root
+ * overlay) or didn't say. Never a sentinel such as 2^63. */
+ diskTotal: number | null;
diskLimited: boolean;
}
@@ -104,8 +106,22 @@ export interface SpaceResources {
diskAllocated: number;
/** Null while stopped or unreachable. */
usage: GuestUsage | null;
- /** Null: nothing to say (a container). */
+ /** Its own data on this Mac (never the base it shares); null: nothing to measure. */
diskOnHost: DiskOnHost | null;
+ /** The base image it is a copy-on-write copy of, counted once; absent from older hosts. */
+ base?: SharedBase | null;
+}
+
+/** A base image several Spaces share copy-on-write (`SharedBase`). */
+export interface SharedBase {
+ /** Spaces with the same key share the same blocks. */
+ key: string;
+ /** `ghcr.io/trycua/linux:24.04`. */
+ image: string;
+ /** What it takes, once; null: the runtime can't tell it apart. */
+ bytes: number | null;
+ /** Local Spaces that use it, this one included. */
+ sharedWith: number;
}
/** `cua_spaces::resources::ResourcesSnapshot` (the SDK's `Spaces.resources(visible)`). */
diff --git a/apps/cua-spaces-web/src/bridge/resources.ts b/apps/cua-spaces-web/src/bridge/resources.ts
index 13595eceac..89995c1268 100644
--- a/apps/cua-spaces-web/src/bridge/resources.ts
+++ b/apps/cua-spaces-web/src/bridge/resources.ts
@@ -15,7 +15,7 @@ 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 type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SharedBase, SpaceResources } from "./ops/resources";
export const RESOURCES_VISIBLE_MS = 10_000;
export const RESOURCES_HIDDEN_MS = 5 * 60_000;
diff --git a/apps/cua-spaces-web/src/bridge/space-detail.ts b/apps/cua-spaces-web/src/bridge/space-detail.ts
index d1ce26bf24..9eca419466 100644
--- a/apps/cua-spaces-web/src/bridge/space-detail.ts
+++ b/apps/cua-spaces-web/src/bridge/space-detail.ts
@@ -139,13 +139,15 @@ function fallbackSection(input: StreamSectionInput): StreamSection {
const on = (input.open ?? []).includes(id);
return [{ id: "pip" as const, symbol: on ? "pip.exit" : "pip.enter", help: on ? "Close picture in picture" : "Picture in picture", active: on }];
};
- const desktop = res ? `Desktop (${res})` : "Desktop";
+ // The resolution shows once, as the row's detail; the tooltip has both.
+ const desktop = "Desktop";
+ const desktopHelp = res ? `Desktop (${res})` : "Desktop";
const windows = (input.windows ?? []).map((w) => {
const label = w.title.trim() || w.appName.trim() || w.appId;
return { id: w.id, kind: "window" as const, label, help: label, icon: { kind: "app" as const, appName: w.appName, appId: w.appId, pid: w.pid ?? 0 }, actions: pip(w.id) };
});
return {
- rows: [{ id: "desktop", kind: "desktop", label: desktop, help: desktop, resolution: res, icon: { kind: "os", id: `os-${input.os}` }, actions: pip("desktop") }, ...windows],
+ rows: [{ id: "desktop", kind: "desktop", label: desktop, help: desktopHelp, resolution: res, icon: { kind: "os", id: `os-${input.os}` }, actions: pip("desktop") }, ...windows],
statusText: input.windows === null ? "Looking for this Space’s windows…" : windows.length ? null : input.failed ? "No windows: the Space’s window host is not up." : "No open windows in this Space yet.",
};
}
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.tsx
index 54c1118c1c..72a14deb27 100644
--- a/apps/cua-spaces-web/src/components/resources/space-resources-panel.tsx
+++ b/apps/cua-spaces-web/src/components/resources/space-resources-panel.tsx
@@ -1,23 +1,25 @@
// 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 { useBridge, type ComputerResources, type SpaceResources } from "@/bridge";
+import { lowDiskWarning, spacePanel, type DiskFitView, type SpacePanelInput, type SpacePanelView } 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".
+ * A Space's numbers on its page: Processor, Memory and Space for files,
+ * each a title, the main number, the one "Given ..." line and a bar, then
+ * "How it fits on this Mac". The words are the core's
+ * (`resources.spacePanel`); a TypeScript stand-in answers only without it.
*/
export function SpaceResourcesPanel({
space,
name,
host,
computer,
- siblings,
+ spaces,
+ baseName,
}: {
space: SpaceResources;
/** The Space's name ("macOS 1"). */
@@ -26,89 +28,67 @@ export function SpaceResourcesPanel({
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 }[];
+ /** Every Space on that computer, for how it fits. */
+ spaces: SpaceResources[];
+ /** Its base image's system ("Ubuntu 24.04"), when known. */
+ baseName: string | null;
}) {
- 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),
- },
- ];
+ const { core } = useBridge();
+ const input: SpacePanelInput = { space, name, host, computer, spaces, baseName };
+ const view = core.tryCall<SpacePanelView>("resources.spacePanel", { input }) ?? spacePanel(input);
return (
<section data-space-resources="" aria-label="Resources" className="mt-6">
<div className="grid gap-4 md:grid-cols-3">
- {cards.map((c) => (
+ {view.cards.map((c) => (
<div key={c.label} data-resource-card={c.label} className="rounded-lg bg-muted/60 p-4">
<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>
+ <p className="mt-1.5 text-xl leading-tight font-semibold tracking-[-0.01em] tabular-nums">{c.value}</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}
+ {c.fraction != null ? <Bar fill={c.fraction} className="mt-3.5" /> : 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>
+ {host && view.fit ? <DiskFit fit={view.fit} host={host} computer={computer} /> : null}
</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 SWATCH: Record<string, string> = {
+ yours: "bg-muted-foreground/60",
+ thisSpace: "bg-brand-strong",
+ otherSpaces: "bg-brand/45",
+ base: "bg-success/60",
+ free: "border bg-foreground/10",
+};
+
+/** "How it fits on this Mac": your own files, this Space, other Spaces, each shared base once, free. */
+function DiskFit({ fit, host, computer }: { fit: DiskFitView; host: ComputerResources; computer: string }) {
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" })),
- ];
+ const bar = fit.parts.filter((p) => p.kind !== "free");
return (
<div data-disk-fit="" className="mt-4 rounded-lg bg-muted/60 p-4">
<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>
+ <span className="text-xs text-muted-foreground tabular-nums">{fit.total}</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 className="mt-3 flex h-2 overflow-hidden rounded-full bg-foreground/10" role="img" aria-label={fit.parts.map((p) => `${p.label} ${p.value}`).join(", ")}>
+ {bar.map((p) => (
+ <div key={p.key} className={cn("h-full", SWATCH[p.kind])} style={{ width: `${p.fraction * 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 /* design-ok: legend swatch, a 2 px square */ className={cn("size-2 rounded-xs", s.className)} aria-hidden />
- {s.label} · {size(s.bytes)}
+ {fit.parts.map((p) => (
+ <li key={p.key} data-disk-part={p.kind === "base" ? "base" : p.key} className="flex items-center gap-1.5 tabular-nums">
+ <span /* design-ok: legend swatch, a 2 px square */ className={cn("size-2 rounded-xs", SWATCH[p.kind])} aria-hidden />
+ {/* One inline run, so the flex gap only parts the swatch from the words. */}
+ <span>
+ {p.label} · {p.value}
+ {p.detail ? <span className="text-muted-foreground">, {p.detail}</span> : null}
+ </span>
</li>
))}
- <li data-disk-part="free" className="flex items-center gap-1.5">
- <span /* design-ok: legend swatch, a 2 px square */ className="size-2 rounded-xs border bg-foreground/10" aria-hidden />
- Free · {size(parts.free)}
- </li>
</ul>
+ {fit.note ? <p data-disk-fit-note="" className="mt-3 text-xs text-muted-foreground">{fit.note}</p> : null}
{warning ? <LowDiskWarning warning={warning} compact className="mt-4 rounded-lg" /> : null}
</div>
);
diff --git a/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsx b/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsx
index e9fcb343d9..ae19945296 100644
--- a/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsx
+++ b/apps/cua-spaces-web/src/legacy/__tests__/resources.test.tsx
@@ -138,15 +138,37 @@ describe.skipIf(!wasmBuilt)("resources on Home and a Space's page", () => {
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).");
+ // Its own data on this Mac, of the size it was given.
+ expect(card("Space for files")).toBe("Space for files19 of 80 GB");
+ // Title, number, the one "Given" line and the bar: no explanations, no footer.
+ expect(panel.textContent).not.toMatch(/Busy means|free for its apps|Uses about|Updates every|file names/);
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="yours"]')?.textContent).toBe("Your own files and apps · 929 GB");
+ expect(fit.querySelector('[data-disk-part="space"]')?.textContent).toMatch(/ · 19 GB$/);
+ expect(fit.querySelector('[data-disk-part="others"]')?.textContent).toBe("Other Spaces · 6 GB");
+ // Each shared base once, with who shares it.
+ const bases = Array.from(fit.querySelectorAll('[data-disk-part="base"]')).map((b) => b.textContent);
+ expect(bases).toHaveLength(2);
+ expect(bases[0]).toMatch(/ image · 25 GB, only this Space uses it$/);
+ expect(bases[1]).toBe("linux 24.04 image · 4.1 GB, used by 1 Space");
expect(fit.querySelector('[data-disk-part="free"]')?.textContent).toBe("Free · 41 GB");
expect(fit.querySelector("[data-low-disk]")).not.toBeNull();
});
+ it("a container's page: its own data with no fake total", async () => {
+ await mountApp(`/spaces/${encodeURIComponent("local:agent-sandbox")}`, { 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 files = panel.querySelector('[data-resource-card="Space for files"]')!;
+ expect(files.textContent).toBe("Space for files6 GB");
+ expect(files.querySelector("[data-bar-fill]")).toBeNull();
+ expect(panel.querySelector('[data-resource-card="Memory"]')?.textContent).toContain("Given 4 GB of this Mac’s 64 GB");
+ });
+
it("another computer's Space shows its panel once that computer reports 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());
diff --git a/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsx b/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsx
index 111bfa1e60..20d0bb0545 100644
--- a/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsx
+++ b/apps/cua-spaces-web/src/legacy/components/resources/space-resources-panel.tsx
@@ -1,23 +1,25 @@
// 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 { useBridge, type ComputerResources, type SpaceResources } from "@/bridge";
+import { lowDiskWarning, spacePanel, type DiskFitView, type SpacePanelInput, type SpacePanelView } from "@/lib/resources";
import { cn } from "@/lib/utils";
import { Bar, LowDiskWarning } from "@/legacy/components/resources/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".
+ * A Space's numbers on its page: Processor, Memory and Space for files,
+ * each a title, the main number, the one "Given ..." line and a bar, then
+ * "How it fits on this Mac". The words are the core's
+ * (`resources.spacePanel`); a TypeScript stand-in answers only without it.
*/
export function SpaceResourcesPanel({
space,
name,
host,
computer,
- siblings,
+ spaces,
+ baseName,
}: {
space: SpaceResources;
/** The Space's name ("macOS 1"). */
@@ -26,89 +28,67 @@ export function SpaceResourcesPanel({
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 }[];
+ /** Every Space on that computer, for how it fits. */
+ spaces: SpaceResources[];
+ /** Its base image's system ("Ubuntu 24.04"), when known. */
+ baseName: string | null;
}) {
- 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),
- },
- ];
+ const { core } = useBridge();
+ const input: SpacePanelInput = { space, name, host, computer, spaces, baseName };
+ const view = core.tryCall<SpacePanelView>("resources.spacePanel", { input }) ?? spacePanel(input);
return (
<section data-space-resources="" aria-label="Resources" className="mt-6">
<div className="grid gap-4 md:grid-cols-3">
- {cards.map((c) => (
+ {view.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>
+ <p className="mt-1.5 text-xl leading-tight font-semibold tracking-[-0.01em] tabular-nums">{c.value}</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}
+ {c.fraction != null ? <Bar fill={c.fraction} className="mt-3.5" /> : 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>
+ {host && view.fit ? <DiskFit fit={view.fit} host={host} computer={computer} /> : null}
</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 SWATCH: Record<string, string> = {
+ yours: "bg-muted-foreground/60",
+ thisSpace: "bg-brand-strong",
+ otherSpaces: "bg-brand/45",
+ base: "bg-success/60",
+ free: "border bg-foreground/10",
+};
+
+/** "How it fits on this Mac": your own files, this Space, other Spaces, each shared base once, free. */
+function DiskFit({ fit, host, computer }: { fit: DiskFitView; host: ComputerResources; computer: string }) {
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" })),
- ];
+ const bar = fit.parts.filter((p) => p.kind !== "free");
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>
+ <span className="text-xs text-muted-foreground tabular-nums">{fit.total}</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 className="mt-3 flex h-2 overflow-hidden rounded-full bg-foreground/10" role="img" aria-label={fit.parts.map((p) => `${p.label} ${p.value}`).join(", ")}>
+ {bar.map((p) => (
+ <div key={p.key} className={cn("h-full", SWATCH[p.kind])} style={{ width: `${p.fraction * 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)}
+ {fit.parts.map((p) => (
+ <li key={p.key} data-disk-part={p.kind === "base" ? "base" : p.key} className="flex items-center gap-1.5 tabular-nums">
+ <span className={cn("size-2 rounded-xs", SWATCH[p.kind])} aria-hidden />
+ {/* One inline run, so the flex gap only parts the swatch from the words. */}
+ <span>
+ {p.label} · {p.value}
+ {p.detail ? <span className="text-muted-foreground">, {p.detail}</span> : null}
+ </span>
</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>
+ {fit.note ? <p data-disk-fit-note="" className="mt-3 text-xs text-muted-foreground">{fit.note}</p> : null}
{warning ? <LowDiskWarning warning={warning} compact className="mt-4 rounded-lg border" /> : null}
</div>
);
diff --git a/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsx
index 1976dee0a9..96dcfb9b0a 100644
--- a/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsx
+++ b/apps/cua-spaces-web/src/legacy/routes/spaces/$spaceId.tsx
@@ -13,6 +13,7 @@ import { AgentsSection } from "@/components/space-detail/agents-section";
import { DropWell } from "@/components/space-detail/drop-well";
import { FactList } from "@/legacy/components/space-detail/facts";
import { SpaceResourcesPanel } from "@/legacy/components/resources/space-resources-panel";
+import { systemName } from "@/lib/resources";
import { StreamSection } from "@/components/space-detail/stream-section";
import { StreamSurface } from "@/legacy/components/space-detail/stream-surface";
import { StateLabel } from "@/components/state-dot";
@@ -534,11 +535,20 @@ function SpaceResources({ space, spaces, snapshot, machines }: { space: Space; s
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.
+ // The Spaces on the same computer, with the numbers it sent, for how it fits.
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 }] : [];
+ const onComputer = spaces.flatMap((s) => {
+ const r = sameComputer(s) ? spaceResources(snapshot, s.id) : null;
+ return r ? [r] : [];
});
- return <SpaceResourcesPanel space={mine} name={space.name} host={host} computer={computer} siblings={siblings} />;
+ return (
+ <SpaceResourcesPanel
+ space={mine}
+ name={space.name}
+ host={host}
+ computer={computer}
+ spaces={onComputer}
+ baseName={systemName(space.osPrettyName)}
+ />
+ );
}
diff --git a/apps/cua-spaces-web/src/lib/resources.test.ts b/apps/cua-spaces-web/src/lib/resources.test.ts
index 1ccd016efb..758612ea92 100644
--- a/apps/cua-spaces-web/src/lib/resources.test.ts
+++ b/apps/cua-spaces-web/src/lib/resources.test.ts
@@ -6,11 +6,13 @@ 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";
+import { diskFit, extraSpacesLine, hostMeters, knownSize, lowDiskWarning, onHostLine, size, sizeOf, spaceMeters, spacePanel, systemName, updatedAgo } from "./resources";
-const GB = 1_000_000_000;
+/** GiB: sizes read the way macOS shows memory ("4 GB of 36 GB"). */
+const GB = 1024 ** 3;
+const MB = 1024 ** 2;
-const host = (free: number, total = 1000 * GB): ComputerResources => ({
+const host = (free: number, total = 1024 * GB): ComputerResources => ({
id: "this-mac",
name: "",
online: true,
@@ -40,6 +42,7 @@ const space = (over: Partial<SpaceResources> = {}): SpaceResources => ({
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 },
+ base: null,
...over,
});
@@ -48,10 +51,29 @@ describe("sizes", () => {
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(size(1024 * GB)).toBe("1 TB");
+ expect(size(1536 * 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");
+ expect(sizeOf(800 * GB, 1024 * GB)).toBe("800 GB of 1 TB");
+ });
+
+ it("uses one convention, the way macOS shows memory: 4 GiB is 4 GB, never 4.3", () => {
+ expect(size(4 * GB)).toBe("4 GB");
+ expect(size(36 * GB)).toBe("36 GB");
+ // A 2 TB (decimal) disk, in the same binary units.
+ expect(size(2e12)).toBe("1.8 TB");
+ });
+
+ it("never says 0 GB for something", () => {
+ expect(size(500 * MB)).toBe("500 MB");
+ expect(size(249_856)).toBe("244 KB");
+ expect(size(0)).toBe("0 KB");
+ expect(sizeOf(717 * MB, 4 * GB)).toBe("717 MB of 4 GB");
+ });
+
+ it("a sentinel is no size", () => {
+ for (const v of [2 ** 63 - 1, 9223372036854771712, 2 ** 64 - 1, -1, 0, Number.NaN, null, undefined]) expect(knownSize(v)).toBeNull();
+ expect(knownSize(80 * GB)).toBe(80 * GB);
});
});
@@ -106,10 +128,10 @@ describe("meters", () => {
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("names a base by its system", () => {
+ expect(systemName("Ubuntu 24.04.5 LTS")).toBe("Ubuntu 24.04");
+ expect(systemName("macOS 26.5.2 (25F84)")).toBe("macOS 26.5");
+ expect(systemName(undefined)).toBeNull();
});
it("says how old another computer's summary is", () => {
@@ -148,3 +170,80 @@ describe("the demo host's numbers", () => {
expect(demoResources(rows, 0).spaces.some((s) => s.id === "relay:studio-pc/render")).toBe(false);
});
});
+
+/** The owner's Mac: 18 cores, 36 GiB of memory, a 2 TB disk nearly full. */
+const ownersMac = (): ComputerResources => ({
+ ...host(5.6e9, 2e12),
+ cpuCount: 18,
+ memoryTotal: 36 * GB,
+ warning: { level: "critical", free: 5.6e9, total: 2e12, threshold: 5 * GB },
+});
+
+/** pipbox: an Ubuntu container under gVisor, whose root has no size of its own. */
+const pipbox = (diskTotal: number | null): SpaceResources => ({
+ id: "local:pipbox",
+ powerState: "running",
+ cpuAllocated: 2,
+ memoryAllocated: 4 * GB,
+ diskAllocated: 0,
+ usage: { cpuCount: 2, cpuPercent: 13, loadAverage1m: 0, memoryUsed: 717 * MB, memoryTotal: 4 * GB, memoryLimited: true, diskUsed: 249_856, diskTotal, diskLimited: false },
+ diskOnHost: { bytes: 249_856, allocated: 249_856, sharesSpace: false },
+ base: { key: "sha256:9ac0", image: "ghcr.io/trycua/linux:24.04", bytes: 4.41e9, sharedWith: 1 },
+});
+
+describe("a Space's resources dialog (the core's stand-in)", () => {
+ const view = (s: SpaceResources, spaces = [s]) => spacePanel({ space: s, name: "pipbox", host: ownersMac(), computer: "this Mac", spaces, baseName: "Ubuntu 24.04" });
+
+ it("no sentinel ever reaches it: i64::MAX, u64::MAX, -1, 0", () => {
+ for (const sentinel of [2 ** 63 - 1, 9223372036854771712, 2 ** 64 - 1, -1, 0, null]) {
+ const v = view(pipbox(sentinel));
+ expect(v.cards.map((c) => [c.label, c.value, c.given])).toEqual([
+ ["Processor", "13% busy", "Given 2 of this Mac’s 18 cores"],
+ ["Memory", "717 MB of 4 GB", "Given 4 GB of this Mac’s 36 GB"],
+ ["Space for files", "244 KB", null],
+ ]);
+ expect(v.cards[2]!.fraction).toBeNull();
+ expect(JSON.stringify(v)).not.toMatch(/9223372|PB|Busy means|Uses about|Updates every/);
+ }
+ });
+
+ it("how it fits adds up, the base counted once", () => {
+ const fit = view(pipbox(null)).fit!;
+ expect(fit.total).toBe("1.8 TB");
+ expect(fit.parts.map((p) => `${p.label} · ${p.value}${p.detail ? `, ${p.detail}` : ""}`)).toEqual([
+ "Your own files and apps · 1.8 TB",
+ "pipbox · 244 KB",
+ "Ubuntu 24.04 image · 4.1 GB, only this Space uses it",
+ "Free · 5.2 GB",
+ ]);
+ expect(fit.parts.reduce((n, p) => n + p.bytes, 0)).toBe(2e12);
+ expect(fit.parts.reduce((n, p) => n + p.fraction, 0)).toBeCloseTo(1, 9);
+ expect(fit.warning?.critical).toBe(true);
+ });
+
+ it("copy-on-write: two Spaces on one image count it once and say so", () => {
+ const base = { key: "sha256:9ac0", image: "ghcr.io/trycua/linux:24.04", bytes: 4.41e9, sharedWith: 2 };
+ const me = { ...pipbox(null), base };
+ const twin: SpaceResources = { ...me, id: "local:twin", diskOnHost: { bytes: 2 * GB, allocated: 2 * GB, sharesSpace: false } };
+ const fit = diskFit(ownersMac(), me, "pipbox", [me, twin], "Ubuntu 24.04");
+ expect(fit.parts.filter((p) => p.kind === "base").map((p) => p.detail)).toEqual(["shared by 2 Spaces"]);
+ expect(fit.parts.find((p) => p.kind === "otherSpaces")?.value).toBe("2 GB");
+ expect(fit.parts.reduce((n, p) => n + p.bytes, 0)).toBe(2e12);
+ });
+
+ it("not copy-on-write: only its own data", () => {
+ const me = { ...space(), base: null };
+ const fit = diskFit(host(41 * GB), me, "macOS 1", [me], null);
+ expect(fit.parts.some((p) => p.kind === "base")).toBe(false);
+ expect(fit.parts.find((p) => p.kind === "thisSpace")?.value).toBe("19 GB");
+ });
+
+ it("what can't be told apart is said plainly, never guessed", () => {
+ const me = space({ diskOnHost: { bytes: null, allocated: 40 * GB, sharesSpace: true }, base: { key: "m", image: "ghcr.io/trycua/macos:26", bytes: null, sharedWith: 1 } });
+ const fit = diskFit(host(41 * GB), me, "macOS 1", [me], null);
+ expect(fit.note).toBe("Can’t tell macOS 1’s own data apart from the image it shares.");
+ expect(fit.parts.some((p) => p.kind === "thisSpace" || p.kind === "base")).toBe(false);
+ const files = spacePanel({ space: me, name: "macOS 1", host: null, computer: "this Mac", spaces: [me], baseName: null }).cards[2]!;
+ expect(files.value).toBe("Up to 80 GB");
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/resources.ts b/apps/cua-spaces-web/src/lib/resources.ts
index 60494a15dd..8d35b80be3 100644
--- a/apps/cua-spaces-web/src/lib/resources.ts
+++ b/apps/cua-spaces-web/src/lib/resources.ts
@@ -7,32 +7,42 @@
* "busy", "in use", "free". Never vCPU, RSS, APFS, sparse or cgroup.
*/
-import type { ComputerResources, SpaceResources } from "@/bridge";
+import type { ComputerResources, SharedBase, SpaceResources } from "@/bridge";
export const LABELS = { cpu: "Processor", memory: "Memory", disk: "Space for files" } as const;
-const GB = 1_000_000_000;
+const MIB = 1024 * 1024;
+/** Sizes at or above this are "unlimited" or "unknown" sentinels, never sizes (2^60). */
+export const SIZE_SENTINEL_FLOOR = 2 ** 60;
-/** 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);
+/** A size, or null when it is 0, negative, not a number or a sentinel. */
+export function knownSize(bytes: number | null | undefined): number | null {
+ return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 && bytes < SIZE_SENTINEL_FLOOR ? bytes : null;
}
-/** "41 GB", "3.1 GB", "1 TB", "1.5 TB". */
+/**
+ * A size in binary units labelled the way macOS labels memory: "512 MB",
+ * "2.1 GB", "4 GB", "1.8 TB"; under 1 MB, "244 KB" (never "0 GB" for
+ * something). The app core's `format_size`, the same everywhere.
+ */
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`;
+ const units = ["MB", "GB", "TB", "PB"];
+ let v = bytes / MIB;
+ if (v < 1) return `${Math.round(bytes / 1024)} KB`;
+ let i = 0;
+ while (v >= 1024 && i < units.length - 1) {
+ v /= 1024;
+ i += 1;
}
- return `${gbNumber(bytes)} GB`;
+ const text = v >= 100 ? String(Math.round(v)) : (Math.round(v * 10) / 10).toFixed(1).replace(/\.0$/, "");
+ return `${text} ${units[i]}`;
}
-/** "3.1 of 8 GB" (same unit) or "800 GB of 1 TB". */
+/** "3.1 of 8 GB" (same unit) or "717 MB of 4 GB": the core's `of_text`. */
export function sizeOf(used: number, total: number): string {
const whole = size(total);
const unit = whole.split(" ")[1];
- const part = size(used);
+ const part = size(Math.min(used, total));
return part.endsWith(` ${unit}`) ? `${part.split(" ")[0]} of ${whole}` : `${part} of ${whole}`;
}
@@ -134,9 +144,162 @@ export function lowDiskWarning(c: ComputerResources, computer: string): { level:
: { 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 };
+/* ---- A Space's resources dialog (the core's `resources.spacePanel`) ---------------- */
+
+export interface SpacePanelCard {
+ label: string;
+ /** The main number: "13% busy", "717 MB of 4 GB", "244 KB". */
+ value: string;
+ /** "Given 2 of this Mac’s 18 cores". */
+ given: string | null;
+ /** The bar, 0 to 1; null: nothing to fill it against. */
+ fraction: number | null;
+}
+
+export type DiskFitKind = "yours" | "thisSpace" | "otherSpaces" | "base" | "free";
+
+export interface DiskFitPart {
+ key: string;
+ kind: DiskFitKind;
+ label: string;
+ value: string;
+ /** For a base: "shared by 3 Spaces", "only this Space uses it". */
+ detail: string | null;
+ bytes: number;
+ /** Its share of the bar; the parts add up to 1. */
+ fraction: number;
+}
+
+export interface DiskFitView {
+ total: string;
+ parts: DiskFitPart[];
+ /** What could not be told apart, in plain words. */
+ note: string | null;
+ warning: { text: string; button: string; critical: boolean } | null;
+}
+
+export interface SpacePanelView {
+ cards: SpacePanelCard[];
+ fit: DiskFitView | null;
+}
+
+export interface SpacePanelInput {
+ space: SpaceResources;
+ name: string;
+ host: ComputerResources | null;
+ /** "this Mac", or the other computer's name. */
+ computer: string;
+ /** Every Space on that computer. */
+ spaces: SpaceResources[];
+ /** Its base image's system ("Ubuntu 24.04"), when known. */
+ baseName: string | null;
+}
+
+/** "Ubuntu 24.04.5 LTS" is "Ubuntu 24.04"; "macOS 26.5.2 (25F84)" is "macOS 26.5". */
+export function systemName(pretty: string | null | undefined): string | null {
+ const m = pretty?.trim().match(/^(.*?\d+(?:\.\d+)?)/);
+ return m?.[1] ?? null;
+}
+
+/** `ghcr.io/trycua/linux:24.04` is "linux 24.04". */
+export function imageName(reference: string): string {
+ const r = reference.split("@")[0] ?? reference;
+ return r.slice(r.lastIndexOf("/") + 1).replace(":", " ");
+}
+
+const ownBytes = (s: SpaceResources): number | null => s.diskOnHost?.bytes ?? null;
+
+/** "How it fits on this Mac": each piece once (a shared base too), adding up to the volume. */
+export function diskFit(host: ComputerResources, me: SpaceResources, name: string, spaces: SpaceResources[], baseName: string | null): DiskFitView {
+ const total = host.diskTotal;
+ const free = Math.min(host.diskFree, total);
+ const used = total - free;
+ const mine = ownBytes(me);
+ const others = spaces.filter((s) => s.id !== me.id).reduce((n, s) => n + (ownBytes(s) ?? 0), 0);
+ const bases: SharedBase[] = [];
+ for (const s of [me, ...spaces.filter((o) => o.id !== me.id)]) {
+ if (s.base && !bases.some((b) => b.key === s.base!.key)) bases.push(s.base);
+ }
+ const knownBases = bases.reduce((n, b) => n + (b.bytes ?? 0), 0);
+ const counted = (mine ?? 0) + others + knownBases;
+ const yours = Math.max(0, used - counted);
+ const whole = Math.max(total, counted + yours + free, 1);
+ const part = (key: string, kind: DiskFitKind, label: string, detail: string | null, bytes: number): DiskFitPart => ({
+ key,
+ kind,
+ label,
+ value: size(bytes),
+ detail,
+ bytes,
+ fraction: bytes / whole,
+ });
+ const parts = [part("yours", "yours", "Your own files and apps", null, yours)];
+ if (mine != null) parts.push(part("space", "thisSpace", name, null, mine));
+ if (others > 0) parts.push(part("others", "otherSpaces", "Other Spaces", null, others));
+ let note = mine == null ? `Can’t tell ${name}’s own data apart from the image it shares.` : null;
+ for (const b of bases) {
+ const isMine = me.base?.key === b.key;
+ const label = `${isMine && baseName ? baseName : imageName(b.image)} image`;
+ const detail = isMine
+ ? b.sharedWith <= 1
+ ? "only this Space uses it"
+ : `shared by ${b.sharedWith} Spaces`
+ : `used by ${b.sharedWith} Space${b.sharedWith === 1 ? "" : "s"}`;
+ if (b.bytes != null) parts.push(part(b.key, "base", label, detail, b.bytes));
+ else if (isMine && note == null) note = `Can’t tell how much the shared ${label} takes.`;
+ }
+ parts.push(part("free", "free", "Free", null, free));
+ const level = host.warning.level;
+ const warning =
+ level === "ok"
+ ? null
+ : {
+ text:
+ level === "critical"
+ ? "This Mac is out of space, so new Spaces can’t be created. Delete old Spaces or snapshots."
+ : "This Mac is almost out of space. Delete old Spaces or snapshots.",
+ button: "See what’s using space",
+ critical: level === "critical",
+ };
+ return { total: size(total), parts, note, warning };
+}
+
+/** A Space's resources dialog: three cards (no explanatory sentences) and how it fits. */
+export function spacePanel(i: SpacePanelInput): SpacePanelView {
+ const s = i.space;
+ const u = s.powerState === "running" ? s.usage : null;
+ const whose = `${i.computer || "this Mac"}’s`;
+ const host = i.host;
+ const processor: SpacePanelCard = {
+ label: LABELS.cpu,
+ value: u ? `${Math.min(100, Math.max(0, Math.round(u.cpuPercent)))}% busy` : "Stopped",
+ given: s.cpuAllocated ? (host?.cpuCount ? `Given ${s.cpuAllocated} of ${whose} ${cores(host.cpuCount)}` : `Given ${cores(s.cpuAllocated)}`) : null,
+ fraction: u ? fill(u.cpuPercent, 100) : 0,
+ };
+ const memTotal = s.memoryAllocated || (u?.memoryLimited ? u.memoryTotal : 0);
+ const memory: SpacePanelCard = {
+ label: LABELS.memory,
+ value: u ? (memTotal ? sizeOf(u.memoryUsed, memTotal) : size(u.memoryUsed)) : "Off",
+ given: s.memoryAllocated
+ ? host?.memoryTotal
+ ? `Given ${size(s.memoryAllocated)} of ${whose} ${size(host.memoryTotal)}`
+ : `Given ${size(s.memoryAllocated)}`
+ : null,
+ fraction: u ? fill(u.memoryUsed, memTotal) : 0,
+ };
+ const given = knownSize(s.diskAllocated) ?? (u?.diskLimited ? knownSize(u.diskTotal) : null);
+ // Not measured on its computer: what the guest holds, only when that is its own data alone
+ // (an overlay with no size of its own; a VM's guest counts its base system too).
+ const guestOwn = u && !u.diskLimited && knownSize(u.diskTotal) == null && u.diskUsed < SIZE_SENTINEL_FLOOR ? u.diskUsed : null;
+ const own = s.diskOnHost?.bytes ?? guestOwn;
+ const files: SpacePanelCard = {
+ label: LABELS.disk,
+ value: own != null && given != null ? sizeOf(own, given) : own != null ? size(own) : given != null ? `Up to ${size(given)}` : "—",
+ given: null,
+ fraction: own != null && given != null ? fill(own, given) : null,
+ };
+ return {
+ cards: [processor, memory, files],
+ fit: host && host.diskTotal > 0 ? diskFit(host, s, i.name, i.spaces, i.baseName) : null,
+ };
}
diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
index 3d30d5c31e..e36534c8da 100644
--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
@@ -13,6 +13,7 @@ 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 { systemName } from "@/lib/resources";
import { StreamSection } from "@/components/space-detail/stream-section";
import { StreamSurface } from "@/components/space-detail/stream-surface";
import { SpaceHeader } from "@/components/space-detail/space-header";
@@ -662,13 +663,22 @@ function SpaceResources({ space, spaces, snapshot, machines }: { space: Space; s
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.
+ // The Spaces on the same computer, with the numbers it sent, for how it fits.
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 }] : [];
+ const onComputer = spaces.flatMap((s) => {
+ const r = sameComputer(s) ? spaceResources(snapshot, s.id) : null;
+ return r ? [r] : [];
});
- return <SpaceResourcesPanel space={mine} name={space.name} host={host} computer={computer} siblings={siblings} />;
+ return (
+ <SpaceResourcesPanel
+ space={mine}
+ name={space.name}
+ host={host}
+ computer={computer}
+ spaces={onComputer}
+ baseName={systemName(space.osPrettyName)}
+ />
+ );
}
/** `stream.viewContext`'s answer (camelCase). */
diff --git a/apps/cua-spaces/src/components/SpaceWindowList.test.tsx b/apps/cua-spaces/src/components/SpaceWindowList.test.tsx
index 7468905236..ec983caa06 100644
--- a/apps/cua-spaces/src/components/SpaceWindowList.test.tsx
+++ b/apps/cua-spaces/src/components/SpaceWindowList.test.tsx
@@ -71,9 +71,11 @@ describe("SpaceWindowList (the Stream section)", () => {
it("draws the core's rows: Desktop with the display's resolution, then each window by title", async () => {
renderList();
await screen.findByText("Cua Docs");
- expect(await screen.findByText("Desktop (1280×800)")).toBeInTheDocument();
+ expect(await screen.findByText("Desktop")).toBeInTheDocument();
const labels = Array.from(document.querySelectorAll(".ssr-label")).map((e) => e.textContent);
- expect(labels).toEqual(["Desktop (1280×800)", "Cua Docs", "Release notes", "xterm", LONG_TITLE]);
+ expect(labels).toEqual(["Desktop", "Cua Docs", "Release notes", "xterm", LONG_TITLE]);
+ // The resolution shows once, as the Desktop row's detail.
+ expect(Array.from(document.querySelectorAll(".ssr-resolution")).map((e) => e.textContent)).toEqual(["1280×800"]);
// The screen target is the Desktop row, not a window row.
expect(screen.queryByText("Cua Driver Local")).toBeNull();
expect(screen.queryByRole("status")).toBeNull();
@@ -108,7 +110,7 @@ describe("SpaceWindowList (the Stream section)", () => {
expect(within(rowOf("xterm")).queryByTestId("ssr-app-icon")).toBeNull();
expect(within(rowOf("xterm")).queryByRole("img")).toBeNull();
// The Desktop row carries the Space's OS mark.
- expect(rowOf("Desktop (1280×800)").querySelector('[data-os-icon="os-ubuntu"]')).not.toBeNull();
+ expect(rowOf("Desktop").querySelector('[data-os-icon="os-ubuntu"]')).not.toBeNull();
});
it("gives every row a Picture in picture icon button", async () => {
@@ -123,7 +125,7 @@ describe("SpaceWindowList (the Stream section)", () => {
it("the Desktop row's button pins the desktop", async () => {
const { onPipDesktop, onPipWindow } = renderList();
await screen.findByText("Cua Docs");
- fireEvent.click(within(rowOf("Desktop (1280×800)")).getByRole("button", { name: "Picture in picture" }));
+ fireEvent.click(within(rowOf("Desktop")).getByRole("button", { name: "Picture in picture" }));
expect(onPipDesktop).toHaveBeenCalledTimes(1);
expect(onPipWindow).not.toHaveBeenCalled();
});
@@ -147,7 +149,7 @@ describe("SpaceWindowList (the Stream section)", () => {
}),
);
expect(await screen.findByRole("status")).toHaveTextContent("No windows: the Space’s window host is not up.");
- expect(screen.getByText("Desktop (1280×800)")).toBeInTheDocument();
+ expect(screen.getByText("Desktop")).toBeInTheDocument();
});
it("tracks open picture-in-picture panels: pip.exit and Close while open", async () => {
let panels: string[] = ["w-2"];
@@ -181,7 +183,7 @@ describe("SpaceWindowList (the Stream section)", () => {
await waitFor(() => expect(notes).toHaveAccessibleName("Close picture in picture"));
expect(notes).toHaveAttribute("aria-pressed", "true");
// Opening the Desktop's: the row flips at once.
- const desktop = within(rowOf("Desktop (1280×800)")).getByRole("button");
+ const desktop = within(rowOf("Desktop")).getByRole("button");
fireEvent.click(desktop);
expect(onPipDesktop).toHaveBeenCalledTimes(1);
await waitFor(() => expect(desktop).toHaveAccessibleName("Close picture in picture"));
diff --git a/apps/cua-spaces/src/components/SpaceWindowList.tsx b/apps/cua-spaces/src/components/SpaceWindowList.tsx
index 4755af6cbe..ad05d70475 100644
--- a/apps/cua-spaces/src/components/SpaceWindowList.tsx
+++ b/apps/cua-spaces/src/components/SpaceWindowList.tsx
@@ -183,6 +183,7 @@ export function SpaceWindowList({
<span className="ssr-label" title={row.help}>
{row.label}
</span>
+ {row.resolution ? <span className="ssr-resolution">{row.resolution}</span> : null}
{row.actions.map((action) => (
<button
key={action.id}
diff --git a/apps/cua-spaces/src/model/window.ts b/apps/cua-spaces/src/model/window.ts
index 4f4cfdfdc8..6aed86c625 100644
--- a/apps/cua-spaces/src/model/window.ts
+++ b/apps/cua-spaces/src/model/window.ts
@@ -174,10 +174,11 @@ export interface StreamRow {
/** "desktop" or the window's handle. */
id: string;
kind: "desktop" | "window";
- /** One line: "Desktop (1280×800)" or the window's title. */
+ /** One line: "Desktop" or the window's title. */
label: string;
/** The full label, for the tooltip. */
help: string;
+ /** The Desktop row's display resolution ("1280×800"), its quiet right-hand detail. */
resolution: string | null;
icon: StreamRowIcon;
actions: { id: "pip"; symbol: string; help: string; active: boolean }[];
diff --git a/apps/cua-spaces/src/styles/desktop.css b/apps/cua-spaces/src/styles/desktop.css
index 52b4154b1a..e22f5f238d 100644
--- a/apps/cua-spaces/src/styles/desktop.css
+++ b/apps/cua-spaces/src/styles/desktop.css
@@ -2941,6 +2941,12 @@ html.is-teleport-picker .hp-panel {
text-overflow: ellipsis;
white-space: nowrap;
}
+.dw .ssr-resolution {
+ flex: 0 0 auto;
+ color: var(--dw-text-3);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
.dw .ssr-status {
margin: 0;
padding: 8px 12px;
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index 70310d82d7..d07c15d525 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -97,4 +97,4 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| --- | --- |
| [Protocol](/cua-sdk/reference/protocol) | The gRPC contracts of cua-spacesd (`cua.env.v1`) and the cua daemon (`cua.daemon.v1`). |
-349 items, 432 methods. The [Types](/cua-sdk/reference/types) page lists them.
+350 items, 432 methods. The [Types](/cua-sdk/reference/types) page lists them.
diff --git a/docs/content/docs/cua-sdk/reference/protocol/daemon-resources.mdx b/docs/content/docs/cua-sdk/reference/protocol/daemon-resources.mdx
index e64135573c..2af6be6d32 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/daemon-resources.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/daemon-resources.mdx
@@ -126,7 +126,7 @@ What `cua.env.v1.SystemService.Metrics` reports from inside a Space.
| `memory_total` | 5 | `uint64` | Memory size in bytes. |
| `memory_limited` | 6 | `bool` | `memory_total` is the guest's own limit. |
| `disk_used` | 7 | `uint64` | Disk in use in bytes. |
-| `disk_total` | 8 | `uint64` | Disk size in bytes. |
+| `disk_total` | 8 | `uint64` | Disk size in bytes; 0 when the guest's file system has no size of its own (gVisor's root overlay says "unlimited") or did not say. Readers treat any size at or above 2^60 bytes the same way: a sentinel, never a size. |
| `disk_limited` | 9 | `bool` | `disk_total` is the guest's own disk. |
### DiskOnHost
@@ -152,4 +152,17 @@ One extra Space on this computer.
| `memory_allocated` | 4 | `uint64` | Memory given to it in bytes (0: unknown). |
| `disk_allocated` | 5 | `uint64` | Its disk's size limit in bytes (0: unknown). |
| `usage` | 6 | [`GuestUsage`](#guestusage) | The guest's own numbers; unset while it is off or unreachable. |
-| `disk_on_host` | 7 | [`DiskOnHost`](#diskonhost) | What it costs this computer; unset for a container. |
+| `disk_on_host` | 7 | [`DiskOnHost`](#diskonhost) | What it costs this computer: its own data only, never the base it shares; unset when there is nothing to measure. |
+| `base` | 8 | [`SharedBase`](#sharedbase) | The base image it is a copy-on-write copy of; unset when it has none or the runtime cannot tell it apart. |
+
+### SharedBase
+
+A base image several Spaces share copy-on-write: a container image's
+layers, the image a virtual machine's disk was cloned from.
+
+| Field | # | Type | Description |
+| --- | --- | --- | --- |
+| `key` | 1 | `string` | Which base: Spaces with the same key share the same blocks. |
+| `image` | 2 | `string` | The image reference it came from, for example `ghcr.io/trycua/linux:24.04`. |
+| `bytes` | 3 | optional `uint64` | What it takes on this computer, once for all its Spaces. Unset when the runtime cannot tell it apart from the Spaces' own data. |
+| `shared_with` | 4 | `uint32` | Local Spaces that use it, this one included. |
diff --git a/docs/content/docs/cua-sdk/reference/protocol/env-system.mdx b/docs/content/docs/cua-sdk/reference/protocol/env-system.mdx
index 641d07824e..69c2e7da25 100644
--- a/docs/content/docs/cua-sdk/reference/protocol/env-system.mdx
+++ b/docs/content/docs/cua-sdk/reference/protocol/env-system.mdx
@@ -310,7 +310,7 @@ Response for `SystemService.Metrics`.
| `load_average_1m` | 4 | `double` | 1-minute load average (0 on Windows). |
| `memory_total_bytes` | 5 | `uint64` | Total guest memory in bytes. |
| `memory_used_bytes` | 6 | `uint64` | Used guest memory in bytes (excluding reclaimable cache). |
-| `disk_total_bytes` | 7 | `uint64` | Total bytes of the filesystem named by `disk_path`. |
+| `disk_total_bytes` | 7 | `uint64` | Total bytes of the filesystem named by `disk_path`; 0 when it has no size of its own (gVisor's root overlay reports "unlimited"), never a sentinel such as 2^63. |
| `disk_used_bytes` | 8 | `uint64` | Used bytes of that filesystem. |
| `managed_process_count` | 9 | `uint32` | Processes currently managed by `ProcessService`. |
| `media_session_count` | 10 | `uint32` | Open media sessions. |
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
index d01f800bb3..d68ff6541d 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx
@@ -18,7 +18,7 @@ The cua SDK: the only `#[uniffi::export]` crate of `libs/cua`.
These are the objects, records, enums and functions the language bindings export, documented once in the [Cua SDK reference](/cua-sdk/reference), whose Rust tabs show each signature. Objects are `Arc<T>` handles whose methods are `async fn` returning `Result<_, CuaError>`, records are structs with public fields, and names are snake_case.
-[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
+[`agent_event_category`](/cua-sdk/reference/agents#agent_event_category), [`agent_harnesses`](/cua-sdk/reference/agents#agent_harnesses), [`AgentActionReport`](/cua-sdk/reference/spaces/agents#agentactionreport-record), [`AgentArtifact`](/cua-sdk/reference/agents#agentartifact-record), [`AgentDelivery`](/cua-sdk/reference/spaces/persistent-agents#agentdelivery-record), [`AgentEvent`](/cua-sdk/reference/agents#agentevent-record), [`AgentEventPage`](/cua-sdk/reference/agents#agenteventpage-record), [`AgentFile`](/cua-sdk/reference/agents#agentfile-record), [`AgentInfo`](/cua-sdk/reference/agent-setup#agentinfo-record), [`AgentMcpServer`](/cua-sdk/reference/agent-setup#agentmcpserver-record), [`AgentPauseReport`](/cua-sdk/reference/spaces/persistent-agents#agentpausereport-record), [`AgentResumeReport`](/cua-sdk/reference/spaces/persistent-agents#agentresumereport-record), [`AgentRun`](/cua-sdk/reference/agents#agentrun), [`AgentRunInfo`](/cua-sdk/reference/agents#agentruninfo-record), [`AgentRunMcpServer`](/cua-sdk/reference/agents#agentrunmcpserver-record), [`AgentRunOptions`](/cua-sdk/reference/agents#agentrunoptions-record), [`AgentRunResult`](/cua-sdk/reference/agents#agentrunresult-record), [`AgentRunStatus`](/cua-sdk/reference/spaces/agents#agentrunstatus-record), [`Agents`](/cua-sdk/reference/agents#agents), [`AgentSetup`](/cua-sdk/reference/agent-setup#agentsetup), [`AgentSetupChange`](/cua-sdk/reference/agent-setup#agentsetupchange-enum), [`AgentSetupOutcome`](/cua-sdk/reference/agent-setup#agentsetupoutcome-record), [`AgentSetupTarget`](/cua-sdk/reference/agent-setup#agentsetuptarget-enum), [`AgentStartReport`](/cua-sdk/reference/spaces/agents#agentstartreport-record), [`AgentTranscript`](/cua-sdk/reference/agents#agenttranscript), [`AgentTranscriptItem`](/cua-sdk/reference/agents#agenttranscriptitem-record), [`ambiguous_sandbox_candidates`](/cua-sdk/reference/sandbox/lifecycle#ambiguous_sandbox_candidates), [`AudioPacket`](/cua-sdk/reference/spacesd/computer#audiopacket-record), [`AudioSink`](/cua-sdk/reference/spacesd/computer#audiosink), [`Auth`](/cua-sdk/reference/auth#auth), [`AuthIdentity`](/cua-sdk/reference/auth#authidentity-record), [`AuthStatus`](/cua-sdk/reference/auth#authstatus-record), [`BakeForkCheck`](/cua-sdk/reference/sandbox/bake#bakeforkcheck-record), [`BakeOptions`](/cua-sdk/reference/sandbox/bake#bakeoptions-record), [`BakeSummary`](/cua-sdk/reference/sandbox/bake#bakesummary-record), [`BuildFile`](/cua-sdk/reference/image#buildfile-record), [`BuildImageConfig`](/cua-sdk/reference/spaces/build#buildimageconfig-record), [`BuildInfo`](/cua-sdk/reference/spaces/build#buildinfo-record), [`BuildListener`](/cua-sdk/reference/spaces/build#buildlistener), [`BuildOptions`](/cua-sdk/reference/spaces/build#buildoptions-record), [`BuildProgress`](/cua-sdk/reference/spaces/build#buildprogress-record), [`BuildResult`](/cua-sdk/reference/spaces/build#buildresult-record), [`BuildStep`](/cua-sdk/reference/spaces/build#buildstep-enum), [`BuildStepResult`](/cua-sdk/reference/spaces/build#buildstepresult-record), [`BulkResult`](/cua-sdk/reference/spaces/sharing#bulkresult-record), [`BundledSkill`](/cua-sdk/reference/agent-setup#bundledskill-record), [`canonical_image`](/cua-sdk/reference/image#canonical_image), [`canonical_image_tier`](/cua-sdk/reference/image#canonical_image_tier), [`check_placement`](/cua-sdk/reference/cua#check_placement), [`CheckpointSummary`](/cua-sdk/reference/sandbox/checkpoints#checkpointsummary-record), [`CloudAuditEntry`](/cua-sdk/reference/spaces/persistent-agents#cloudauditentry-record), [`CloudCheck`](/cua-sdk/reference/spaces/persistent-agents#cloudcheck-record), [`CloudConnected`](/cua-sdk/reference/spaces/persistent-agents#cloudconnected-record), [`CloudConnectOptions`](/cua-sdk/reference/spaces/persistent-agents#cloudconnectoptions-record), [`CloudCostReport`](/cua-sdk/reference/spaces/persistent-agents#cloudcostreport-record), [`CloudCostRow`](/cua-sdk/reference/spaces/persistent-agents#cloudcostrow-record), [`CloudCredentials`](/cua-sdk/reference/spaces/persistent-agents#cloudcredentials-record), [`CloudDisconnected`](/cua-sdk/reference/spaces/persistent-agents#clouddisconnected-record), [`CloudKind`](/cua-sdk/reference/spaces/persistent-agents#cloudkind-record), [`CloudNext`](/cua-sdk/reference/spaces/persistent-agents#cloudnext-record), [`CloudProvider`](/cua-sdk/reference/spaces/persistent-agents#cloudprovider-record), [`CloudResource`](/cua-sdk/reference/spaces/persistent-agents#cloudresource-record), [`CloudStatus`](/cua-sdk/reference/spaces/persistent-agents#cloudstatus-record), [`CloudSweepItem`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepitem-record), [`CloudSweepReport`](/cua-sdk/reference/spaces/persistent-agents#cloudsweepreport-record), [`CloudTarget`](/cua-sdk/reference/spaces/persistent-agents#cloudtarget-record), [`CloudTestReport`](/cua-sdk/reference/spaces/persistent-agents#cloudtestreport-record), [`ComputerGrant`](/cua-sdk/reference/spaces/persistent-agents#computergrant-record), [`ComputerResources`](/cua-sdk/reference/spaces/resources#computerresources-record), [`config_get`](/cua-sdk/reference/cua#config_get), [`config_list`](/cua-sdk/reference/cua#config_list), [`config_path`](/cua-sdk/reference/cua#config_path), [`config_set`](/cua-sdk/reference/cua#config_set), [`config_unset`](/cua-sdk/reference/cua#config_unset), [`ConfigEntry`](/cua-sdk/reference/cua#configentry-record), [`Container`](/cua-sdk/reference/image#container-record), [`contrib_providers_built`](/cua-sdk/reference/sandbox#contrib_providers_built), [`Cua`](/cua-sdk/reference/cua#cua), [`CuaConfig`](/cua-sdk/reference/cua#cuaconfig-record), [`CuaInfo`](/cua-sdk/reference/cua#cuainfo-record), [`CuaMode`](/cua-sdk/reference/cua#cuamode-enum), [`CursorArt`](/cua-sdk/reference/spaces/streams#cursorart-record), [`DeviceEnrollment`](/cua-sdk/reference/spaces/host#deviceenrollment-record), [`Devices`](/cua-sdk/reference/spaces/host#devices), [`DevicesSnapshot`](/cua-sdk/reference/spaces/host#devicessnapshot-record), [`DiskLevel`](/cua-sdk/reference/spaces/resources#disklevel-enum), [`DiskOnHost`](/cua-sdk/reference/spaces/resources#diskonhost-record), [`DiskWarning`](/cua-sdk/reference/spaces/resources#diskwarning-record), [`DoctorReport`](/cua-sdk/reference/cua#doctorreport-record), [`DriveAccessRequest`](/cua-sdk/reference/spaces/volume#driveaccessrequest-record), [`DriveAudit`](/cua-sdk/reference/spaces/volume#driveaudit-record), [`DriveAuditEvent`](/cua-sdk/reference/spaces/volume#driveauditevent-record), [`DriveCacheStats`](/cua-sdk/reference/spaces/volume#drivecachestats-record), [`DriveConflict`](/cua-sdk/reference/spaces/volume#driveconflict-record), [`DriveDevice`](/cua-sdk/reference/spaces/volume#drivedevice-record), [`DriveEntry`](/cua-sdk/reference/spaces/volume#driveentry-record), [`DriveFile`](/cua-sdk/reference/spaces/volume#drivefile-record), [`DriveFileSync`](/cua-sdk/reference/spaces/volume#drivefilesync-record), [`DriveGrant`](/cua-sdk/reference/spaces/volume#drivegrant-record), [`DriveListing`](/cua-sdk/reference/spaces/volume#drivelisting-record), [`DriveMountStatus`](/cua-sdk/reference/spaces/volume#drivemountstatus-record), [`DriveObject`](/cua-sdk/reference/spaces/volume#driveobject-record), [`DrivePendingUpload`](/cua-sdk/reference/spaces/volume#drivependingupload-record), [`DriveS3Settings`](/cua-sdk/reference/spaces/volume#drives3settings-record), [`DriveSpaceVolume`](/cua-sdk/reference/spaces/volume#drivespacevolume-record), [`DriveStorage`](/cua-sdk/reference/spaces/volume#drivestorage-record), [`DriveStorageCheck`](/cua-sdk/reference/spaces/volume#drivestoragecheck-record), [`DriveStorageUpdate`](/cua-sdk/reference/spaces/volume#drivestorageupdate-record), [`DriveSyncEvent`](/cua-sdk/reference/spaces/volume#drivesyncevent-record), [`DriveSyncEvents`](/cua-sdk/reference/spaces/volume#drivesyncevents-record), [`DriveSyncStatus`](/cua-sdk/reference/spaces/volume#drivesyncstatus-record), [`DriveVersion`](/cua-sdk/reference/spaces/volume#driveversion-record), [`DriveView`](/cua-sdk/reference/spaces/volume#driveview-record), [`EgressEnforcement`](/cua-sdk/reference/spaces/space#egressenforcement-enum), [`EgressPolicy`](/cua-sdk/reference/spaces#egresspolicy-record), [`ElasticAssignment`](/cua-sdk/reference/spaces/elastic#elasticassignment-record), [`ElasticBudget`](/cua-sdk/reference/spaces/elastic#elasticbudget-record), [`ElasticBudgetUpdate`](/cua-sdk/reference/spaces/elastic#elasticbudgetupdate-record), [`ElasticDecision`](/cua-sdk/reference/spaces/elastic#elasticdecision-record), [`ElasticHost`](/cua-sdk/reference/spaces/elastic#elastichost-record), [`ElasticNewHost`](/cua-sdk/reference/spaces/elastic#elasticnewhost-record), [`ElasticPlan`](/cua-sdk/reference/spaces/elastic#elasticplan-record), [`ElasticPlanRequest`](/cua-sdk/reference/spaces/elastic#elasticplanrequest-record), [`ElasticRemoved`](/cua-sdk/reference/spaces/elastic#elasticremoved-record), [`ElasticUnplaced`](/cua-sdk/reference/spaces/elastic#elasticunplaced-record), [`ForkBatch`](/cua-sdk/reference/sandbox/fork-batch#forkbatch), [`ForkBatchEvent`](/cua-sdk/reference/sandbox/fork-batch#forkbatchevent-enum), [`ForkBatchItem`](/cua-sdk/reference/sandbox/fork-batch#forkbatchitem-record), [`ForkBatchPlacement`](/cua-sdk/reference/sandbox/fork-batch#forkbatchplacement-record), [`ForkBatchResult`](/cua-sdk/reference/sandbox/fork-batch#forkbatchresult-record), [`ForkBatchSummary`](/cua-sdk/reference/sandbox/fork-batch#forkbatchsummary-record), [`ForkGroup`](/cua-sdk/reference/sandbox/fork-batch#forkgroup-record), [`ForkManyOptions`](/cua-sdk/reference/sandbox/fork-batch#forkmanyoptions-record), [`FrameSink`](/cua-sdk/reference/spacesd/computer#framesink), [`GpuOption`](/cua-sdk/reference/spaces#gpuoption-record), [`GpuSupport`](/cua-sdk/reference/spaces#gpusupport-record), [`GuestDisplay`](/cua-sdk/reference/spacesd#guestdisplay), [`GuestUsage`](/cua-sdk/reference/spaces/resources#guestusage-record), [`HomeTransfer`](/cua-sdk/reference/spaces/persistent-agents#hometransfer-record), [`Host`](/cua-sdk/reference/spaces/host#host), [`HostAccessRecord`](/cua-sdk/reference/spaces/host#hostaccessrecord-record), [`HostPermission`](/cua-sdk/reference/spaces/host#hostpermission-record), [`HostProvidedSpace`](/cua-sdk/reference/spaces/host#hostprovidedspace-record), [`HostServiceMigration`](/cua-sdk/reference/spaces/host#hostservicemigration-record), [`HostSettingsChange`](/cua-sdk/reference/spaces/host#hostsettingschange-record), [`HostSetupOptions`](/cua-sdk/reference/spaces/host#hostsetupoptions-record), [`HostSpacesAuditRecord`](/cua-sdk/reference/spaces/host#hostspacesauditrecord-record), [`HostStatus`](/cua-sdk/reference/spaces/host#hoststatus-record), [`HttpHeader`](/cua-sdk/reference/services#httpheader-record), [`HttpResponse`](/cua-sdk/reference/services#httpresponse-record), [`image_alias`](/cua-sdk/reference/image#image_alias), [`ImageBuild`](/cua-sdk/reference/image#imagebuild-record), [`ImageInfo`](/cua-sdk/reference/image#imageinfo-record), [`ImageLayer`](/cua-sdk/reference/image#imagelayer-enum), [`Local`](/cua-sdk/reference/cua#local), [`LocalImage`](/cua-sdk/reference/cua#localimage-record), [`LocalStorage`](/cua-sdk/reference/cua#localstorage-record), [`LocationInfo`](/cua-sdk/reference/cua#locationinfo-record), [`locations`](/cua-sdk/reference/cua#locations), [`LoginAttempt`](/cua-sdk/reference/auth#loginattempt), [`LoginMethod`](/cua-sdk/reference/auth#loginmethod-enum), [`MachineHealth`](/cua-sdk/reference/spaces/host#machinehealth-record), [`MachineHealthCheck`](/cua-sdk/reference/spaces/host#machinehealthcheck-record), [`may_have_session`](/cua-sdk/reference/auth#may_have_session), [`mcp_connect`](/cua-sdk/reference/services#mcp_connect), [`mcp_connect_url`](/cua-sdk/reference/services#mcp_connect_url), [`McpClient`](/cua-sdk/reference/services#mcpclient), [`McpConfig`](/cua-sdk/reference/services#mcpconfig-record), [`MediaBridge`](/cua-sdk/reference/spacesd/computer#mediabridge-record), [`MediaEvent`](/cua-sdk/reference/spacesd/computer#mediaevent-record), [`MediaSession`](/cua-sdk/reference/spacesd/computer#mediasession), [`MediaStats`](/cua-sdk/reference/spacesd/computer#mediastats-record), [`NamedVolume`](/cua-sdk/reference/spaces/volume#namedvolume-record), [`normalize_image`](/cua-sdk/reference/image#normalize_image), [`NotificationInfo`](/cua-sdk/reference/spaces/persistent-agents#notificationinfo-record), [`omarchy_image`](/cua-sdk/reference/image#omarchy_image), [`Overlay`](/cua-sdk/reference/sandbox#overlay-record), [`OverlayResult`](/cua-sdk/reference/sandbox#overlayresult-record), [`PairingCode`](/cua-sdk/reference/spaces/host#pairingcode-record), [`parse_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#parse_sandbox_ref), [`PersistentAgentInfo`](/cua-sdk/reference/spaces/persistent-agents#persistentagentinfo-record), [`PersistentAgentOptions`](/cua-sdk/reference/spaces/persistent-agents#persistentagentoptions-record), [`PoolCreateOptions`](/cua-sdk/reference/image#poolcreateoptions-record), [`PortForward`](/cua-sdk/reference/services#portforward), [`presence_color`](/cua-sdk/reference/spaces/streams#presence_color), [`presence_conformance_json`](/cua-sdk/reference/spaces/streams#presence_conformance_json), [`presence_cursor_art`](/cua-sdk/reference/spaces/streams#presence_cursor_art), [`presence_cursor_art_all`](/cua-sdk/reference/spaces/streams#presence_cursor_art_all), [`presence_cursor_art_svg`](/cua-sdk/reference/spaces/streams#presence_cursor_art_svg), [`presence_now_ms`](/cua-sdk/reference/spaces/streams#presence_now_ms), [`presence_text_color`](/cua-sdk/reference/spaces/streams#presence_text_color), [`PresenceCursor`](/cua-sdk/reference/spaces/streams#presencecursor-record), [`PresenceDrawable`](/cua-sdk/reference/spaces/streams#presencedrawable-record), [`PresenceEvent`](/cua-sdk/reference/spaces/streams#presenceevent-record), [`PresenceIdentity`](/cua-sdk/reference/spaces/streams#presenceidentity-record), [`PresenceMember`](/cua-sdk/reference/spaces/streams#presencemember-record), [`PresenceParticipant`](/cua-sdk/reference/spaces/streams#presenceparticipant-record), [`PresencePoint`](/cua-sdk/reference/spaces/streams#presencepoint-record), [`PresenceView`](/cua-sdk/reference/spaces/streams#presenceview), [`Prewarm`](/cua-sdk/reference/spaces/elastic#prewarm-record), [`PrewarmOptions`](/cua-sdk/reference/spaces/elastic#prewarmoptions-record), [`PrewarmPlacement`](/cua-sdk/reference/spaces/elastic#prewarmplacement-record), [`PublicUrl`](/cua-sdk/reference/services#publicurl-record), [`qualify_sandbox_ref`](/cua-sdk/reference/sandbox/lifecycle#qualify_sandbox_ref), [`ReadinessProbe`](/cua-sdk/reference/image#readinessprobe-record), [`RegistrySecret`](/cua-sdk/reference/image#registrysecret-enum), [`Relay`](/cua-sdk/reference/spaces/host#relay), [`RelayAuditEvent`](/cua-sdk/reference/spaces/host#relayauditevent-record), [`RelayClientInfo`](/cua-sdk/reference/spaces/host#relayclientinfo-record), [`RelayDevice`](/cua-sdk/reference/spaces/host#relaydevice-record), [`RelayMachine`](/cua-sdk/reference/spaces/host#relaymachine-record), [`ReplayMode`](/cua-sdk/reference/spacesd/shell#replaymode-enum), [`resolve_image`](/cua-sdk/reference/image#resolve_image), [`resolve_image_with_secret`](/cua-sdk/reference/image#resolve_image_with_secret), [`ResolvedImage`](/cua-sdk/reference/image#resolvedimage-record), [`ResourcesEvent`](/cua-sdk/reference/spaces/resources#resourcesevent-enum), [`ResourcesListener`](/cua-sdk/reference/spaces/resources#resourceslistener), [`ResourcesSnapshot`](/cua-sdk/reference/spaces/resources#resourcessnapshot-record), [`ResourcesUpdate`](/cua-sdk/reference/spaces/resources#resourcesupdate-record), [`ResourcesWatch`](/cua-sdk/reference/spaces/resources#resourceswatch), [`RoutineInfo`](/cua-sdk/reference/spaces/persistent-agents#routineinfo-record), [`RuntimeCheck`](/cua-sdk/reference/cua#runtimecheck-record), [`RuntimeCheckStatus`](/cua-sdk/reference/cua#runtimecheckstatus-enum), [`Sandbox`](/cua-sdk/reference/sandbox#sandbox), [`sandbox_locations`](/cua-sdk/reference/sandbox#sandbox_locations), [`SandboxCreateOptions`](/cua-sdk/reference/image#sandboxcreateoptions-record), [`Sandboxes`](/cua-sdk/reference/sandbox#sandboxes), [`SandboxInfo`](/cua-sdk/reference/sandbox#sandboxinfo-record), [`SandboxListing`](/cua-sdk/reference/sandbox#sandboxlisting-record), [`SandboxPhase`](/cua-sdk/reference/sandbox#sandboxphase-enum), [`SandboxPool`](/cua-sdk/reference/image#sandboxpool-record), [`SandboxRefParts`](/cua-sdk/reference/sandbox/lifecycle#sandboxrefparts-record), [`SandboxStatus`](/cua-sdk/reference/sandbox#sandboxstatus-enum), [`Service`](/cua-sdk/reference/services#service), [`ServiceEndpoint`](/cua-sdk/reference/services#serviceendpoint-record), [`SetupStep`](/cua-sdk/reference/cua#setupstep-record), [`Share`](/cua-sdk/reference/share#share-record), [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum), [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record), [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record), [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record), [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record), [`SnapshotFallbackOptions`](/cua-sdk/reference/sandbox/fork-batch#snapshotfallbackoptions-record), [`SnapshotSyncProgress`](/cua-sdk/reference/sandbox/fork-batch#snapshotsyncprogress-record), [`Space`](/cua-sdk/reference/spaces/space#space), [`SpaceAgentOptions`](/cua-sdk/reference/spaces/agents#spaceagentoptions-record), [`SpaceAppIcon`](/cua-sdk/reference/spaces/space#spaceappicon-record), [`SpaceAppIconRequest`](/cua-sdk/reference/spaces/space#spaceappiconrequest-record), [`SpaceBashResult`](/cua-sdk/reference/spaces/space#spacebashresult-record), [`SpaceCancelOutcome`](/cua-sdk/reference/spaces#spacecanceloutcome-record), [`SpaceCreateListener`](/cua-sdk/reference/spaces#spacecreatelistener), [`SpaceCreateOptions`](/cua-sdk/reference/spaces#spacecreateoptions-record), [`SpaceCreateProgress`](/cua-sdk/reference/spaces#spacecreateprogress-record), [`SpaceCreateResult`](/cua-sdk/reference/spaces#spacecreateresult-record), [`SpaceCreatingElsewhere`](/cua-sdk/reference/spaces/space#spacecreatingelsewhere-record), [`SpaceDisplay`](/cua-sdk/reference/spaces/space#spacedisplay-record), [`SpaceHotspotStatus`](/cua-sdk/reference/spaces/space#spacehotspotstatus-record), [`SpaceInfo`](/cua-sdk/reference/spaces#spaceinfo-record), [`SpaceList`](/cua-sdk/reference/spaces/list-watch#spacelist-record), [`SpacePowerReport`](/cua-sdk/reference/spaces/resize#spacepowerreport-record), [`SpacePresence`](/cua-sdk/reference/spaces/streams#spacepresence), [`SpaceRelayRegistration`](/cua-sdk/reference/spaces/relay-registration#spacerelayregistration-record), [`SpaceResizeReport`](/cua-sdk/reference/spaces/resize#spaceresizereport-record), [`SpaceResources`](/cua-sdk/reference/spaces/resources#spaceresources-record), [`Spaces`](/cua-sdk/reference/spaces#spaces), [`spaces_tool_methods`](/cua-sdk/reference/spaces#spaces_tool_methods), [`SpacesdClient`](/cua-sdk/reference/spacesd#spacesdclient), [`SpacesdDownload`](/cua-sdk/reference/spacesd#spacesddownload), [`SpacesdForward`](/cua-sdk/reference/spacesd#spacesdforward), [`SpacesdHttpHeader`](/cua-sdk/reference/spacesd#spacesdhttpheader-record), [`SpacesdHttpRequest`](/cua-sdk/reference/spacesd#spacesdhttprequest-record), [`SpacesdHttpResponse`](/cua-sdk/reference/spacesd#spacesdhttpresponse-record), [`SpacesdProcess`](/cua-sdk/reference/spacesd/shell#spacesdprocess), [`SpaceSendFileOptions`](/cua-sdk/reference/spaces/space#spacesendfileoptions-record), [`SpaceSendFileReport`](/cua-sdk/reference/spaces/space#spacesendfilereport-record), [`SpaceSentFile`](/cua-sdk/reference/spaces/space#spacesentfile-record), [`SpaceShareEntry`](/cua-sdk/reference/spaces/sharing#spaceshareentry-record), [`SpaceShares`](/cua-sdk/reference/spaces/sharing#spaceshares-record), [`SpaceSharing`](/cua-sdk/reference/spaces/sharing#spacesharing-record), [`SpacesHost`](/cua-sdk/reference/spaces/host#spaceshost-record), [`SpacesHostLimit`](/cua-sdk/reference/spaces/host#spaceshostlimit-record), [`SpacesHostLoad`](/cua-sdk/reference/spaces/host#spaceshostload-record), [`SpacesListListener`](/cua-sdk/reference/spaces/list-watch#spaceslistlistener), [`SpacesListWatch`](/cua-sdk/reference/spaces/list-watch#spaceslistwatch), [`SpacesToolMethod`](/cua-sdk/reference/spaces#spacestoolmethod-record), [`SpaceStreamOptions`](/cua-sdk/reference/spaces/streams#spacestreamoptions-record), [`SpaceStreamSession`](/cua-sdk/reference/spaces/streams#spacestreamsession), [`SpaceStreamStats`](/cua-sdk/reference/spaces/streams#spacestreamstats-record), [`SpaceStreamTicket`](/cua-sdk/reference/spaces/streams#spacestreamticket-record), [`SpaceTeamShare`](/cua-sdk/reference/spaces/sharing#spaceteamshare-record), [`SpaceToolInfo`](/cua-sdk/reference/spaces/space#spacetoolinfo-record), [`SpaceToolResult`](/cua-sdk/reference/spaces/space#spacetoolresult-record), [`SpaceTransferReport`](/cua-sdk/reference/spaces/space#spacetransferreport-record), [`SpaceTransport`](/cua-sdk/reference/spaces/channel#spacetransport-record), [`SpaceUsage`](/cua-sdk/reference/spaces/space#spaceusage-record), [`SpaceWindow`](/cua-sdk/reference/spaces/space#spacewindow-record), [`SpaceWriteReport`](/cua-sdk/reference/spaces/space#spacewritereport-record), [`StorageVolume`](/cua-sdk/reference/cua#storagevolume-record), [`StreamStatsReport`](/cua-sdk/reference/auth#streamstatsreport-record), [`telemetry_acknowledge_link_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_link_notice), [`telemetry_acknowledge_notice`](/cua-sdk/reference/auth#telemetry_acknowledge_notice), [`telemetry_flush`](/cua-sdk/reference/auth#telemetry_flush), [`telemetry_link_notice`](/cua-sdk/reference/auth#telemetry_link_notice), [`telemetry_link_notice_due`](/cua-sdk/reference/auth#telemetry_link_notice_due), [`telemetry_link_state`](/cua-sdk/reference/auth#telemetry_link_state), [`telemetry_notice_text`](/cua-sdk/reference/auth#telemetry_notice_text), [`telemetry_record_bench_run`](/cua-sdk/reference/auth#telemetry_record_bench_run), [`telemetry_record_feature`](/cua-sdk/reference/auth#telemetry_record_feature), [`telemetry_record_onboarding_step`](/cua-sdk/reference/auth#telemetry_record_onboarding_step), [`telemetry_record_stream_stats`](/cua-sdk/reference/auth#telemetry_record_stream_stats), [`telemetry_reset_id`](/cua-sdk/reference/auth#telemetry_reset_id), [`telemetry_schema_json`](/cua-sdk/reference/auth#telemetry_schema_json), [`telemetry_set_enabled`](/cua-sdk/reference/auth#telemetry_set_enabled), [`telemetry_set_surface`](/cua-sdk/reference/auth#telemetry_set_surface), [`telemetry_show_last`](/cua-sdk/reference/auth#telemetry_show_last), [`telemetry_status`](/cua-sdk/reference/auth#telemetry_status), [`telemetry_sync_account`](/cua-sdk/reference/auth#telemetry_sync_account), [`telemetry_use_app_notice`](/cua-sdk/reference/auth#telemetry_use_app_notice), [`TelemetryLinkNotice`](/cua-sdk/reference/auth#telemetrylinknotice-record), [`TelemetryStatus`](/cua-sdk/reference/auth#telemetrystatus-record), [`TeleportApprover`](/cua-sdk/reference/spaces/space#teleportapprover), [`TeleportDecision`](/cua-sdk/reference/spaces/space#teleportdecision-record), [`TeleportItem`](/cua-sdk/reference/spaces/space#teleportitem-record), [`TeleportManifest`](/cua-sdk/reference/spaces/space#teleportmanifest-record), [`TeleportReceipt`](/cua-sdk/reference/spaces/space#teleportreceipt-record), [`VideoFrame`](/cua-sdk/reference/spacesd/computer#videoframe-record), [`ViewerLink`](/cua-sdk/reference/sandbox#viewerlink-record), [`ViewerOptions`](/cua-sdk/reference/sandbox#vieweroptions-record), [`VolumeMount`](/cua-sdk/reference/spaces/volume#volumemount-record).
## Types
diff --git a/docs/content/docs/cua-sdk/reference/spaces/resources.mdx b/docs/content/docs/cua-sdk/reference/spaces/resources.mdx
index 8e7000da38..b5881eb536 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/resources.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/resources.mdx
@@ -180,7 +180,8 @@ One extra Space on this Mac.
| `memory_allocated` / `memoryAllocated` | `u64` | | Memory given to it, bytes (0: unknown). |
| `disk_allocated` / `diskAllocated` | `u64` | | Its disk's size limit, bytes (0: unknown). |
| `usage` | [`Option<GuestUsage>`](#guestusage-record) | | The guest's own numbers; absent while it is off or unreachable. |
-| `disk_on_host` / `diskOnHost` | [`Option<DiskOnHost>`](#diskonhost-record) | | What it costs this Mac; absent for a container. |
+| `disk_on_host` / `diskOnHost` | [`Option<DiskOnHost>`](#diskonhost-record) | | What it costs this Mac: its own data only, never the base it shares; absent when there is nothing to measure. |
+| `base` | [`Option<SharedBase>`](/cua-sdk/reference/spaces/space#sharedbase-record) | | The base image it is a copy-on-write copy of, counted once for all the Spaces that share it; absent when it has none or the runtime cannot tell it apart. |
## `GuestUsage` record
@@ -195,7 +196,7 @@ What `SystemService.Metrics` reports from inside a Space.
| `memory_total` / `memoryTotal` | `u64` | | Memory size, bytes. |
| `memory_limited` / `memoryLimited` | `bool` | | `memory_total` is the guest's own limit. |
| `disk_used` / `diskUsed` | `u64` | | Disk in use, bytes. |
-| `disk_total` / `diskTotal` | `u64` | | Disk size, bytes. |
+| `disk_total` / `diskTotal` | `Option<u64>` | | Disk size, bytes; absent when the guest's file system has no size of its own (gVisor's root overlay) or did not say. Never a sentinel. |
| `disk_limited` / `diskLimited` | `bool` | | `disk_total` is the guest's own disk. |
## `DiskOnHost` record
diff --git a/docs/content/docs/cua-sdk/reference/spaces/space.mdx b/docs/content/docs/cua-sdk/reference/spaces/space.mdx
index fd038ff0d8..0065b3c31e 100644
--- a/docs/content/docs/cua-sdk/reference/spaces/space.mdx
+++ b/docs/content/docs/cua-sdk/reference/spaces/space.mdx
@@ -1021,6 +1021,18 @@ Returned by [`Space.hotspot_status`](#spacehotspot_status), [`Space.start_hotspo
| `bytes_in` / `bytesIn` | `u64` | | Bytes into the guest. |
| `served_here` / `servedHere` | `bool` | | Served by the process that owns the Spaces runtime. |
+## `SharedBase` record
+
+A base image several Spaces share copy-on-write (a container image's
+layers, the image a VM disk was cloned from).
+
+| Field | Type | Default | Description |
+| --- | --- | --- | --- |
+| `key` | `String` | | Which base: Spaces with the same key share the same blocks. |
+| `image` | `String` | | The image reference it came from (`ghcr.io/trycua/linux:24.04`). |
+| `bytes` | `Option<u64>` | | What it takes on this computer, once for all its Spaces; absent when the runtime cannot tell it apart from the Spaces' own data. |
+| `shared_with` / `sharedWith` | `u32` | | Local Spaces that use it, this one included. |
+
## `SiteLoginOptions` record
Options for `Space.request_site_login`.
diff --git a/docs/content/docs/cua-sdk/reference/types.mdx b/docs/content/docs/cua-sdk/reference/types.mdx
index 1c14d4afd8..609568bdac 100644
--- a/docs/content/docs/cua-sdk/reference/types.mdx
+++ b/docs/content/docs/cua-sdk/reference/types.mdx
@@ -48,7 +48,7 @@ Renamed members: in Kotlin, objects implement `AutoCloseable`, whose `close()` f
## All items
-321 items. Methods are listed on their object.
+322 items. Methods are listed on their object.
The 10 items of Batched forks are listed on [its page](/cua-sdk/reference/sandbox/fork-batch#all-items).
@@ -285,6 +285,7 @@ The 11 items of Processor, memory and disk are listed on [its page](/cua-sdk/ref
| [`Share`](/cua-sdk/reference/share#share-record) | record | One share. |
| [`ShareAccess`](/cua-sdk/reference/share#shareaccess-enum) | enum | Who may open a share. |
| [`ShareCheck`](/cua-sdk/reference/share#sharecheck-record) | record | What opening a link once returned. |
+| [`SharedBase`](/cua-sdk/reference/spaces/space#sharedbase-record) | record | A base image several Spaces share copy-on-write (a container image's layers, the image a VM disk was cloned from). |
| [`SiteLoginOptions`](/cua-sdk/reference/spaces/space#siteloginoptions-record) | record | Options for `Space.request_site_login`. |
| [`SiteLoginReport`](/cua-sdk/reference/spaces/space#siteloginreport-record) | record | What `Space.request_site_login` did. |
| [`Space`](/cua-sdk/reference/spaces/space#space) | object | A connected Space. |
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/system.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/system.rs
index 5a3bbc2489..12216023c4 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/system.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/system.rs
@@ -521,9 +521,10 @@ fn disk_usage(path: &std::path::Path) -> (u64, u64) {
return (0, 0);
}
let frag = stat.f_frsize as u64;
- let total = stat.f_blocks as u64 * frag;
- let free = stat.f_bfree as u64 * frag;
- (total, total.saturating_sub(free))
+ sized(
+ (stat.f_blocks as u64).saturating_mul(frag),
+ (stat.f_bfree as u64).saturating_mul(frag),
+ )
}
#[cfg(not(unix))]
{
@@ -532,11 +533,27 @@ fn disk_usage(path: &std::path::Path) -> (u64, u64) {
.iter()
.filter(|d| path.starts_with(d.mount_point()))
.max_by_key(|d| d.mount_point().as_os_str().len())
- .map(|d| (d.total_space(), d.total_space() - d.available_space()))
+ .map(|d| sized(d.total_space(), d.available_space()))
.unwrap_or((0, 0))
}
}
+/// Sizes at or above this are "unlimited" sentinels, not sizes (gVisor's
+/// root overlay reports `MaxInt64` bytes; no volume holds an exbibyte).
+const SIZE_SENTINEL_FLOOR: u64 = 1 << 60;
+
+/// `(total, used)` from a file system's size and free bytes. One with no
+/// size of its own (gVisor's root overlay) reports total 0, the contract's
+/// "no size", and what it holds as used: never the sentinel.
+fn sized(total: u64, free: u64) -> (u64, u64) {
+ let used = total.saturating_sub(free);
+ if total >= SIZE_SENTINEL_FLOOR {
+ (0, if used >= SIZE_SENTINEL_FLOOR { 0 } else { used })
+ } else {
+ (total, used)
+ }
+}
+
async fn run_power_command(mode: ShutdownMode) {
let args: &[&str] = match (mode, cfg!(windows)) {
(ShutdownMode::GuestPoweroff, false) => &["shutdown", "-h", "now"],
@@ -1336,3 +1353,24 @@ fn cpu_usage() -> (u32, f64) {
}
(s.system.cpus().len() as u32, s.last.unwrap_or(0.0))
}
+
+#[cfg(test)]
+mod sized_tests {
+ use super::sized;
+
+ #[test]
+ fn a_file_system_with_no_size_reports_none_never_the_sentinel() {
+ // gVisor's root overlay: MaxInt64 rounded down to a page.
+ let total = (i64::MAX as u64) & !4095;
+ assert_eq!(sized(total, total - 241_664), (0, 241_664));
+ assert_eq!(sized(i64::MAX as u64, i64::MAX as u64), (0, 0));
+ assert_eq!(sized(u64::MAX, 0), (0, 0));
+ }
+
+ #[test]
+ fn a_real_disk_reports_its_size() {
+ let gib = 1u64 << 30;
+ assert_eq!(sized(64 * gib, 40 * gib), (64 * gib, 24 * gib));
+ assert_eq!(sized(0, 0), (0, 0));
+ }
+}
diff --git a/libs/cua/crates/cua-cli/src/resources_view.rs b/libs/cua/crates/cua-cli/src/resources_view.rs
index 9fcbe2925f..418ab6a5d5 100644
--- a/libs/cua/crates/cua-cli/src/resources_view.rs
+++ b/libs/cua/crates/cua-cli/src/resources_view.rs
@@ -312,6 +312,7 @@ mod tests {
allocated: 87 * GIB,
shares_space: true,
}),
+ base: None,
}],
computers: vec![ComputerResources {
id: "mini1234".into(),
diff --git a/libs/cua/crates/cua-sdk/src/native/spaces_resources.rs b/libs/cua/crates/cua-sdk/src/native/spaces_resources.rs
index 26873ab5ef..2b80be9c2f 100644
--- a/libs/cua/crates/cua-sdk/src/native/spaces_resources.rs
+++ b/libs/cua/crates/cua-sdk/src/native/spaces_resources.rs
@@ -96,8 +96,9 @@ pub struct GuestUsage {
pub memory_limited: bool,
/// Disk in use, bytes.
pub disk_used: u64,
- /// Disk size, bytes.
- pub disk_total: u64,
+ /// Disk size, bytes; absent when the guest's file system has no size
+ /// of its own (gVisor's root overlay) or did not say. Never a sentinel.
+ pub disk_total: Option<u64>,
/// `disk_total` is the guest's own disk.
pub disk_limited: bool,
}
@@ -132,8 +133,30 @@ pub struct SpaceResources {
pub disk_allocated: u64,
/// The guest's own numbers; absent while it is off or unreachable.
pub usage: Option<GuestUsage>,
- /// What it costs this Mac; absent for a container.
+ /// What it costs this Mac: its own data only, never the base it
+ /// shares; absent when there is nothing to measure.
pub disk_on_host: Option<DiskOnHost>,
+ /// The base image it is a copy-on-write copy of, counted once for all
+ /// the Spaces that share it; absent when it has none or the runtime
+ /// cannot tell it apart.
+ #[serde(default)]
+ pub base: Option<SharedBase>,
+}
+
+/// A base image several Spaces share copy-on-write (a container image's
+/// layers, the image a VM disk was cloned from).
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SharedBase {
+ /// Which base: Spaces with the same key share the same blocks.
+ pub key: String,
+ /// The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ pub image: String,
+ /// What it takes on this computer, once for all its Spaces; absent when
+ /// the runtime cannot tell it apart from the Spaces' own data.
+ pub bytes: Option<u64>,
+ /// Local Spaces that use it, this one included.
+ pub shared_with: u32,
}
/// One sample of everything.
@@ -462,6 +485,7 @@ mod resources_tests {
allocated: 31 << 30,
shares_space: true,
}),
+ base: None,
}],
computers: vec![],
warning,
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/stream-section.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/stream-section.json
index da717ba3e2..718d169a96 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/stream-section.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/stream-section.json
@@ -7,7 +7,7 @@
"Desktop (1280×800)"
],
"rows": [
- "desktop desktop | Desktop (1280×800) | 1280×800 | os os-ubuntu | pip pip.enter: Picture in picture"
+ "desktop desktop | Desktop | 1280×800 | os os-ubuntu | pip pip.enter: Picture in picture"
],
"statusText": "Looking for this Space’s windows…"
},
@@ -20,7 +20,7 @@
"Quarterly planning notes for the Spaces launch, draft 7 (unsaved changes) - gedit"
],
"rows": [
- "desktop desktop | Desktop (1280×800) | 1280×800 | os os-ubuntu | pip pip.enter: Picture in picture",
+ "desktop desktop | Desktop | 1280×800 | os os-ubuntu | pip pip.enter: Picture in picture",
"window w-1 | Mozilla Firefox | - | app Firefox firefox 812 | pip pip.enter: Picture in picture",
"window w-2 | xterm | - | app xterm xterm 904 | pip pip.exit: Close picture in picture (on)",
"window w-3 | Quarterly planning notes for the Spaces launch, draft 7 (unsaved changes) - gedit | - | app gedit org.gnome.gedit 0 | pip pip.enter: Picture in picture"
@@ -45,7 +45,7 @@
"Desktop (1920×1080)"
],
"rows": [
- "desktop desktop | Desktop (1920×1080) | 1920×1080 | os os-windows | pip pip.enter: Picture in picture"
+ "desktop desktop | Desktop | 1920×1080 | os os-windows | pip pip.enter: Picture in picture"
],
"statusText": "No windows: the Space’s window host is not up."
},
@@ -55,7 +55,7 @@
"Desktop (1024×768)"
],
"rows": [
- "desktop desktop | Desktop (1024×768) | 1024×768 | os os-arch | pip pip.enter: Picture in picture"
+ "desktop desktop | Desktop | 1024×768 | os os-arch | pip pip.enter: Picture in picture"
],
"statusText": "No open windows in this Space yet."
},
@@ -65,7 +65,7 @@
"Desktop (1280×800)"
],
"rows": [
- "desktop desktop | Desktop (1280×800) | 1280×800 | os os-linux | pip pip.enter: Picture in picture"
+ "desktop desktop | Desktop | 1280×800 | os os-linux | pip pip.enter: Picture in picture"
],
"statusText": "No windows match your filter."
},
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index c9bb416da2..98e26a70dc 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -577,6 +577,9 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
"resources.view" => out(resources::view(&a.get("snapshot")?, a.get("nowMs")?)),
"resources.thisMac" => out(resources::this_mac_view(&a.get("computer")?)),
"resources.space" => out(resources::space_view(&a.get("space")?)),
+ // A Space's resources dialog: its three cards and how it fits on
+ // its computer, each base image counted once.
+ "resources.spacePanel" => out(resources::space_panel(&a.get("input")?)),
"resources.computer" => out(resources::computer_view(
&a.get("computer")?,
a.get("nowMs")?,
diff --git a/libs/cua/crates/cua-spaces-app-core/src/resources.rs b/libs/cua/crates/cua-spaces-app-core/src/resources.rs
index 38e4389d3b..0d06538799 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/resources.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/resources.rs
@@ -125,12 +125,29 @@ pub struct GuestUsage {
pub memory_limited: bool,
/// Disk in use, bytes.
pub disk_used: u64,
- /// Disk size, bytes.
- pub disk_total: u64,
+ /// Disk size, bytes; none when the guest's file system has no size of
+ /// its own. A sentinel (`i64::MAX`, `u64::MAX`, -1) or 0 reads as none
+ /// ([`known_size`]), so no shell ever shows one.
+ #[serde(deserialize_with = "de_known_size")]
+ pub disk_total: Option<u64>,
/// `disk_total` is the guest's own disk.
pub disk_limited: bool,
}
+/// Sizes at or above this are "unlimited" or "unknown" sentinels, never
+/// sizes (no volume holds an exbibyte).
+pub const SIZE_SENTINEL_FLOOR: u64 = 1 << 60;
+
+/// A size, or none when it is 0 or a sentinel.
+pub fn known_size(bytes: u64) -> Option<u64> {
+ (bytes > 0 && bytes < SIZE_SENTINEL_FLOOR).then_some(bytes)
+}
+
+fn de_known_size<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
+ let v = Option::<serde_json::Number>::deserialize(d)?;
+ Ok(v.and_then(|n| n.as_u64()).and_then(known_size))
+}
+
/// What a Space costs this Mac's disk.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -159,8 +176,25 @@ pub struct SpaceResources {
pub disk_allocated: u64,
/// The guest's own numbers; none while it is off or unreachable.
pub usage: Option<GuestUsage>,
- /// What it costs this Mac; none for a container.
+ /// What it costs this Mac: its own data only, never the base it shares.
pub disk_on_host: Option<DiskOnHost>,
+ /// The base image it is a copy-on-write copy of, counted once.
+ pub base: Option<SharedBase>,
+}
+
+/// A base image several Spaces share copy-on-write.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SharedBase {
+ /// Spaces with the same key share the same blocks.
+ pub key: String,
+ /// The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ pub image: String,
+ /// What it takes on this Mac, once; none when the runtime cannot tell
+ /// it apart from the Spaces' own data.
+ pub bytes: Option<u64>,
+ /// Local Spaces that use it, this one included.
+ pub shared_with: u32,
}
/// One sample of everything (`Spaces.resources`).
@@ -463,23 +497,39 @@ pub fn space_view(s: &SpaceResources) -> SpaceResourcesView {
None => row(MEMORY, format_size(memory), None, ResourceTone::Normal),
});
}
- let disk = if s.disk_allocated > 0 {
- s.disk_allocated
- } else {
+ // Space for files: what the Space itself holds on this Mac (never the
+ // base image it shares) of the size it was given. A file system with
+ // no size of its own has no total: only what it holds.
+ let disk = known_size(s.disk_allocated).or_else(|| {
usage
.filter(|u| u.disk_limited)
- .map(|u| u.disk_total)
- .unwrap_or(0)
- };
- if disk > 0 {
- rows.push(row(
+ .and_then(|u| u.disk_total)
+ .and_then(known_size)
+ });
+ let own = s.disk_on_host.and_then(|d| d.bytes).or_else(|| {
+ // Not measured on this Mac: what the guest says it holds, only when
+ // that is its own data alone (an overlay with no size of its own; a
+ // VM's guest counts its base system too).
+ usage
+ .filter(|u| !u.disk_limited && u.disk_total.is_none())
+ .map(|u| u.disk_used)
+ .filter(|b| *b < SIZE_SENTINEL_FLOOR)
+ });
+ match (own, disk) {
+ (Some(b), Some(d)) => rows.push(row(
FILES,
- format!("up to {}", format_size(disk)),
- usage
- .filter(|u| u.disk_limited)
- .and_then(|u| fraction(u.disk_used, u.disk_total)),
+ of_text(b, d),
+ fraction(b, d),
ResourceTone::Normal,
- ));
+ )),
+ (Some(b), None) => rows.push(row(FILES, format_size(b), None, ResourceTone::Normal)),
+ (None, Some(d)) => rows.push(row(
+ FILES,
+ format!("up to {}", format_size(d)),
+ None,
+ ResourceTone::Normal,
+ )),
+ (None, None) => {}
}
let on_this_mac = s.disk_on_host.as_ref().and_then(on_this_mac_text);
@@ -503,6 +553,322 @@ pub fn space_view(s: &SpaceResources) -> SpaceResourcesView {
}
}
+/// What one piece of "How it fits on this Mac" is.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum DiskFitKind {
+ /// Everything on the volume that is not a Space: your own files and apps.
+ Yours,
+ /// This Space's own data.
+ ThisSpace,
+ /// Every other Space's own data, together.
+ OtherSpaces,
+ /// A base image Spaces share, counted once.
+ Base,
+ /// Free space.
+ Free,
+}
+
+/// One piece of the bar and its legend entry.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DiskFitPart {
+ /// Stable key (`yours`, `space`, `others`, `free`, a base's key).
+ pub key: String,
+ /// What it is.
+ pub kind: DiskFitKind,
+ /// "Your own files and apps", the Space's name, "Ubuntu 24.04 image".
+ pub label: String,
+ /// Its size in words ("4.4 GB").
+ pub value: String,
+ /// More words, for a base: "shared by 3 Spaces", "only this Space uses
+ /// it".
+ pub detail: Option<String>,
+ /// Bytes, for the bar.
+ pub bytes: u64,
+ /// Its share of the bar, 0 to 1; the parts add up to 1.
+ pub fraction: f64,
+}
+
+/// "How it fits on this Mac": the volume's pieces, each counted once.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DiskFitView {
+ /// The volume's size in words ("2 TB").
+ pub total: String,
+ /// Your own files and apps, this Space, other Spaces, shared bases,
+ /// free: they add up to the volume.
+ pub parts: Vec<DiskFitPart>,
+ /// What could not be told apart, in plain words; none when everything
+ /// was measured.
+ pub note: Option<String>,
+ /// The low-disk warning, when it is true.
+ pub warning: Option<WarningView>,
+}
+
+/// An image reference as a name: `ghcr.io/trycua/linux:24.04` is
+/// "linux 24.04".
+pub fn image_name(reference: &str) -> String {
+ let r = reference.split('@').next().unwrap_or(reference);
+ let last = r.rsplit('/').next().unwrap_or(r);
+ last.replacen(':', " ", 1)
+}
+
+/// "How it fits on this Mac" for Space `this` (named `name`) among the
+/// computer's `spaces` (this one included or not). `base_name` names this
+/// Space's base ("Ubuntu 24.04"); other bases are named from their image.
+pub fn disk_fit(
+ host: &ComputerResources,
+ this: &SpaceResources,
+ name: &str,
+ spaces: &[SpaceResources],
+ base_name: Option<&str>,
+) -> DiskFitView {
+ let total = host.disk_total;
+ let free = host.disk_free.min(total);
+ let used = total - free;
+ let own = |s: &SpaceResources| s.disk_on_host.and_then(|d| d.bytes);
+ let this_own = own(this);
+ let others: u64 = spaces
+ .iter()
+ .filter(|s| s.id != this.id)
+ .filter_map(own)
+ .sum();
+ // Each base once, in the order the Spaces come (this Space's first).
+ let mut bases: Vec<&SharedBase> = Vec::new();
+ for b in std::iter::once(this)
+ .chain(spaces.iter().filter(|s| s.id != this.id))
+ .filter_map(|s| s.base.as_ref())
+ {
+ if !bases.iter().any(|o| o.key == b.key) {
+ bases.push(b);
+ }
+ }
+ let known_bases: u64 = bases.iter().filter_map(|b| b.bytes).sum();
+ let counted = this_own
+ .unwrap_or(0)
+ .saturating_add(others)
+ .saturating_add(known_bases);
+ let yours = used.saturating_sub(counted);
+ // Measurements a little off never make the parts overflow the bar.
+ let whole = total
+ .max(counted.saturating_add(yours).saturating_add(free))
+ .max(1);
+ let part = |key: &str, kind, label: String, detail: Option<String>, bytes: u64| DiskFitPart {
+ key: key.into(),
+ kind,
+ label,
+ value: format_size(bytes),
+ detail,
+ bytes,
+ fraction: bytes as f64 / whole as f64,
+ };
+ let mut parts = vec![part(
+ "yours",
+ DiskFitKind::Yours,
+ "Your own files and apps".into(),
+ None,
+ yours,
+ )];
+ if let Some(b) = this_own {
+ parts.push(part("space", DiskFitKind::ThisSpace, name.into(), None, b));
+ }
+ if others > 0 {
+ parts.push(part(
+ "others",
+ DiskFitKind::OtherSpaces,
+ "Other Spaces".into(),
+ None,
+ others,
+ ));
+ }
+ let mut note = this_own
+ .is_none()
+ .then(|| format!("Can't tell {name}'s own data apart from the image it shares."));
+ for b in &bases {
+ let label = match base_name.filter(|_| this.base.as_ref().is_some_and(|t| t.key == b.key)) {
+ Some(n) => format!("{n} image"),
+ None => format!("{} image", image_name(&b.image)),
+ };
+ let mine = this.base.as_ref().is_some_and(|t| t.key == b.key);
+ let detail = match (b.shared_with, mine) {
+ (0 | 1, true) => "only this Space uses it".to_string(),
+ (n, true) => format!("shared by {n} Spaces"),
+ (n, false) => format!("used by {n} Space{}", if n == 1 { "" } else { "s" }),
+ };
+ match b.bytes {
+ Some(bytes) => parts.push(part(&b.key, DiskFitKind::Base, label, Some(detail), bytes)),
+ None if mine && note.is_none() => {
+ note = Some(format!("Can't tell how much the shared {label} takes."));
+ }
+ None => {}
+ }
+ }
+ parts.push(part("free", DiskFitKind::Free, "Free".into(), None, free));
+ DiskFitView {
+ total: format_size(total),
+ parts,
+ note,
+ warning: warning_view(&host.warning),
+ }
+}
+
+/// One card of a Space's resources dialog: the label, the main number,
+/// the one "Given ..." line and the bar. No explanatory sentences.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SpacePanelCard {
+ /// "Processor", "Memory" or "Space for files".
+ pub label: String,
+ /// The main number: "13% busy", "717 MB of 4 GB", "244 KB".
+ pub value: String,
+ /// "Given 2 of this Mac's 18 cores"; none when there is nothing given
+ /// to say.
+ pub given: Option<String>,
+ /// The bar, 0 to 1; none for a card with nothing to fill it against.
+ pub fraction: Option<f64>,
+}
+
+/// A Space's resources dialog: the three cards and how it fits.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SpacePanelView {
+ /// Processor, Memory, Space for files.
+ pub cards: Vec<SpacePanelCard>,
+ /// "How it fits on this Mac"; none without the computer's numbers.
+ pub fit: Option<DiskFitView>,
+}
+
+/// What a Space's resources dialog reads.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SpacePanelInput {
+ /// The Space's numbers.
+ pub space: SpaceResources,
+ /// Its name ("pipbox").
+ pub name: String,
+ /// Its computer's numbers, when it sent them.
+ pub host: Option<ComputerResources>,
+ /// "this Mac", or the other computer's name.
+ pub computer: String,
+ /// Every Space on that computer, for how it fits.
+ pub spaces: Vec<SpaceResources>,
+ /// The name of its base image's system ("Ubuntu 24.04"), when known.
+ pub base_name: Option<String>,
+}
+
+/// "this Mac's" / "Studio's".
+fn whose(computer: &str) -> String {
+ format!(
+ "{}\u{2019}s",
+ if computer.is_empty() {
+ "this Mac"
+ } else {
+ computer
+ }
+ )
+}
+
+/// A Space's resources dialog.
+pub fn space_panel(i: &SpacePanelInput) -> SpacePanelView {
+ let s = &i.space;
+ let usage = s.usage.filter(|_| s.power_state == "running");
+ let host = i.host.as_ref();
+ let whose = whose(&i.computer);
+ let cores = |n: u32| format!("{n} core{}", if n == 1 { "" } else { "s" });
+
+ let cpu_given = (s.cpu_allocated > 0).then(|| match host.filter(|h| h.cpu_count > 0) {
+ Some(h) => format!(
+ "Given {} of {whose} {}",
+ s.cpu_allocated,
+ cores(h.cpu_count)
+ ),
+ None => format!("Given {}", cores(s.cpu_allocated)),
+ });
+ let processor = SpacePanelCard {
+ label: PROCESSOR.into(),
+ value: match usage {
+ Some(u) => format!("{}% busy", u.cpu_percent.round().clamp(0.0, 100.0)),
+ None => "Stopped".into(),
+ },
+ given: cpu_given,
+ fraction: Some(
+ usage
+ .map(|u| (u.cpu_percent / 100.0).clamp(0.0, 1.0))
+ .unwrap_or(0.0),
+ ),
+ };
+
+ let mem_total = if s.memory_allocated > 0 {
+ s.memory_allocated
+ } else {
+ usage
+ .filter(|u| u.memory_limited)
+ .map(|u| u.memory_total)
+ .unwrap_or(0)
+ };
+ let mem_given = (s.memory_allocated > 0).then(|| match host.filter(|h| h.memory_total > 0) {
+ Some(h) => format!(
+ "Given {} of {whose} {}",
+ format_size(s.memory_allocated),
+ format_size(h.memory_total)
+ ),
+ None => format!("Given {}", format_size(s.memory_allocated)),
+ });
+ let memory = SpacePanelCard {
+ label: MEMORY.into(),
+ value: match usage {
+ Some(u) if mem_total > 0 => of_text(u.memory_used, mem_total),
+ Some(u) => format_size(u.memory_used),
+ None => "Off".into(),
+ },
+ given: mem_given,
+ fraction: Some(
+ usage
+ .and_then(|u| fraction(u.memory_used, mem_total))
+ .unwrap_or(0.0),
+ ),
+ };
+
+ // Space for files: what the Space itself holds on its computer (never
+ // the base image it shares, which "How it fits" counts once), of the
+ // size it was given. With no size of its own, only what it holds.
+ let size = known_size(s.disk_allocated).or_else(|| {
+ usage
+ .filter(|u| u.disk_limited)
+ .and_then(|u| u.disk_total)
+ .and_then(known_size)
+ });
+ let own = s.disk_on_host.and_then(|d| d.bytes).or_else(|| {
+ usage
+ .filter(|u| !u.disk_limited && u.disk_total.is_none())
+ .map(|u| u.disk_used)
+ .filter(|b| *b < SIZE_SENTINEL_FLOOR)
+ });
+ let files = SpacePanelCard {
+ label: FILES.into(),
+ value: match (own, size) {
+ (Some(b), Some(d)) => of_text(b, d),
+ (Some(b), None) => format_size(b),
+ (None, Some(d)) => format!("Up to {}", format_size(d)),
+ (None, None) => "\u{2014}".into(),
+ },
+ // The size it was given is already in the main number.
+ given: None,
+ fraction: match (own, size) {
+ (Some(b), Some(d)) => fraction(b, d),
+ _ => None,
+ },
+ };
+
+ SpacePanelView {
+ cards: vec![processor, memory, files],
+ fit: host
+ .filter(|h| h.disk_total > 0)
+ .map(|h| disk_fit(h, s, &i.name, &i.spaces, i.base_name.as_deref())),
+ }
+}
+
fn lowercase_first(s: &str) -> String {
let mut c = s.chars();
match c.next() {
@@ -603,7 +969,7 @@ mod tests {
memory_total: 8 * GIB,
memory_limited: true,
disk_used: 20 * GIB,
- disk_total: 80 * GIB,
+ disk_total: Some(80 * GIB),
disk_limited: true,
..Default::default()
}),
@@ -612,6 +978,7 @@ mod tests {
allocated: 87 * GIB,
shares_space: true,
}),
+ base: None,
}
}
@@ -685,11 +1052,12 @@ mod tests {
"4 cores \u{b7} 22% busy".to_string()
),
("Memory".to_string(), "3.1 of 8 GB".to_string()),
- ("Space for files".to_string(), "up to 80 GB".to_string()),
+ // Its own data on this Mac, of the size it was given.
+ ("Space for files".to_string(), "31 of 80 GB".to_string()),
]
);
assert_eq!(v.rows[0].fraction, Some(0.22));
- assert_eq!(v.rows[2].fraction, Some(0.25));
+ assert_eq!(v.rows[2].fraction, Some(31.0 / 80.0));
assert_eq!(
v.on_this_mac.as_deref(),
Some("Uses about 31 GB on this Mac (shares space with other copies)")
@@ -716,10 +1084,11 @@ mod tests {
[
("Processor".to_string(), "4 cores".to_string()),
("Memory".to_string(), "8 GB".to_string()),
- ("Space for files".to_string(), "up to 80 GB".to_string()),
+ ("Space for files".to_string(), "6 of 80 GB".to_string()),
]
);
- assert!(v.rows.iter().all(|r| r.fraction.is_none()));
+ assert!(v.rows[..2].iter().all(|r| r.fraction.is_none()));
+ assert_eq!(v.rows[2].fraction, Some(6.0 / 80.0));
assert_eq!(
v.on_this_mac.as_deref(),
Some("Uses about 6 GB on this Mac")
@@ -783,7 +1152,7 @@ mod tests {
let v = space_view(&s);
assert_eq!(v.rows[0].value, "4 cores \u{b7} 22% busy");
assert_eq!(v.rows[1].value, "3.1 of 8 GB");
- assert_eq!(v.rows[2].value, "up to 80 GB");
+ assert_eq!(v.rows[2].value, "31 of 80 GB");
}
#[test]
@@ -864,4 +1233,386 @@ mod tests {
assert!(!text.contains(jargon), "{jargon} in {text}");
}
}
+
+ /// A running Ubuntu container under gVisor: no size of its own.
+ fn container(json_disk_total: &str) -> SpaceResources {
+ serde_json::from_str(&format!(
+ r#"{{"id":"local:pipbox","powerState":"running","cpuAllocated":2,"memoryAllocated":{mem},
+ "diskAllocated":0,
+ "usage":{{"cpuCount":2,"cpuPercent":13,"memoryUsed":751619276,"memoryTotal":{mem},
+ "memoryLimited":true,"diskUsed":249856,"diskTotal":{json_disk_total},"diskLimited":false}},
+ "diskOnHost":{{"bytes":249856,"allocated":249856,"sharesSpace":false}},
+ "base":{{"key":"sha256:9ac0","image":"ghcr.io/trycua/linux:24.04","bytes":4410000000,"sharedWith":1}}}}"#,
+ mem = 4 * GIB
+ ))
+ .unwrap()
+ }
+
+ #[test]
+ fn a_sentinel_size_never_reaches_a_row() {
+ for sentinel in [
+ "9223372036854775807", // i64::MAX
+ "9223372036854771712", // gVisor: i64::MAX to a page
+ "18446744073709551615", // u64::MAX
+ "-1",
+ "0",
+ "null",
+ ] {
+ let s = container(sentinel);
+ assert_eq!(s.usage.unwrap().disk_total, None, "{sentinel}");
+ let v = space_view(&s);
+ let files = v.rows.iter().find(|r| r.label == FILES).unwrap();
+ // Only what it holds: no fake total, never "0 GB".
+ assert_eq!(files.value, "244 KB", "{sentinel}");
+ assert_eq!(files.fraction, None);
+ for r in &v.rows {
+ assert!(!r.value.contains("PB") && !r.value.contains("TB"), "{r:?}");
+ }
+ }
+ assert_eq!(known_size(i64::MAX as u64), None);
+ assert_eq!(known_size(u64::MAX), None);
+ assert_eq!(known_size(0), None);
+ assert_eq!(known_size(80 * GIB), Some(80 * GIB));
+ }
+
+ #[test]
+ fn memory_reads_the_way_macos_shows_it() {
+ // Given 4 GiB of a 36 GiB Mac: "4 GB" and "36 GB", never 4.3 and 39.
+ let s = container("0");
+ let v = space_view(&s);
+ assert_eq!(
+ v.rows.iter().find(|r| r.label == MEMORY).unwrap().value,
+ "717 MB of 4 GB"
+ );
+ assert_eq!(format_size(36 * GIB), "36 GB");
+ assert_eq!(format_size(500 * (1 << 20)), "500 MB");
+ }
+
+ fn host(free: u64) -> ComputerResources {
+ ComputerResources {
+ disk_total: 2 * TB,
+ disk_free: free,
+ ..mac()
+ }
+ }
+
+ fn total(v: &DiskFitView) -> f64 {
+ v.parts.iter().map(|p| p.fraction).sum()
+ }
+
+ #[test]
+ fn the_fit_counts_a_copy_on_write_base_once() {
+ let this = container("0");
+ let twin = SpaceResources {
+ id: "local:twin".into(),
+ disk_on_host: Some(DiskOnHost {
+ bytes: Some(2 * GIB),
+ allocated: 2 * GIB,
+ shares_space: false,
+ }),
+ base: this.base.clone().map(|b| SharedBase {
+ shared_with: 2,
+ ..b
+ }),
+ ..this.clone()
+ };
+ let this = SpaceResources {
+ base: twin.base.clone(),
+ ..this
+ };
+ let free = 6 * GIB;
+ let v = disk_fit(
+ &host(free),
+ &this,
+ "pipbox",
+ &[this.clone(), twin],
+ Some("Ubuntu 24.04"),
+ );
+ let kinds: Vec<_> = v.parts.iter().map(|p| (p.kind, p.label.as_str())).collect();
+ assert_eq!(
+ kinds,
+ [
+ (DiskFitKind::Yours, "Your own files and apps"),
+ (DiskFitKind::ThisSpace, "pipbox"),
+ (DiskFitKind::OtherSpaces, "Other Spaces"),
+ (DiskFitKind::Base, "Ubuntu 24.04 image"),
+ (DiskFitKind::Free, "Free"),
+ ]
+ );
+ let base = &v.parts[3];
+ assert_eq!(base.detail.as_deref(), Some("shared by 2 Spaces"));
+ assert_eq!(base.bytes, 4_410_000_000);
+ assert_eq!(v.parts[1].value, "244 KB");
+ // Used + this Space + others + the base once + free = the volume.
+ let sum: u64 = v.parts.iter().map(|p| p.bytes).sum();
+ assert_eq!(sum, 2 * TB);
+ assert!((total(&v) - 1.0).abs() < 1e-9);
+ assert_eq!(v.total, "2 TB");
+ assert_eq!(v.note, None);
+ assert!(v.warning.is_some(), "this Mac is low: the warning stays");
+ }
+
+ #[test]
+ fn the_last_user_of_a_base_says_so() {
+ let this = container("0");
+ let v = disk_fit(
+ &host(100 * GIB),
+ &this,
+ "pipbox",
+ std::slice::from_ref(&this),
+ None,
+ );
+ let base = v
+ .parts
+ .iter()
+ .find(|p| p.kind == DiskFitKind::Base)
+ .unwrap();
+ assert_eq!(base.label, "linux 24.04 image");
+ assert_eq!(base.detail.as_deref(), Some("only this Space uses it"));
+ assert!(v.parts.iter().all(|p| p.kind != DiskFitKind::OtherSpaces));
+ }
+
+ #[test]
+ fn a_space_with_no_base_is_its_own_data_only() {
+ let this = SpaceResources {
+ base: None,
+ ..space()
+ };
+ let v = disk_fit(
+ &host(100 * GIB),
+ &this,
+ "aurora",
+ std::slice::from_ref(&this),
+ None,
+ );
+ assert!(v.parts.iter().all(|p| p.kind != DiskFitKind::Base));
+ assert_eq!(v.parts[1].bytes, 31 * GIB);
+ let sum: u64 = v.parts.iter().map(|p| p.bytes).sum();
+ assert_eq!(sum, 2 * TB);
+ }
+
+ #[test]
+ fn what_cannot_be_told_apart_is_said_plainly() {
+ let this = SpaceResources {
+ disk_on_host: Some(DiskOnHost {
+ bytes: None,
+ allocated: 40 * GIB,
+ shares_space: true,
+ }),
+ base: Some(SharedBase {
+ key: "macos".into(),
+ image: "ghcr.io/trycua/macos:26".into(),
+ bytes: None,
+ shared_with: 1,
+ }),
+ ..space()
+ };
+ let v = disk_fit(
+ &host(100 * GIB),
+ &this,
+ "aurora",
+ std::slice::from_ref(&this),
+ None,
+ );
+ assert_eq!(
+ v.note.as_deref(),
+ Some("Can't tell aurora's own data apart from the image it shares.")
+ );
+ // Nothing guessed: no part for it.
+ assert!(
+ v.parts
+ .iter()
+ .all(|p| p.kind != DiskFitKind::ThisSpace && p.kind != DiskFitKind::Base)
+ );
+ let base_only = SpaceResources {
+ disk_on_host: Some(DiskOnHost {
+ bytes: Some(GIB),
+ allocated: 40 * GIB,
+ shares_space: true,
+ }),
+ ..this
+ };
+ let v = disk_fit(
+ &host(100 * GIB),
+ &base_only,
+ "aurora",
+ std::slice::from_ref(&base_only),
+ None,
+ );
+ assert_eq!(
+ v.note.as_deref(),
+ Some("Can't tell how much the shared macos 26 image takes.")
+ );
+ }
+
+ #[test]
+ fn measurements_a_little_off_never_overflow_the_bar() {
+ let mut this = container("0");
+ this.disk_on_host = Some(DiskOnHost {
+ bytes: Some(3 * TB),
+ allocated: 3 * TB,
+ shares_space: false,
+ });
+ let v = disk_fit(
+ &host(GIB),
+ &this,
+ "pipbox",
+ std::slice::from_ref(&this),
+ None,
+ );
+ assert_eq!(v.parts[0].bytes, 0);
+ assert!((total(&v) - 1.0).abs() < 1e-9);
+ }
+
+ /// The owner's Mac: 18 cores, 36 GiB, a 2 TB disk with 5.6 GB free.
+ fn owners_mac() -> ComputerResources {
+ ComputerResources {
+ cpu_count: 18,
+ memory_total: 36 * GIB,
+ disk_total: 2_000_000_000_000,
+ disk_free: 5_600_000_000,
+ warning: DiskWarning {
+ level: DiskLevel::Critical,
+ free: 5_600_000_000,
+ total: 2_000_000_000_000,
+ threshold: 5 * GIB,
+ },
+ ..mac()
+ }
+ }
+
+ fn panel(s: SpaceResources) -> SpacePanelView {
+ space_panel(&SpacePanelInput {
+ spaces: vec![s.clone()],
+ space: s,
+ name: "pipbox".into(),
+ host: Some(owners_mac()),
+ computer: "this Mac".into(),
+ base_name: Some("Ubuntu 24.04".into()),
+ })
+ }
+
+ fn cards(v: &SpacePanelView) -> Vec<(String, String, Option<String>)> {
+ v.cards
+ .iter()
+ .map(|c| (c.label.clone(), c.value.clone(), c.given.clone()))
+ .collect()
+ }
+
+ #[test]
+ fn the_resources_dialog_of_a_gvisor_container() {
+ for sentinel in [
+ "9223372036854771712",
+ "9223372036854775807",
+ "18446744073709551615",
+ "-1",
+ "0",
+ ] {
+ let v = panel(container(sentinel));
+ assert_eq!(
+ cards(&v),
+ [
+ (
+ "Processor".to_string(),
+ "13% busy".to_string(),
+ Some("Given 2 of this Mac\u{2019}s 18 cores".to_string())
+ ),
+ (
+ "Memory".to_string(),
+ "717 MB of 4 GB".to_string(),
+ // GiB both sides, labelled the way macOS does.
+ Some("Given 4 GB of this Mac\u{2019}s 36 GB".to_string())
+ ),
+ // Its own data, no fake total, never "0 GB".
+ ("Space for files".to_string(), "244 KB".to_string(), None),
+ ],
+ "{sentinel}"
+ );
+ assert_eq!(v.cards[2].fraction, None);
+ let fit = v.fit.unwrap();
+ assert_eq!(fit.total, "1.8 TB");
+ let legend: Vec<_> = fit
+ .parts
+ .iter()
+ .map(|p| {
+ format!(
+ "{} \u{b7} {}{}",
+ p.label,
+ p.value,
+ p.detail
+ .as_ref()
+ .map(|d| format!(", {d}"))
+ .unwrap_or_default()
+ )
+ })
+ .collect();
+ assert_eq!(
+ legend,
+ [
+ "Your own files and apps \u{b7} 1.8 TB",
+ "pipbox \u{b7} 244 KB",
+ "Ubuntu 24.04 image \u{b7} 4.1 GB, only this Space uses it",
+ "Free \u{b7} 5.2 GB",
+ ]
+ );
+ let sum: u64 = fit.parts.iter().map(|p| p.bytes).sum();
+ assert_eq!(sum, 2_000_000_000_000);
+ // This Mac really is nearly full: the warning stays.
+ assert!(fit.warning.unwrap().critical);
+ }
+ }
+
+ #[test]
+ fn the_resources_dialog_of_a_stopped_vm() {
+ let s = SpaceResources {
+ power_state: "stopped".into(),
+ usage: None,
+ ..space()
+ };
+ let v = space_panel(&SpacePanelInput {
+ spaces: vec![s.clone()],
+ space: s,
+ name: "aurora".into(),
+ host: None,
+ computer: "this Mac".into(),
+ base_name: None,
+ });
+ assert_eq!(
+ cards(&v),
+ [
+ (
+ "Processor".to_string(),
+ "Stopped".to_string(),
+ Some("Given 4 cores".to_string())
+ ),
+ (
+ "Memory".to_string(),
+ "Off".to_string(),
+ Some("Given 8 GB".to_string())
+ ),
+ (
+ "Space for files".to_string(),
+ "31 of 80 GB".to_string(),
+ None
+ ),
+ ]
+ );
+ assert_eq!(v.fit, None);
+ }
+
+ #[test]
+ fn the_dialog_never_says_more_than_the_numbers() {
+ let v = panel(container("0"));
+ let all = serde_json::to_string(&v).unwrap();
+ for banned in [
+ "Busy means",
+ "free for its apps",
+ "Uses about",
+ "Updates every",
+ "file names",
+ "9223372",
+ ] {
+ assert!(!all.contains(banned), "{banned}: {all}");
+ }
+ }
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs
index d2d9960775..80ce105add 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs
@@ -953,7 +953,8 @@ fn detail_facts(
if u.memory_limited && u.memory_total > 0 {
facts.push(fact("Memory", usage_text(u.memory_used, u.memory_total)));
}
- if u.disk_limited && u.disk_total > 0 {
+ // Never a sentinel ("unlimited" as 2^63): only a real size.
+ if u.disk_limited && crate::resources::known_size(u.disk_total).is_some() {
facts.push(fact("Storage", usage_text(u.disk_used, u.disk_total)));
}
}
@@ -1736,6 +1737,36 @@ mod tests {
assert!(hosted_rows(&spaces, "local:a", "").is_empty());
}
+ #[test]
+ fn a_storage_fact_never_shows_a_sentinel() {
+ let space = super::super::row_to_space(
+ &local_row("local:o", Some("ghcr.io/trycua/linux:24.04"), None, None),
+ 0,
+ );
+ for total in [i64::MAX as u64, u64::MAX, 0] {
+ let usage = SpaceUsage {
+ disk_used: 1 << 20,
+ disk_total: total,
+ disk_limited: true,
+ ..Default::default()
+ };
+ let d = detail_live(&space, Some(&usage), None);
+ assert_eq!(fact_of(&d, "Storage"), None, "{total}");
+ }
+ let real = SpaceUsage {
+ disk_used: 2 << 30,
+ disk_total: 4 << 30,
+ disk_limited: true,
+ ..Default::default()
+ };
+ assert_eq!(
+ fact_of(&detail_live(&space, Some(&real), None), "Storage")
+ .unwrap()
+ .value,
+ "2 GB / 4 GB"
+ );
+ }
+
#[test]
fn kind_and_architecture_facts_warn_about_emulation_on_this_mac_only() {
let omarchy = super::super::row_to_space(
diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/stream.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/stream.rs
index 200721cea8..e438725eb2 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/stream.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/stream.rs
@@ -8,8 +8,9 @@
//! - The Desktop row's icon is the Space's OS mark ([`crate::notch::os_icon`]):
//! the label already says "Desktop", so a generic display glyph would say
//! it twice, while the OS mark tells an Ubuntu desktop from a Windows one.
-//! Its label carries the resolution of the Space's primary display
-//! ("Desktop (1280×800)"), from the display list.
+//! Its label is "Desktop"; the resolution of the Space's primary display
+//! ("1280×800", from the display list) is the row's quiet right-hand
+//! detail ([`StreamRow::resolution`]), said once, never in the label too.
//! - A window row's label is the window's title (the app name only when the
//! title is empty) and its icon is the app's own, from the SDK's
//! `Space.app_icon`; a Space with no icon for the app shows none, never a
@@ -126,7 +127,7 @@ pub struct StreamRow {
pub id: String,
/// Desktop or window.
pub kind: StreamRowKind,
- /// The one line ("Desktop (1280×800)", a window's title).
+ /// The one line ("Desktop", a window's title).
pub label: String,
/// The full label, for the tooltip when it is truncated.
pub help: String,
@@ -186,12 +187,12 @@ pub fn stream_section(input: &StreamSectionInput) -> StreamSection {
let resolution = input
.display
.and_then(|d| resolution_text(d.width_px, d.height_px));
- let label = desktop_label(resolution.as_deref());
+ // The resolution shows once, as the row's detail; the tooltip has both.
let mut rows = vec![StreamRow {
id: DESKTOP_ROW_ID.into(),
kind: StreamRowKind::Desktop,
- help: label.clone(),
- label,
+ help: desktop_label(resolution.as_deref()),
+ label: "Desktop".into(),
resolution,
icon: StreamRowIcon::Os {
id: os_icon(input.os, input.os_name.as_deref()).into(),
@@ -391,8 +392,10 @@ mod tests {
fn desktop_row_carries_the_resolution_and_the_os_mark() {
let s = stream_section(&input(Some(vec![])));
let d = &s.rows[0];
- assert_eq!(d.label, "Desktop (1280\u{d7}800)");
+ // Said once: the label is "Desktop", the resolution its detail.
+ assert_eq!(d.label, "Desktop");
assert_eq!(d.resolution.as_deref(), Some("1280\u{d7}800"));
+ assert_eq!(d.help, "Desktop (1280\u{d7}800)");
assert_eq!(
d.icon,
StreamRowIcon::Os {
@@ -417,10 +420,7 @@ mod tests {
i.open = vec!["w2".into()];
let s = stream_section(&i);
let labels: Vec<&str> = s.rows.iter().map(|r| r.label.as_str()).collect();
- assert_eq!(
- labels,
- ["Desktop (1280\u{d7}800)", "Mozilla Firefox", "xterm"]
- );
+ assert_eq!(labels, ["Desktop", "Mozilla Firefox", "xterm"]);
assert_eq!(
s.rows[1].icon,
StreamRowIcon::App {
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index c481e5f7e2..bc4ecb6cb6 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -3475,6 +3475,7 @@ mod resources_tests {
allocated: 87 * GIB,
shares_space: true,
}),
+ base: None,
}],
computers: vec![rt::ComputerResources {
id: "mini".into(),
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 916badf334..99dae7ef08 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -1391,7 +1391,7 @@ pub struct AppStreamRow {
pub id: String,
/// Desktop or window.
pub kind: AppStreamRowKind,
- /// The one line ("Desktop (1280×800)", a window's title).
+ /// The one line ("Desktop", a window's title).
pub label: String,
/// The full label, for the tooltip when it is truncated.
pub help: String,
@@ -11407,8 +11407,10 @@ pub struct AppGuestUsage {
pub memory_limited: bool,
/// Disk in use, bytes.
pub disk_used: u64,
- /// Disk size, bytes.
- pub disk_total: u64,
+ /// Disk size, bytes; none when the guest's file system has no size of
+ /// its own. A sentinel (`i64::MAX`, `u64::MAX`, -1) or 0 reads as none
+ /// ([`known_size`]), so no shell ever shows one.
+ pub disk_total: Option<u64>,
/// `disk_total` is the guest's own disk.
pub disk_limited: bool,
}
@@ -11425,6 +11427,21 @@ pub struct AppDiskOnHost {
pub shares_space: bool,
}
+/// A base image several Spaces share copy-on-write.
+pub type AppSharedBase = core::resources::SharedBase;
+#[uniffi::remote(Record)]
+pub struct AppSharedBase {
+ /// Spaces with the same key share the same blocks.
+ pub key: String,
+ /// The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ pub image: String,
+ /// What it takes on this Mac, once; none when the runtime cannot tell
+ /// it apart from the Spaces' own data.
+ pub bytes: Option<u64>,
+ /// Local Spaces that use it, this one included.
+ pub shared_with: u32,
+}
+
/// One extra Space on this Mac.
pub type AppSpaceResources = core::resources::SpaceResources;
#[uniffi::remote(Record)]
@@ -11441,8 +11458,10 @@ pub struct AppSpaceResources {
pub disk_allocated: u64,
/// The guest's own numbers; none while it is off or unreachable.
pub usage: Option<AppGuestUsage>,
- /// What it costs this Mac; none for a container.
+ /// What it costs this Mac: its own data only, never the base it shares.
pub disk_on_host: Option<AppDiskOnHost>,
+ /// The base image it is a copy-on-write copy of, counted once.
+ pub base: Option<AppSharedBase>,
}
/// One sample of everything (`Spaces.resources`).
diff --git a/libs/cua/crates/cua-spaces/src/resources/disk.rs b/libs/cua/crates/cua-spaces/src/resources/disk.rs
index d540e60717..201063f095 100644
--- a/libs/cua/crates/cua-spaces/src/resources/disk.rs
+++ b/libs/cua/crates/cua-spaces/src/resources/disk.rs
@@ -189,6 +189,71 @@ pub struct Footprint {
/// full (0: not reported). The fallback when [`Footprint::dir`] cannot
/// be read.
pub reported: u64,
+ /// The image reference it was made from (`ghcr.io/trycua/linux:24.04`).
+ pub image: String,
+ /// What identifies that image's blocks: its digest when the state file
+ /// has one, else the reference.
+ pub image_key: String,
+}
+
+/// A Space's base image as measured: which one, and what it takes.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct BaseMeasure {
+ /// Spaces with the same key share the same blocks.
+ pub key: String,
+ /// Bytes it takes; `None` when it cannot be told apart.
+ pub bytes: Option<u64>,
+}
+
+/// The image reference and its key, from a state file's `image` and
+/// `image_info`.
+pub fn image_of(l: &cua_sandbox_core::state::LocalState) -> (String, String) {
+ let info = l.extra.get("image_info");
+ let text = |v: Option<&serde_json::Value>| {
+ v.and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+ };
+ let reference = text(info.and_then(|i| i.get("reference")))
+ .or_else(|| text(l.image.get("registry")))
+ .or_else(|| text(Some(&l.image)))
+ .unwrap_or_default();
+ let key = text(info.and_then(|i| i.get("digest"))).unwrap_or_else(|| reference.clone());
+ (reference, key)
+}
+
+/// What a copy-on-write clone shares with its base: the blocks its files
+/// occupy beyond the ones only it holds. `None` when the private bytes
+/// could not be measured (it cannot tell its own data from the base's).
+pub fn shared_blocks(d: &DiskOnHost) -> Option<u64> {
+ d.bytes.map(|own| d.allocated.saturating_sub(own))
+}
+
+/// A qcow2 file's backing file (the base image it was made from), from its
+/// header: relative names are relative to the file's directory.
+pub fn qcow2_backing_file(path: &Path) -> Option<PathBuf> {
+ use std::io::{Read, Seek, SeekFrom};
+ let mut f = std::fs::File::open(path).ok()?;
+ let mut hdr = [0u8; 24];
+ f.read_exact(&mut hdr).ok()?;
+ if &hdr[..4] != b"QFI\xfb" {
+ return None;
+ }
+ let offset = u64::from_be_bytes(hdr[8..16].try_into().ok()?);
+ let size = u32::from_be_bytes(hdr[16..20].try_into().ok()?) as usize;
+ if offset == 0 || size == 0 || size > 1023 {
+ return None;
+ }
+ f.seek(SeekFrom::Start(offset)).ok()?;
+ let mut name = vec![0u8; size];
+ f.read_exact(&mut name).ok()?;
+ let name = PathBuf::from(String::from_utf8(name).ok()?);
+ Some(if name.is_absolute() {
+ name
+ } else {
+ path.parent()?.join(name)
+ })
}
/// What `lume serve` says about one VM.
@@ -245,7 +310,10 @@ pub fn footprints(
runtime: l.runtime_type.clone(),
dir: None,
engine: false,
+ image: String::new(),
+ image_key: String::new(),
};
+ (f.image, f.image_key) = image_of(&l);
match l.runtime_type.as_str() {
"gvisor" | "runsc" | "container" | "docker" | "runc" | "managed"
| "qemu-docker" | "qemu_docker" => f.engine = true,
@@ -326,6 +394,24 @@ pub fn container_volumes(
out
}
+/// The image Space `name`'s own container runs, for its shared base.
+pub fn container_image<'a>(
+ name: &str,
+ home_tag: &str,
+ containers: &'a [cua_disk::docker::DockerContainer],
+) -> Option<&'a str> {
+ containers
+ .iter()
+ .find(|c| {
+ c.name == name
+ && c.labels
+ .get(cua_disk::docker::LABEL_HOME)
+ .is_none_or(|h| h == home_tag)
+ })
+ .map(|c| c.image_id.as_str())
+ .filter(|id| !id.is_empty())
+}
+
/// What container Space `name` costs: the writable layers of its
/// containers plus the anonymous volumes they mount (what deleting it
/// frees). Its image's layers are shared and not counted, nor are named
@@ -356,6 +442,39 @@ pub fn container_disk(
})
}
+/// Each Space's shared base, from what was measured of it (`image`, the
+/// reference it came from, and the measure, by Space): Spaces with the same
+/// key share one base, counted once. Its bytes are the largest any of them
+/// measured (a clone that shares fewer blocks has changed more of them);
+/// `None` when none could tell.
+pub fn shared_bases(items: &[(String, Option<BaseMeasure>)]) -> Vec<Option<super::SharedBase>> {
+ use std::collections::HashMap;
+ let mut groups: HashMap<&str, (u32, Option<u64>)> = HashMap::new();
+ for (_, m) in items {
+ if let Some(m) = m.as_ref().filter(|m| !m.key.is_empty()) {
+ let g = groups.entry(m.key.as_str()).or_insert((0, None));
+ g.0 += 1;
+ g.1 = match (g.1, m.bytes) {
+ (Some(a), Some(b)) => Some(a.max(b)),
+ (a, b) => a.or(b),
+ };
+ }
+ }
+ items
+ .iter()
+ .map(|(image, m)| {
+ let m = m.as_ref().filter(|m| !m.key.is_empty())?;
+ let (shared_with, bytes) = groups[m.key.as_str()];
+ Some(super::SharedBase {
+ key: m.key.clone(),
+ image: image.clone(),
+ bytes,
+ shared_with,
+ })
+ })
+ .collect()
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/libs/cua/crates/cua-spaces/src/resources/hub.rs b/libs/cua/crates/cua-spaces/src/resources/hub.rs
index 84457c1bbd..5193235afc 100644
--- a/libs/cua/crates/cua-spaces/src/resources/hub.rs
+++ b/libs/cua/crates/cua-spaces/src/resources/hub.rs
@@ -6,7 +6,7 @@
//! task samples every [`VISIBLE_TICK`] (a visible window) or [`HIDDEN_TICK`]
//! (only hidden watchers, for the menu bar warning), then ends.
-use super::disk::{self, Footprint, LumeFacts};
+use super::disk::{self, BaseMeasure, Footprint, LumeFacts};
use super::host::{self, HostSampler};
use super::{
ComputerResources, DISK_MEASURE_EVERY, DiskLevel, DiskOnHost, DiskWarning, GuestUsage,
@@ -104,6 +104,7 @@ struct Measured {
at: Instant,
power_state: String,
value: Option<DiskOnHost>,
+ base: Option<BaseMeasure>,
}
impl Hub {
@@ -408,12 +409,19 @@ impl Spaces {
.map(GuestUsage::from)
}))
.await;
- let spaces: Vec<SpaceResources> = infos
+ let mut bases = Vec::with_capacity(infos.len());
+ let mut spaces: Vec<SpaceResources> = infos
.iter()
.zip(usages)
.map(|(info, usage)| {
let name = info.id.trim_start_matches("local:");
let fp = facts.iter().find(|f| f.name == name);
+ let measured = st.disks.get(&info.id);
+ bases.push((
+ fp.map(|f| f.image.clone()).unwrap_or_default(),
+ measured.and_then(|m| m.base.clone()),
+ ));
+
// A guest that reports its own limits fills what the state
// file did not record.
let own = usage.filter(|u| u.memory_limited || u.disk_limited);
@@ -433,13 +441,17 @@ impl Spaces {
disk_allocated: fp
.map(|f| f.disk)
.filter(|d| *d > 0)
- .or(own.filter(|u| u.disk_limited).map(|u| u.disk_total))
+ .or(own.filter(|u| u.disk_limited).and_then(|u| u.disk_total))
.unwrap_or(0),
usage,
- disk_on_host: st.disks.get(&info.id).and_then(|m| m.value),
+ disk_on_host: measured.and_then(|m| m.value),
+ base: None,
}
})
.collect();
+ for (s, base) in spaces.iter_mut().zip(disk::shared_bases(&bases)) {
+ s.base = base;
+ }
let mut this_mac = ComputerResources {
id: THIS_MAC.into(),
@@ -460,7 +472,6 @@ impl Spaces {
// Your Spaces on your other computers: only what each takes on its
// computer's disk, asked of that computer (cached; never measured
// here).
- let mut spaces = spaces;
if ask.disk {
spaces.extend(self.remote_space_disks(wait_remote).await);
}
@@ -525,10 +536,10 @@ impl Spaces {
due.into_iter().partition(|(_, fp, _)| fp.engine);
let mut measured =
futures_util::future::join_all(on_disk.into_iter().map(|(id, fp, power)| async move {
- let value = tokio::task::spawn_blocking(move || measure_footprint(&fp))
+ let (value, base) = tokio::task::spawn_blocking(move || measure_footprint(&fp))
.await
- .unwrap_or(None);
- (id, power, value)
+ .unwrap_or((None, None));
+ (id, power, value, base)
}))
.await;
// Containers: the engine's own count of each one's layer, asked once
@@ -537,19 +548,19 @@ impl Spaces {
if !in_engine.is_empty()
&& let Some(sizes) = engine_disks(&home, &in_engine).await
{
- measured.extend(
- in_engine
- .into_iter()
- .map(|(id, fp, power)| (id, power, sizes.get(&fp.name).copied())),
- );
+ measured.extend(in_engine.into_iter().map(|(id, fp, power)| {
+ let (value, base) = sizes.get(&fp.name).cloned().unwrap_or((None, None));
+ (id, power, value, base)
+ }));
}
- for (id, power_state, value) in measured {
+ for (id, power_state, value, base) in measured {
st.disks.insert(
id,
Measured {
at: Instant::now(),
power_state,
value,
+ base,
},
);
}
@@ -621,7 +632,7 @@ const ENGINE_TIMEOUT: Duration = Duration::from_secs(20);
async fn engine_disks(
home: &std::path::Path,
due: &[(String, Footprint, String)],
-) -> Option<HashMap<String, DiskOnHost>> {
+) -> Option<HashMap<String, (Option<DiskOnHost>, Option<BaseMeasure>)>> {
let engine = cua_disk::docker::connect().await?;
let tag = cua_vmm::container::home_tag_for(home);
let ask = async {
@@ -635,11 +646,18 @@ async fn engine_disks(
} else {
engine.volume_sizes(&volumes).await.unwrap_or_default()
};
+ // The image each runs: its layers are the base its Spaces share.
+ let images = engine.images().await.unwrap_or_default();
Some(
due.iter()
.filter_map(|(_, fp, _)| {
let d = disk::container_disk(&fp.name, &tag, &containers, &sizes)?;
- Some((fp.name.clone(), d))
+ let base =
+ disk::container_image(&fp.name, &tag, &containers).map(|id| BaseMeasure {
+ key: id.to_string(),
+ bytes: images.iter().find(|i| i.id == id).map(|i| i.size),
+ });
+ Some((fp.name.clone(), (Some(d), base)))
})
.collect(),
)
@@ -650,10 +668,13 @@ async fn engine_disks(
.flatten()
}
-/// What the Space with `fp` costs this computer's disk.
-fn measure_footprint(fp: &Footprint) -> Option<DiskOnHost> {
- let dir = fp.dir.as_deref()?;
- disk::measure(dir).or_else(|| {
+/// What the Space with `fp` costs this computer's disk (its own data), and
+/// the base it shares.
+fn measure_footprint(fp: &Footprint) -> (Option<DiskOnHost>, Option<BaseMeasure>) {
+ let Some(dir) = fp.dir.as_deref() else {
+ return (None, None);
+ };
+ let value = disk::measure(dir).or_else(|| {
// Lume's directory is somewhere else: only Lume's own count, which
// clones count in full.
(fp.reported > 0).then_some(DiskOnHost {
@@ -661,6 +682,31 @@ fn measure_footprint(fp: &Footprint) -> Option<DiskOnHost> {
allocated: fp.reported,
shares_space: true,
})
+ });
+ (value, base_of(fp, value.as_ref()))
+}
+
+/// The base a VM's disk shares: an APFS clone's shared blocks (Lume), a
+/// qcow2 overlay's backing image (QEMU). Other runtimes keep their base
+/// apart and are not counted.
+fn base_of(fp: &Footprint, own: Option<&DiskOnHost>) -> Option<BaseMeasure> {
+ if fp.image_key.is_empty() {
+ return None;
+ }
+ let bytes = match fp.runtime.as_str() {
+ "lume" => own.and_then(disk::shared_blocks),
+ "qemu" => {
+ let dir = fp.dir.as_deref()?;
+ let state: cua_vmm::qemu::QemuState =
+ serde_json::from_slice(&std::fs::read(dir.join("state.json")).ok()?).ok()?;
+ let backing = disk::qcow2_backing_file(&state.disk)?;
+ Some(cua_vmm::disk::allocated_size(&backing))
+ }
+ _ => return None,
+ };
+ Some(BaseMeasure {
+ key: fp.image_key.clone(),
+ bytes,
})
}
diff --git a/libs/cua/crates/cua-spaces/src/resources/mod.rs b/libs/cua/crates/cua-spaces/src/resources/mod.rs
index 2c97e6d8f2..e99572d69e 100644
--- a/libs/cua/crates/cua-spaces/src/resources/mod.rs
+++ b/libs/cua/crates/cua-spaces/src/resources/mod.rs
@@ -223,14 +223,37 @@ pub struct GuestUsage {
pub memory_limited: bool,
/// Disk in use, bytes.
pub disk_used: u64,
- /// Disk size, bytes.
- pub disk_total: u64,
+ /// Disk size, bytes; `None` when the guest's file system has no size of
+ /// its own (gVisor's root overlay reports "unlimited") or did not say.
+ /// Never a sentinel: see [`known_size`].
+ #[serde(default, deserialize_with = "de_known_size")]
+ pub disk_total: Option<u64>,
/// `disk_total` is the guest's own disk.
pub disk_limited: bool,
}
+/// Sizes at or above this are not sizes: "unlimited" or "unknown" sentinels
+/// (`i64::MAX`, `u64::MAX`, gVisor's `MaxInt64` rounded to a page). No
+/// volume holds an exbibyte.
+pub const SIZE_SENTINEL_FLOOR: u64 = 1 << 60;
+
+/// A size as reported, or `None` when it is no size: 0 (not said) or a
+/// sentinel ([`SIZE_SENTINEL_FLOOR`]). The one place a guest's or an older
+/// daemon's "unlimited" turns into an explicit absence, so no sentinel ever
+/// reaches a screen.
+pub fn known_size(bytes: u64) -> Option<u64> {
+ (bytes > 0 && bytes < SIZE_SENTINEL_FLOOR).then_some(bytes)
+}
+
+/// [`known_size`] for JSON: a number (any sign or size), `null` or absent.
+fn de_known_size<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
+ let v = Option::<serde_json::Number>::deserialize(d)?;
+ Ok(v.and_then(|n| n.as_u64()).and_then(known_size))
+}
+
impl From<crate::stream::Usage> for GuestUsage {
fn from(u: crate::stream::Usage) -> Self {
+ let disk_total = known_size(u.disk_total);
GuestUsage {
cpu_count: u.cpu_count,
cpu_percent: u.cpu_percent,
@@ -238,9 +261,14 @@ impl From<crate::stream::Usage> for GuestUsage {
memory_used: u.memory_used,
memory_total: u.memory_total,
memory_limited: u.memory_limited,
- disk_used: u.disk_used,
- disk_total: u.disk_total,
- disk_limited: u.disk_limited,
+ // A used count above a size that is no size is no count either.
+ disk_used: if u.disk_used >= SIZE_SENTINEL_FLOOR {
+ 0
+ } else {
+ u.disk_used
+ },
+ disk_total,
+ disk_limited: u.disk_limited && disk_total.is_some(),
}
}
}
@@ -278,8 +306,32 @@ pub struct SpaceResources {
pub disk_allocated: u64,
/// The guest's own numbers; `None` while it is off or unreachable.
pub usage: Option<GuestUsage>,
- /// What it costs this Mac; `None` for a container.
+ /// What it costs this Mac: only its own data (a clone's or a
+ /// container's changes), never the base it shares; `None` when there
+ /// is nothing to measure.
pub disk_on_host: Option<DiskOnHost>,
+ /// The base image it is a copy-on-write copy of, counted once for all
+ /// the Spaces on this computer that share it; `None` when it has none
+ /// or the runtime cannot tell it apart.
+ #[serde(default)]
+ pub base: Option<SharedBase>,
+}
+
+/// A base image several Spaces share copy-on-write (a container image's
+/// layers, the image a VM disk was cloned from).
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SharedBase {
+ /// Which base: Spaces with the same key share the same blocks.
+ pub key: String,
+ /// The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ pub image: String,
+ /// What it takes on this computer, once for all its Spaces; `None`
+ /// when the runtime cannot tell it apart from the Spaces' own data.
+ pub bytes: Option<u64>,
+ /// Local Spaces that use it, this one included (1: deleting this Space
+ /// leaves no other user of it).
+ pub shared_with: u32,
}
/// One sample of everything.
@@ -383,7 +435,8 @@ impl SpaceResources {
|| grew(a.memory_used, b.memory_used)
|| grew(a.memory_total, b.memory_total)
|| grew(a.disk_used, b.disk_used)
- || grew(a.disk_total, b.disk_total)
+ || a.disk_total.is_some() != b.disk_total.is_some()
+ || grew(a.disk_total.unwrap_or(0), b.disk_total.unwrap_or(0))
}
_ => true,
};
@@ -399,6 +452,7 @@ impl SpaceResources {
};
usage
|| disk
+ || self.base != sent.base
|| self.id != sent.id
|| self.power_state != sent.power_state
|| self.cpu_allocated != sent.cpu_allocated
diff --git a/libs/cua/crates/cua-spaces/src/resources/tests.rs b/libs/cua/crates/cua-spaces/src/resources/tests.rs
index e1facfed45..b598573081 100644
--- a/libs/cua/crates/cua-spaces/src/resources/tests.rs
+++ b/libs/cua/crates/cua-spaces/src/resources/tests.rs
@@ -83,7 +83,7 @@ fn space(id: &str) -> SpaceResources {
memory_total: 8 * GIB,
memory_limited: true,
disk_used: 20 * GIB,
- disk_total: 80 * GIB,
+ disk_total: Some(80 * GIB),
disk_limited: true,
..Default::default()
}),
@@ -92,6 +92,7 @@ fn space(id: &str) -> SpaceResources {
allocated: 31 * GIB,
shares_space: true,
}),
+ base: None,
}
}
@@ -234,3 +235,148 @@ fn events_have_a_stable_json_shape() {
assert_eq!(v["value"]["level"], "critical");
assert_eq!(serde_json::from_value::<ResourcesEvent>(v).unwrap(), e);
}
+
+/// gVisor's root overlay: `MaxInt64` rounded down to a page.
+const GVISOR_UNLIMITED: u64 = (i64::MAX as u64) & !4095;
+
+#[test]
+fn a_size_that_is_a_sentinel_is_no_size() {
+ use super::known_size;
+ for sentinel in [i64::MAX as u64, u64::MAX, GVISOR_UNLIMITED, 0] {
+ assert_eq!(known_size(sentinel), None, "{sentinel}");
+ }
+ assert_eq!(known_size(80 * GIB), Some(80 * GIB));
+ assert_eq!(known_size(1), Some(1));
+}
+
+#[test]
+fn a_guest_with_an_unlimited_root_reports_no_disk_size() {
+ let u = GuestUsage::from(crate::stream::Usage {
+ disk_used: 241_664,
+ disk_total: GVISOR_UNLIMITED,
+ ..Default::default()
+ });
+ assert_eq!(u.disk_total, None);
+ assert_eq!(u.disk_used, 241_664);
+ // A VM's own disk keeps its size.
+ let vm = GuestUsage::from(crate::stream::Usage {
+ disk_used: 20 * GIB,
+ disk_total: 80 * GIB,
+ disk_limited: true,
+ ..Default::default()
+ });
+ assert_eq!((vm.disk_total, vm.disk_limited), (Some(80 * GIB), true));
+}
+
+#[test]
+fn json_from_an_older_daemon_never_carries_a_sentinel() {
+ for raw in [
+ "9223372036854775807",
+ "18446744073709551615",
+ "-1",
+ "0",
+ "null",
+ ] {
+ let u: GuestUsage = serde_json::from_str(&format!(
+ r#"{{"cpuCount":2,"cpuPercent":1,"loadAverage1m":0,"memoryUsed":1,"memoryTotal":2,"memoryLimited":true,"diskUsed":5,"diskTotal":{raw},"diskLimited":false}}"#
+ ))
+ .unwrap();
+ assert_eq!(u.disk_total, None, "{raw}");
+ }
+ let u: GuestUsage = serde_json::from_str(
+ r#"{"cpuCount":2,"cpuPercent":1,"loadAverage1m":0,"memoryUsed":1,"memoryTotal":2,"memoryLimited":true,"diskUsed":5,"diskLimited":true}"#,
+ )
+ .unwrap();
+ assert_eq!(u.disk_total, None);
+}
+
+#[test]
+fn the_wire_from_an_older_daemon_never_carries_a_sentinel() {
+ use cua_proto::daemon::v1 as pb;
+ for sentinel in [i64::MAX as u64, u64::MAX, GVISOR_UNLIMITED, 0] {
+ let s = SpaceResources::from(pb::SpaceResources {
+ id: "local:a".into(),
+ usage: Some(pb::GuestUsage {
+ disk_used: 1_000,
+ disk_total: sentinel,
+ disk_limited: true,
+ ..Default::default()
+ }),
+ ..Default::default()
+ });
+ let u = s.usage.unwrap();
+ assert_eq!((u.disk_total, u.disk_limited), (None, false), "{sentinel}");
+ }
+}
+
+#[test]
+fn shared_bases_count_each_base_once() {
+ use super::disk::{BaseMeasure, shared_bases};
+ let m = |key: &str, bytes: Option<u64>| {
+ Some(BaseMeasure {
+ key: key.into(),
+ bytes,
+ })
+ };
+ let ubuntu = "ghcr.io/trycua/linux:24.04".to_string();
+ let macos = "ghcr.io/trycua/macos:26".to_string();
+ let out = shared_bases(&[
+ // Copy-on-write: two containers on one image.
+ (ubuntu.clone(), m("sha256:u", Some(3 * GIB))),
+ (ubuntu.clone(), m("sha256:u", Some(3 * GIB))),
+ // The last user of its base.
+ (macos.clone(), m("sha256:m", Some(25 * GIB))),
+ // Not copy-on-write (or a runtime that keeps its base apart).
+ ("x".into(), None),
+ // Can't tell its own data from the base's.
+ ("example.org/windows:11".into(), m("sha256:w", None)),
+ ]);
+ let u = out[0].clone().unwrap();
+ assert_eq!(
+ (u.bytes, u.shared_with, u.image.as_str()),
+ (Some(3 * GIB), 2, ubuntu.as_str())
+ );
+ assert_eq!(out[1], out[0]);
+ let last = out[2].clone().unwrap();
+ assert_eq!((last.bytes, last.shared_with), (Some(25 * GIB), 1));
+ assert_eq!(out[3], None);
+ let w = out[4].clone().unwrap();
+ assert_eq!((w.bytes, w.shared_with), (None, 1));
+}
+
+#[test]
+fn clones_of_one_base_report_the_most_any_shares() {
+ use super::disk::{BaseMeasure, shared_bases, shared_blocks};
+ // A clone that changed more shares fewer blocks with its base.
+ let a = DiskOnHost {
+ bytes: Some(6 * GIB),
+ allocated: 31 * GIB,
+ shares_space: true,
+ };
+ let b = DiskOnHost {
+ bytes: Some(10 * GIB),
+ allocated: 30 * GIB,
+ shares_space: true,
+ };
+ let unknown = DiskOnHost {
+ bytes: None,
+ allocated: 30 * GIB,
+ shares_space: true,
+ };
+ assert_eq!(shared_blocks(&unknown), None);
+ let m = |d: &DiskOnHost| {
+ Some(BaseMeasure {
+ key: "macos".into(),
+ bytes: shared_blocks(d),
+ })
+ };
+ let out = shared_bases(&[
+ ("macos".into(), m(&a)),
+ ("macos".into(), m(&b)),
+ ("macos".into(), m(&unknown)),
+ ]);
+ for s in &out {
+ let s = s.clone().unwrap();
+ assert_eq!((s.bytes, s.shared_with), (Some(25 * GIB), 3));
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/resources/wire.rs b/libs/cua/crates/cua-spaces/src/resources/wire.rs
index 1563bd644f..c0f7b21760 100644
--- a/libs/cua/crates/cua-spaces/src/resources/wire.rs
+++ b/libs/cua/crates/cua-spaces/src/resources/wire.rs
@@ -4,7 +4,7 @@
use super::{
ComputerResources, DiskLevel, DiskOnHost, DiskWarning, GuestUsage, Resources, ResourcesEvent,
- ResourcesUpdate, SpaceResources,
+ ResourcesUpdate, SharedBase, SpaceResources,
};
use cua_proto::daemon::v1 as pb;
use pb::watch_resources_response::Event;
@@ -99,7 +99,8 @@ impl From<&SpaceResources> for pb::SpaceResources {
memory_total: u.memory_total,
memory_limited: u.memory_limited,
disk_used: u.disk_used,
- disk_total: u.disk_total,
+ // 0 on the wire: no size of its own.
+ disk_total: u.disk_total.unwrap_or(0),
disk_limited: u.disk_limited,
}),
disk_on_host: s.disk_on_host.map(|d| pb::DiskOnHost {
@@ -107,6 +108,12 @@ impl From<&SpaceResources> for pb::SpaceResources {
allocated: d.allocated,
shares_space: d.shares_space,
}),
+ base: s.base.as_ref().map(|b| pb::SharedBase {
+ key: b.key.clone(),
+ image: b.image.clone(),
+ bytes: b.bytes,
+ shared_with: b.shared_with,
+ }),
}
}
}
@@ -119,22 +126,37 @@ impl From<pb::SpaceResources> for SpaceResources {
cpu_allocated: s.cpu_allocated,
memory_allocated: s.memory_allocated,
disk_allocated: s.disk_allocated,
- usage: s.usage.map(|u| GuestUsage {
- cpu_count: u.cpu_count,
- cpu_percent: u.cpu_percent,
- load_average_1m: u.load_average_1m,
- memory_used: u.memory_used,
- memory_total: u.memory_total,
- memory_limited: u.memory_limited,
- disk_used: u.disk_used,
- disk_total: u.disk_total,
- disk_limited: u.disk_limited,
+ // An older daemon sends a guest's "unlimited" as a number:
+ // `known_size` turns it into no size.
+ usage: s.usage.map(|u| {
+ let disk_total = super::known_size(u.disk_total);
+ GuestUsage {
+ cpu_count: u.cpu_count,
+ cpu_percent: u.cpu_percent,
+ load_average_1m: u.load_average_1m,
+ memory_used: u.memory_used,
+ memory_total: u.memory_total,
+ memory_limited: u.memory_limited,
+ disk_used: if u.disk_used >= super::SIZE_SENTINEL_FLOOR {
+ 0
+ } else {
+ u.disk_used
+ },
+ disk_total,
+ disk_limited: u.disk_limited && disk_total.is_some(),
+ }
}),
disk_on_host: s.disk_on_host.map(|d| DiskOnHost {
bytes: d.bytes,
allocated: d.allocated,
shares_space: d.shares_space,
}),
+ base: s.base.map(|b| SharedBase {
+ key: b.key,
+ image: b.image,
+ bytes: b.bytes,
+ shared_with: b.shared_with,
+ }),
}
}
}
@@ -261,7 +283,7 @@ mod tests {
memory_total: 8 * GIB,
memory_limited: true,
disk_used: 20 * GIB,
- disk_total: 80 * GIB,
+ disk_total: Some(80 * GIB),
disk_limited: true,
}),
disk_on_host: Some(DiskOnHost {
@@ -269,6 +291,12 @@ mod tests {
allocated: 31 * GIB,
shares_space: true,
}),
+ base: Some(SharedBase {
+ key: "sha256:abc".into(),
+ image: "ghcr.io/trycua/macos:26".into(),
+ bytes: Some(25 * GIB),
+ shared_with: 2,
+ }),
},
SpaceResources {
id: "local:b".into(),
diff --git a/libs/cua/crates/cua-spaces/src/resources/words.rs b/libs/cua/crates/cua-spaces/src/resources/words.rs
index 03aa0ebc9b..b137f4bc79 100644
--- a/libs/cua/crates/cua-spaces/src/resources/words.rs
+++ b/libs/cua/crates/cua-spaces/src/resources/words.rs
@@ -257,6 +257,7 @@ mod tests {
allocated: 87 * GIB,
shares_space: true,
}),
+ base: None,
}
}
diff --git a/libs/cua/crates/cua-spaces/src/stream.rs b/libs/cua/crates/cua-spaces/src/stream.rs
index 049aa93108..bb33d8e453 100644
--- a/libs/cua/crates/cua-spaces/src/stream.rs
+++ b/libs/cua/crates/cua-spaces/src/stream.rs
@@ -166,7 +166,8 @@ pub struct Usage {
pub memory_limited: bool,
/// Home filesystem bytes in use.
pub disk_used: u64,
- /// Home filesystem size, bytes.
+ /// Home filesystem size, bytes; 0 when it has no size of its own
+ /// (gVisor's root overlay reports "unlimited"), never a sentinel.
pub disk_total: u64,
/// `disk_total` is the guest's own disk.
pub disk_limited: bool,
@@ -181,9 +182,16 @@ impl From<pb::MetricsResponse> for Usage {
memory_used: m.memory_used_bytes,
memory_total: m.memory_total_bytes,
memory_limited: m.memory_limited,
- disk_used: m.disk_used_bytes,
- disk_total: m.disk_total_bytes,
- disk_limited: m.disk_limited,
+ disk_used: if m.disk_total_bytes >= crate::resources::SIZE_SENTINEL_FLOOR
+ && m.disk_used_bytes >= crate::resources::SIZE_SENTINEL_FLOOR
+ {
+ 0
+ } else {
+ m.disk_used_bytes
+ },
+ disk_total: crate::resources::known_size(m.disk_total_bytes).unwrap_or(0),
+ disk_limited: m.disk_limited
+ && crate::resources::known_size(m.disk_total_bytes).is_some(),
}
}
}
diff --git a/libs/cua/crates/cua-spaces/tests/resources.rs b/libs/cua/crates/cua-spaces/tests/resources.rs
index e34cf8f557..d8c4632067 100644
--- a/libs/cua/crates/cua-spaces/tests/resources.rs
+++ b/libs/cua/crates/cua-spaces/tests/resources.rs
@@ -149,7 +149,7 @@ async fn a_local_space_reports_what_it_was_given_and_what_it_uses() {
assert_eq!((u.cpu_count, u.cpu_percent), (4, 12.5));
assert_eq!(u.load_average_1m, 0.75);
assert_eq!((u.memory_total, u.memory_limited), (4 * GIB, true));
- assert_eq!((u.disk_total, u.disk_limited), (32 * GIB, true));
+ assert_eq!((u.disk_total, u.disk_limited), (Some(32 * GIB), true));
// A fake engine has no disk files to measure: no number, no claim.
assert_eq!(s.disk_on_host, None);
// The totals add the running Space up (its power word is empty: it
diff --git a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/system_pb.ts b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/system_pb.ts
index 549582c240..a606482af6 100644
--- a/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/system_pb.ts
+++ b/libs/cua/crates/cua-spacesd-html5/web/src/gen/cua/env/v1/system_pb.ts
@@ -797,7 +797,9 @@ export type MetricsResponse = Message<"cua.env.v1.MetricsResponse"> & {
memoryUsedBytes: bigint;
/**
- * Total bytes of the filesystem named by `disk_path`.
+ * Total bytes of the filesystem named by `disk_path`; 0 when it has no
+ * size of its own (gVisor's root overlay reports "unlimited"), never a
+ * sentinel such as 2^63.
*
* @generated from field: uint64 disk_total_bytes = 7;
*/
diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
index 0a21d3cb82..8d6e01b827 100644
--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt
@@ -35973,9 +35973,10 @@ data class GuestUsage (
var `diskUsed`: kotlin.ULong
,
/**
- * Disk size, bytes.
+ * Disk size, bytes; absent when the guest's file system has no size
+ * of its own (gVisor's root overlay) or did not say. Never a sentinel.
*/
- var `diskTotal`: kotlin.ULong
+ var `diskTotal`: kotlin.ULong?
,
/**
* `disk_total` is the guest's own disk.
@@ -36004,7 +36005,7 @@ public object FfiConverterTypeGuestUsage: FfiConverterRustBuffer<GuestUsage> {
FfiConverterULong.read(buf),
FfiConverterBoolean.read(buf),
FfiConverterULong.read(buf),
- FfiConverterULong.read(buf),
+ FfiConverterOptionalULong.read(buf),
FfiConverterBoolean.read(buf),
)
}
@@ -36017,7 +36018,7 @@ public object FfiConverterTypeGuestUsage: FfiConverterRustBuffer<GuestUsage> {
FfiConverterULong.allocationSize(value.`memoryTotal`) +
FfiConverterBoolean.allocationSize(value.`memoryLimited`) +
FfiConverterULong.allocationSize(value.`diskUsed`) +
- FfiConverterULong.allocationSize(value.`diskTotal`) +
+ FfiConverterOptionalULong.allocationSize(value.`diskTotal`) +
FfiConverterBoolean.allocationSize(value.`diskLimited`)
)
@@ -36029,7 +36030,7 @@ public object FfiConverterTypeGuestUsage: FfiConverterRustBuffer<GuestUsage> {
FfiConverterULong.write(value.`memoryTotal`, buf)
FfiConverterBoolean.write(value.`memoryLimited`, buf)
FfiConverterULong.write(value.`diskUsed`, buf)
- FfiConverterULong.write(value.`diskTotal`, buf)
+ FfiConverterOptionalULong.write(value.`diskTotal`, buf)
FfiConverterBoolean.write(value.`diskLimited`, buf)
}
}
@@ -41682,6 +41683,71 @@ public object FfiConverterTypeShareCheck: FfiConverterRustBuffer<ShareCheck> {
+/**
+ * A base image several Spaces share copy-on-write (a container image's
+ * layers, the image a VM disk was cloned from).
+ */
+data class SharedBase (
+ /**
+ * Which base: Spaces with the same key share the same blocks.
+ */
+ var `key`: kotlin.String
+ ,
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */
+ var `image`: kotlin.String
+ ,
+ /**
+ * What it takes on this computer, once for all its Spaces; absent when
+ * the runtime cannot tell it apart from the Spaces' own data.
+ */
+ var `bytes`: kotlin.ULong?
+ ,
+ /**
+ * Local Spaces that use it, this one included.
+ */
+ var `sharedWith`: kotlin.UInt
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeSharedBase: FfiConverterRustBuffer<SharedBase> {
+ override fun read(buf: ByteBuffer): SharedBase {
+ return SharedBase(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalULong.read(buf),
+ FfiConverterUInt.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: SharedBase) = (
+ FfiConverterString.allocationSize(value.`key`) +
+ FfiConverterString.allocationSize(value.`image`) +
+ FfiConverterOptionalULong.allocationSize(value.`bytes`) +
+ FfiConverterUInt.allocationSize(value.`sharedWith`)
+ )
+
+ override fun write(value: SharedBase, buf: ByteBuffer) {
+ FfiConverterString.write(value.`key`, buf)
+ FfiConverterString.write(value.`image`, buf)
+ FfiConverterOptionalULong.write(value.`bytes`, buf)
+ FfiConverterUInt.write(value.`sharedWith`, buf)
+ }
+}
+
+
+
/**
* Options for [`Space::request_site_login`].
*/
@@ -43753,9 +43819,17 @@ data class SpaceResources (
var `usage`: GuestUsage?
,
/**
- * What it costs this Mac; absent for a container.
+ * What it costs this Mac: its own data only, never the base it
+ * shares; absent when there is nothing to measure.
*/
var `diskOnHost`: DiskOnHost?
+ ,
+ /**
+ * The base image it is a copy-on-write copy of, counted once for all
+ * the Spaces that share it; absent when it has none or the runtime
+ * cannot tell it apart.
+ */
+ var `base`: SharedBase?
){
@@ -43779,6 +43853,7 @@ public object FfiConverterTypeSpaceResources: FfiConverterRustBuffer<SpaceResour
FfiConverterULong.read(buf),
FfiConverterOptionalTypeGuestUsage.read(buf),
FfiConverterOptionalTypeDiskOnHost.read(buf),
+ FfiConverterOptionalTypeSharedBase.read(buf),
)
}
@@ -43789,7 +43864,8 @@ public object FfiConverterTypeSpaceResources: FfiConverterRustBuffer<SpaceResour
FfiConverterULong.allocationSize(value.`memoryAllocated`) +
FfiConverterULong.allocationSize(value.`diskAllocated`) +
FfiConverterOptionalTypeGuestUsage.allocationSize(value.`usage`) +
- FfiConverterOptionalTypeDiskOnHost.allocationSize(value.`diskOnHost`)
+ FfiConverterOptionalTypeDiskOnHost.allocationSize(value.`diskOnHost`) +
+ FfiConverterOptionalTypeSharedBase.allocationSize(value.`base`)
)
override fun write(value: SpaceResources, buf: ByteBuffer) {
@@ -43800,6 +43876,7 @@ public object FfiConverterTypeSpaceResources: FfiConverterRustBuffer<SpaceResour
FfiConverterULong.write(value.`diskAllocated`, buf)
FfiConverterOptionalTypeGuestUsage.write(value.`usage`, buf)
FfiConverterOptionalTypeDiskOnHost.write(value.`diskOnHost`, buf)
+ FfiConverterOptionalTypeSharedBase.write(value.`base`, buf)
}
}
@@ -50670,6 +50747,38 @@ public object FfiConverterOptionalTypeScreenshotOptions: FfiConverterRustBuffer<
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalTypeSharedBase: FfiConverterRustBuffer<SharedBase?> {
+ override fun read(buf: ByteBuffer): SharedBase? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterTypeSharedBase.read(buf)
+ }
+
+ override fun allocationSize(value: SharedBase?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterTypeSharedBase.allocationSize(value)
+ }
+ }
+
+ override fun write(value: SharedBase?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterTypeSharedBase.write(value, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
diff --git a/libs/cua/proto/cua/daemon/v1/resources.proto b/libs/cua/proto/cua/daemon/v1/resources.proto
index 6d4fed3199..e57a4f9218 100644
--- a/libs/cua/proto/cua/daemon/v1/resources.proto
+++ b/libs/cua/proto/cua/daemon/v1/resources.proto
@@ -144,7 +144,10 @@ message GuestUsage {
bool memory_limited = 6;
// Disk in use in bytes.
uint64 disk_used = 7;
- // Disk size in bytes.
+ // Disk size in bytes; 0 when the guest's file system has no size of its
+ // own (gVisor's root overlay says "unlimited") or did not say. Readers
+ // treat any size at or above 2^60 bytes the same way: a sentinel, never a
+ // size.
uint64 disk_total = 8;
// `disk_total` is the guest's own disk.
bool disk_limited = 9;
@@ -176,6 +179,25 @@ message SpaceResources {
uint64 disk_allocated = 5;
// The guest's own numbers; unset while it is off or unreachable.
GuestUsage usage = 6;
- // What it costs this computer; unset for a container.
+ // What it costs this computer: its own data only, never the base it
+ // shares; unset when there is nothing to measure.
DiskOnHost disk_on_host = 7;
+ // The base image it is a copy-on-write copy of; unset when it has none or
+ // the runtime cannot tell it apart.
+ SharedBase base = 8;
+}
+
+// A base image several Spaces share copy-on-write: a container image's
+// layers, the image a virtual machine's disk was cloned from.
+message SharedBase {
+ // Which base: Spaces with the same key share the same blocks.
+ string key = 1;
+ // The image reference it came from, for example
+ // `ghcr.io/trycua/linux:24.04`.
+ string image = 2;
+ // What it takes on this computer, once for all its Spaces. Unset when the
+ // runtime cannot tell it apart from the Spaces' own data.
+ optional uint64 bytes = 3;
+ // Local Spaces that use it, this one included.
+ uint32 shared_with = 4;
}
diff --git a/libs/cua/proto/cua/env/v1/system.proto b/libs/cua/proto/cua/env/v1/system.proto
index 24a4f62981..67f0dd5504 100644
--- a/libs/cua/proto/cua/env/v1/system.proto
+++ b/libs/cua/proto/cua/env/v1/system.proto
@@ -408,7 +408,9 @@ message MetricsResponse {
uint64 memory_total_bytes = 5;
// Used guest memory in bytes (excluding reclaimable cache).
uint64 memory_used_bytes = 6;
- // Total bytes of the filesystem named by `disk_path`.
+ // Total bytes of the filesystem named by `disk_path`; 0 when it has no
+ // size of its own (gVisor's root overlay reports "unlimited"), never a
+ // sentinel such as 2^63.
uint64 disk_total_bytes = 7;
// Used bytes of that filesystem.
uint64 disk_used_bytes = 8;
diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.py
index 4fe02b8ebc..5b60a09ac3 100644
--- a/libs/cua/python/src/cua/_native.py
+++ b/libs/cua/python/src/cua/_native.py
@@ -16837,7 +16837,7 @@ class GuestUsage:
"""
What `SystemService.Metrics` reports from inside a Space.
"""
- def __init__(self, *, cpu_count:int, cpu_percent:float, load_average_1m:float, memory_used:int, memory_total:int, memory_limited:bool, disk_used:int, disk_total:int, disk_limited:bool):
+ def __init__(self, *, cpu_count:int, cpu_percent:float, load_average_1m:float, memory_used:int, memory_total:int, memory_limited:bool, disk_used:int, disk_total:typing.Optional[int], disk_limited:bool):
self.cpu_count = cpu_count
self.cpu_percent = cpu_percent
self.load_average_1m = load_average_1m
@@ -16885,7 +16885,7 @@ class _UniffiFfiConverterTypeGuestUsage(_UniffiConverterRustBuffer):
memory_total=_UniffiFfiConverterUInt64.read(buf),
memory_limited=_UniffiFfiConverterBoolean.read(buf),
disk_used=_UniffiFfiConverterUInt64.read(buf),
- disk_total=_UniffiFfiConverterUInt64.read(buf),
+ disk_total=_UniffiFfiConverterOptionalUInt64.read(buf),
disk_limited=_UniffiFfiConverterBoolean.read(buf),
)
@@ -16898,7 +16898,7 @@ class _UniffiFfiConverterTypeGuestUsage(_UniffiConverterRustBuffer):
_UniffiFfiConverterUInt64.check_lower(value.memory_total)
_UniffiFfiConverterBoolean.check_lower(value.memory_limited)
_UniffiFfiConverterUInt64.check_lower(value.disk_used)
- _UniffiFfiConverterUInt64.check_lower(value.disk_total)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.disk_total)
_UniffiFfiConverterBoolean.check_lower(value.disk_limited)
@staticmethod
@@ -16910,7 +16910,7 @@ class _UniffiFfiConverterTypeGuestUsage(_UniffiConverterRustBuffer):
_UniffiFfiConverterUInt64.write(value.memory_total, buf)
_UniffiFfiConverterBoolean.write(value.memory_limited, buf)
_UniffiFfiConverterUInt64.write(value.disk_used, buf)
- _UniffiFfiConverterUInt64.write(value.disk_total, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.disk_total, buf)
_UniffiFfiConverterBoolean.write(value.disk_limited, buf)
@dataclass
@@ -20927,12 +20927,89 @@ class _UniffiFfiConverterOptionalTypeDiskOnHost(_UniffiConverterRustBuffer):
else:
raise InternalError("Unexpected flag byte for optional type")
+@dataclass
+class SharedBase:
+ """
+ A base image several Spaces share copy-on-write (a container image's
+ layers, the image a VM disk was cloned from).
+"""
+ def __init__(self, *, key:str, image:str, bytes:typing.Optional[int], shared_with:int):
+ self.key = key
+ self.image = image
+ self.bytes = bytes
+ self.shared_with = shared_with
+
+
+
+
+ def __str__(self):
+ return "SharedBase(key={}, image={}, bytes={}, shared_with={})".format(self.key, self.image, self.bytes, self.shared_with)
+ def __eq__(self, other):
+ if self.key != other.key:
+ return False
+ if self.image != other.image:
+ return False
+ if self.bytes != other.bytes:
+ return False
+ if self.shared_with != other.shared_with:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSharedBase(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SharedBase(
+ key=_UniffiFfiConverterString.read(buf),
+ image=_UniffiFfiConverterString.read(buf),
+ bytes=_UniffiFfiConverterOptionalUInt64.read(buf),
+ shared_with=_UniffiFfiConverterUInt32.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.key)
+ _UniffiFfiConverterString.check_lower(value.image)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.bytes)
+ _UniffiFfiConverterUInt32.check_lower(value.shared_with)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.key, buf)
+ _UniffiFfiConverterString.write(value.image, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.bytes, buf)
+ _UniffiFfiConverterUInt32.write(value.shared_with, buf)
+
+class _UniffiFfiConverterOptionalTypeSharedBase(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeSharedBase.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeSharedBase.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeSharedBase.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
@dataclass
class SpaceResources:
"""
One extra Space on this Mac.
"""
- def __init__(self, *, id:str, power_state:str, cpu_allocated:int, memory_allocated:int, disk_allocated:int, usage:typing.Optional[GuestUsage], disk_on_host:typing.Optional[DiskOnHost]):
+ def __init__(self, *, id:str, power_state:str, cpu_allocated:int, memory_allocated:int, disk_allocated:int, usage:typing.Optional[GuestUsage], disk_on_host:typing.Optional[DiskOnHost], base:typing.Optional[SharedBase]):
self.id = id
self.power_state = power_state
self.cpu_allocated = cpu_allocated
@@ -20940,12 +21017,13 @@ class SpaceResources:
self.disk_allocated = disk_allocated
self.usage = usage
self.disk_on_host = disk_on_host
+ self.base = base
def __str__(self):
- return "SpaceResources(id={}, power_state={}, cpu_allocated={}, memory_allocated={}, disk_allocated={}, usage={}, disk_on_host={})".format(self.id, self.power_state, self.cpu_allocated, self.memory_allocated, self.disk_allocated, self.usage, self.disk_on_host)
+ return "SpaceResources(id={}, power_state={}, cpu_allocated={}, memory_allocated={}, disk_allocated={}, usage={}, disk_on_host={}, base={})".format(self.id, self.power_state, self.cpu_allocated, self.memory_allocated, self.disk_allocated, self.usage, self.disk_on_host, self.base)
def __eq__(self, other):
if self.id != other.id:
return False
@@ -20961,6 +21039,8 @@ class SpaceResources:
return False
if self.disk_on_host != other.disk_on_host:
return False
+ if self.base != other.base:
+ return False
return True
class _UniffiFfiConverterTypeSpaceResources(_UniffiConverterRustBuffer):
@@ -20974,6 +21054,7 @@ class _UniffiFfiConverterTypeSpaceResources(_UniffiConverterRustBuffer):
disk_allocated=_UniffiFfiConverterUInt64.read(buf),
usage=_UniffiFfiConverterOptionalTypeGuestUsage.read(buf),
disk_on_host=_UniffiFfiConverterOptionalTypeDiskOnHost.read(buf),
+ base=_UniffiFfiConverterOptionalTypeSharedBase.read(buf),
)
@staticmethod
@@ -20985,6 +21066,7 @@ class _UniffiFfiConverterTypeSpaceResources(_UniffiConverterRustBuffer):
_UniffiFfiConverterUInt64.check_lower(value.disk_allocated)
_UniffiFfiConverterOptionalTypeGuestUsage.check_lower(value.usage)
_UniffiFfiConverterOptionalTypeDiskOnHost.check_lower(value.disk_on_host)
+ _UniffiFfiConverterOptionalTypeSharedBase.check_lower(value.base)
@staticmethod
def write(value, buf):
@@ -20995,6 +21077,7 @@ class _UniffiFfiConverterTypeSpaceResources(_UniffiConverterRustBuffer):
_UniffiFfiConverterUInt64.write(value.disk_allocated, buf)
_UniffiFfiConverterOptionalTypeGuestUsage.write(value.usage, buf)
_UniffiFfiConverterOptionalTypeDiskOnHost.write(value.disk_on_host, buf)
+ _UniffiFfiConverterOptionalTypeSharedBase.write(value.base, buf)
class _UniffiFfiConverterSequenceTypeSpaceResources(_UniffiConverterRustBuffer):
@classmethod
@@ -46771,6 +46854,7 @@ __all__ = [
"PublicUrl",
"ReadinessProbe",
"ResolvedImage",
+ "SharedBase",
"SpaceResources",
"ResourcesSnapshot",
"ResourcesUpdate",
diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.py
index 3bbfea3b83..f3cdf2c9b4 100644
--- a/libs/cua/scripts/generate-app-core-ffi.py
+++ b/libs/cua/scripts/generate-app-core-ffi.py
@@ -80,7 +80,7 @@ TYPES = [
("tips.rs", "tips", ["TipsState", "TipPlace", "TipFacts", "TipActionKind", "TipAction", "TipLink", "Tip", "TipsEvent"]),
("upsell.rs", "upsell", ["ProBannerInput", "ProBanner"]),
("account.rs", "account", ["AccountMenuInput", "AccountMenuItemId", "AccountMenuItem"]),
- ("resources.rs", "resources", ["DiskLevel", "DiskWarning", "ComputerResources", "GuestUsage", "DiskOnHost", "SpaceResources", "ResourcesSnapshot", "ResourceTone", "ResourceRow", "WarningView", "ThisMacView", "SpaceResourcesView", "ComputerView", "ResourcesView"]),
+ ("resources.rs", "resources", ["DiskLevel", "DiskWarning", "ComputerResources", "GuestUsage", "DiskOnHost", "SharedBase", "SpaceResources", "ResourcesSnapshot", "ResourceTone", "ResourceRow", "WarningView", "ThisMacView", "SpaceResourcesView", "ComputerView", "ResourcesView"]),
]
# FFI names that read better than the plain prefix.
diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
index 3dd95c3ba0..9076fdf775 100644
--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift
@@ -27812,9 +27812,10 @@ public struct GuestUsage: Equatable, Hashable {
*/
public var diskUsed: UInt64
/**
- * Disk size, bytes.
+ * Disk size, bytes; absent when the guest's file system has no size
+ * of its own (gVisor's root overlay) or did not say. Never a sentinel.
*/
- public var diskTotal: UInt64
+ public var diskTotal: UInt64?
/**
* `disk_total` is the guest's own disk.
*/
@@ -27845,8 +27846,9 @@ public struct GuestUsage: Equatable, Hashable {
* Disk in use, bytes.
*/diskUsed: UInt64,
/**
- * Disk size, bytes.
- */diskTotal: UInt64,
+ * Disk size, bytes; absent when the guest's file system has no size
+ * of its own (gVisor's root overlay) or did not say. Never a sentinel.
+ */diskTotal: UInt64?,
/**
* `disk_total` is the guest's own disk.
*/diskLimited: Bool) {
@@ -27884,7 +27886,7 @@ public struct FfiConverterTypeGuestUsage: FfiConverterRustBuffer {
memoryTotal: FfiConverterUInt64.read(from: &buf),
memoryLimited: FfiConverterBool.read(from: &buf),
diskUsed: FfiConverterUInt64.read(from: &buf),
- diskTotal: FfiConverterUInt64.read(from: &buf),
+ diskTotal: FfiConverterOptionUInt64.read(from: &buf),
diskLimited: FfiConverterBool.read(from: &buf)
)
}
@@ -27897,7 +27899,7 @@ public struct FfiConverterTypeGuestUsage: FfiConverterRustBuffer {
FfiConverterUInt64.write(value.memoryTotal, into: &buf)
FfiConverterBool.write(value.memoryLimited, into: &buf)
FfiConverterUInt64.write(value.diskUsed, into: &buf)
- FfiConverterUInt64.write(value.diskTotal, into: &buf)
+ FfiConverterOptionUInt64.write(value.diskTotal, into: &buf)
FfiConverterBool.write(value.diskLimited, into: &buf)
}
}
@@ -35639,6 +35641,98 @@ public func FfiConverterTypeShareCheck_lower(_ value: ShareCheck) -> RustBuffer
}
+/**
+ * A base image several Spaces share copy-on-write (a container image's
+ * layers, the image a VM disk was cloned from).
+ */
+public struct SharedBase: Equatable, Hashable {
+ /**
+ * Which base: Spaces with the same key share the same blocks.
+ */
+ public var key: String
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */
+ public var image: String
+ /**
+ * What it takes on this computer, once for all its Spaces; absent when
+ * the runtime cannot tell it apart from the Spaces' own data.
+ */
+ public var bytes: UInt64?
+ /**
+ * Local Spaces that use it, this one included.
+ */
+ public var sharedWith: UInt32
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Which base: Spaces with the same key share the same blocks.
+ */key: String,
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */image: String,
+ /**
+ * What it takes on this computer, once for all its Spaces; absent when
+ * the runtime cannot tell it apart from the Spaces' own data.
+ */bytes: UInt64?,
+ /**
+ * Local Spaces that use it, this one included.
+ */sharedWith: UInt32) {
+ self.key = key
+ self.image = image
+ self.bytes = bytes
+ self.sharedWith = sharedWith
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SharedBase: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSharedBase: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SharedBase {
+ return
+ try SharedBase(
+ key: FfiConverterString.read(from: &buf),
+ image: FfiConverterString.read(from: &buf),
+ bytes: FfiConverterOptionUInt64.read(from: &buf),
+ sharedWith: FfiConverterUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: SharedBase, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterString.write(value.image, into: &buf)
+ FfiConverterOptionUInt64.write(value.bytes, into: &buf)
+ FfiConverterUInt32.write(value.sharedWith, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSharedBase_lift(_ buf: RustBuffer) throws -> SharedBase {
+ return try FfiConverterTypeSharedBase.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSharedBase_lower(_ value: SharedBase) -> RustBuffer {
+ return FfiConverterTypeSharedBase.lower(value)
+}
+
+
/**
* Options for [`Space::request_site_login`].
*/
@@ -38478,9 +38572,16 @@ public struct SpaceResources: Equatable, Hashable {
*/
public var usage: GuestUsage?
/**
- * What it costs this Mac; absent for a container.
+ * What it costs this Mac: its own data only, never the base it
+ * shares; absent when there is nothing to measure.
*/
public var diskOnHost: DiskOnHost?
+ /**
+ * The base image it is a copy-on-write copy of, counted once for all
+ * the Spaces that share it; absent when it has none or the runtime
+ * cannot tell it apart.
+ */
+ public var base: SharedBase?
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -38504,8 +38605,14 @@ public struct SpaceResources: Equatable, Hashable {
* The guest's own numbers; absent while it is off or unreachable.
*/usage: GuestUsage?,
/**
- * What it costs this Mac; absent for a container.
- */diskOnHost: DiskOnHost?) {
+ * What it costs this Mac: its own data only, never the base it
+ * shares; absent when there is nothing to measure.
+ */diskOnHost: DiskOnHost?,
+ /**
+ * The base image it is a copy-on-write copy of, counted once for all
+ * the Spaces that share it; absent when it has none or the runtime
+ * cannot tell it apart.
+ */base: SharedBase?) {
self.id = id
self.powerState = powerState
self.cpuAllocated = cpuAllocated
@@ -38513,6 +38620,7 @@ public struct SpaceResources: Equatable, Hashable {
self.diskAllocated = diskAllocated
self.usage = usage
self.diskOnHost = diskOnHost
+ self.base = base
}
@@ -38537,7 +38645,8 @@ public struct FfiConverterTypeSpaceResources: FfiConverterRustBuffer {
memoryAllocated: FfiConverterUInt64.read(from: &buf),
diskAllocated: FfiConverterUInt64.read(from: &buf),
usage: FfiConverterOptionTypeGuestUsage.read(from: &buf),
- diskOnHost: FfiConverterOptionTypeDiskOnHost.read(from: &buf)
+ diskOnHost: FfiConverterOptionTypeDiskOnHost.read(from: &buf),
+ base: FfiConverterOptionTypeSharedBase.read(from: &buf)
)
}
@@ -38549,6 +38658,7 @@ public struct FfiConverterTypeSpaceResources: FfiConverterRustBuffer {
FfiConverterUInt64.write(value.diskAllocated, into: &buf)
FfiConverterOptionTypeGuestUsage.write(value.usage, into: &buf)
FfiConverterOptionTypeDiskOnHost.write(value.diskOnHost, into: &buf)
+ FfiConverterOptionTypeSharedBase.write(value.base, into: &buf)
}
}
@@ -46623,6 +46733,30 @@ fileprivate struct FfiConverterOptionTypeScreenshotOptions: FfiConverterRustBuff
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeSharedBase: FfiConverterRustBuffer {
+ typealias SwiftType = SharedBase?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeSharedBase.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeSharedBase.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.ts
index 224bb775fb..14555b6d2e 100644
--- a/libs/cua/typescript/src/native/cua_sdk.ts
+++ b/libs/cua/typescript/src/native/cua_sdk.ts
@@ -11513,9 +11513,10 @@ export type GuestUsage = {
*/
diskUsed: bigint,
/**
- * Disk size, bytes.
+ * Disk size, bytes; absent when the guest's file system has no size
+ * of its own (gVisor's root overlay) or did not say. Never a sentinel.
*/
- diskTotal: bigint,
+ diskTotal?: bigint,
/**
* `disk_total` is the guest's own disk.
*/
@@ -11550,7 +11551,7 @@ const FfiConverterTypeGuestUsage = (() => {
memoryTotal: FfiConverterUInt64.read(from),
memoryLimited: FfiConverterBool.read(from),
diskUsed: FfiConverterUInt64.read(from),
- diskTotal: FfiConverterUInt64.read(from),
+ diskTotal: FfiConverterOptionalUInt64.read(from),
diskLimited: FfiConverterBool.read(from)
};
}
@@ -11562,7 +11563,7 @@ const FfiConverterTypeGuestUsage = (() => {
FfiConverterUInt64.write(value.memoryTotal, into);
FfiConverterBool.write(value.memoryLimited, into);
FfiConverterUInt64.write(value.diskUsed, into);
- FfiConverterUInt64.write(value.diskTotal, into);
+ FfiConverterOptionalUInt64.write(value.diskTotal, into);
FfiConverterBool.write(value.diskLimited, into);
}
allocationSize(value: TypeName): number {
@@ -11573,7 +11574,7 @@ const FfiConverterTypeGuestUsage = (() => {
FfiConverterUInt64.allocationSize(value.memoryTotal) +
FfiConverterBool.allocationSize(value.memoryLimited) +
FfiConverterUInt64.allocationSize(value.diskUsed) +
- FfiConverterUInt64.allocationSize(value.diskTotal) +
+ FfiConverterOptionalUInt64.allocationSize(value.diskTotal) +
FfiConverterBool.allocationSize(value.diskLimited);
}
@@ -15846,6 +15847,74 @@ const FfiConverterTypeResolvedImage = (() => {
return new FFIConverter();
})();
+/**
+ * A base image several Spaces share copy-on-write (a container image's
+ * layers, the image a VM disk was cloned from).
+ */
+export type SharedBase = {
+ /**
+ * Which base: Spaces with the same key share the same blocks.
+ */
+ key: string,
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */
+ image: string,
+ /**
+ * What it takes on this computer, once for all its Spaces; absent when
+ * the runtime cannot tell it apart from the Spaces' own data.
+ */
+ bytes?: bigint,
+ /**
+ * Local Spaces that use it, this one included.
+ */
+ sharedWith: number
+}
+
+/**
+ * Generated factory for {@link SharedBase} record objects.
+ */
+export const SharedBase = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SharedBase, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SharedBase>,
+ });
+})();
+
+const FfiConverterTypeSharedBase = (() => {
+ type TypeName = SharedBase;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ key: FfiConverterString.read(from),
+ image: FfiConverterString.read(from),
+ bytes: FfiConverterOptionalUInt64.read(from),
+ sharedWith: FfiConverterUInt32.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.key, into);
+ FfiConverterString.write(value.image, into);
+ FfiConverterOptionalUInt64.write(value.bytes, into);
+ FfiConverterUInt32.write(value.sharedWith, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.key) +
+ FfiConverterString.allocationSize(value.image) +
+ FfiConverterOptionalUInt64.allocationSize(value.bytes) +
+ FfiConverterUInt32.allocationSize(value.sharedWith);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
/**
* One extra Space on this Mac.
*/
@@ -15875,9 +15944,16 @@ export type SpaceResources = {
*/
usage?: GuestUsage,
/**
- * What it costs this Mac; absent for a container.
+ * What it costs this Mac: its own data only, never the base it
+ * shares; absent when there is nothing to measure.
*/
- diskOnHost?: DiskOnHost
+ diskOnHost?: DiskOnHost,
+ /**
+ * The base image it is a copy-on-write copy of, counted once for all
+ * the Spaces that share it; absent when it has none or the runtime
+ * cannot tell it apart.
+ */
+ base?: SharedBase
}
/**
@@ -15907,7 +15983,8 @@ const FfiConverterTypeSpaceResources = (() => {
memoryAllocated: FfiConverterUInt64.read(from),
diskAllocated: FfiConverterUInt64.read(from),
usage: FfiConverterOptionalTypeGuestUsage.read(from),
- diskOnHost: FfiConverterOptionalTypeDiskOnHost.read(from)
+ diskOnHost: FfiConverterOptionalTypeDiskOnHost.read(from),
+ base: FfiConverterOptionalTypeSharedBase.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -15918,6 +15995,7 @@ const FfiConverterTypeSpaceResources = (() => {
FfiConverterUInt64.write(value.diskAllocated, into);
FfiConverterOptionalTypeGuestUsage.write(value.usage, into);
FfiConverterOptionalTypeDiskOnHost.write(value.diskOnHost, into);
+ FfiConverterOptionalTypeSharedBase.write(value.base, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.id) +
@@ -15926,7 +16004,8 @@ const FfiConverterTypeSpaceResources = (() => {
FfiConverterUInt64.allocationSize(value.memoryAllocated) +
FfiConverterUInt64.allocationSize(value.diskAllocated) +
FfiConverterOptionalTypeGuestUsage.allocationSize(value.usage) +
- FfiConverterOptionalTypeDiskOnHost.allocationSize(value.diskOnHost);
+ FfiConverterOptionalTypeDiskOnHost.allocationSize(value.diskOnHost) +
+ FfiConverterOptionalTypeSharedBase.allocationSize(value.base);
}
};
@@ -45565,6 +45644,9 @@ const FfiConverterOptionalTypeGuestUsage = new FfiConverterOptional(FfiConverter
// FfiConverter for DiskOnHost | undefined
const FfiConverterOptionalTypeDiskOnHost = new FfiConverterOptional(FfiConverterTypeDiskOnHost);
+// FfiConverter for SharedBase | undefined
+const FfiConverterOptionalTypeSharedBase = new FfiConverterOptional(FfiConverterTypeSharedBase);
+
// FfiConverter for Array<SpaceResources>
const FfiConverterSequenceTypeSpaceResources = new FfiConverterArray(FfiConverterTypeSpaceResources);
@@ -47581,6 +47663,7 @@ export default Object.freeze({
FfiConverterTypeShare,
FfiConverterTypeShareAccess,
FfiConverterTypeShareCheck,
+ FfiConverterTypeSharedBase,
FfiConverterTypeSiteLoginOptions,
FfiConverterTypeSiteLoginReport,
FfiConverterTypeSnapshotFallbackOptions,
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index a55c9ad912..06785407e7 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -17924,9 +17924,11 @@ public struct AppGuestUsage: Equatable, Hashable {
*/
public var diskUsed: UInt64
/**
- * Disk size, bytes.
+ * Disk size, bytes; none when the guest's file system has no size of
+ * its own. A sentinel (`i64::MAX`, `u64::MAX`, -1) or 0 reads as none
+ * ([`known_size`]), so no shell ever shows one.
*/
- public var diskTotal: UInt64
+ public var diskTotal: UInt64?
/**
* `disk_total` is the guest's own disk.
*/
@@ -17957,8 +17959,10 @@ public struct AppGuestUsage: Equatable, Hashable {
* Disk in use, bytes.
*/diskUsed: UInt64,
/**
- * Disk size, bytes.
- */diskTotal: UInt64,
+ * Disk size, bytes; none when the guest's file system has no size of
+ * its own. A sentinel (`i64::MAX`, `u64::MAX`, -1) or 0 reads as none
+ * ([`known_size`]), so no shell ever shows one.
+ */diskTotal: UInt64?,
/**
* `disk_total` is the guest's own disk.
*/diskLimited: Bool) {
@@ -17996,7 +18000,7 @@ public struct FfiConverterTypeAppGuestUsage: FfiConverterRustBuffer {
memoryTotal: FfiConverterUInt64.read(from: &buf),
memoryLimited: FfiConverterBool.read(from: &buf),
diskUsed: FfiConverterUInt64.read(from: &buf),
- diskTotal: FfiConverterUInt64.read(from: &buf),
+ diskTotal: FfiConverterOptionUInt64.read(from: &buf),
diskLimited: FfiConverterBool.read(from: &buf)
)
}
@@ -18009,7 +18013,7 @@ public struct FfiConverterTypeAppGuestUsage: FfiConverterRustBuffer {
FfiConverterUInt64.write(value.memoryTotal, into: &buf)
FfiConverterBool.write(value.memoryLimited, into: &buf)
FfiConverterUInt64.write(value.diskUsed, into: &buf)
- FfiConverterUInt64.write(value.diskTotal, into: &buf)
+ FfiConverterOptionUInt64.write(value.diskTotal, into: &buf)
FfiConverterBool.write(value.diskLimited, into: &buf)
}
}
@@ -36688,6 +36692,94 @@ public func FfiConverterTypeAppShareSheetView_lower(_ value: AppShareSheetView)
}
+public struct AppSharedBase: Equatable, Hashable {
+ /**
+ * Spaces with the same key share the same blocks.
+ */
+ public var key: String
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */
+ public var image: String
+ /**
+ * What it takes on this Mac, once; none when the runtime cannot tell
+ * it apart from the Spaces' own data.
+ */
+ public var bytes: UInt64?
+ /**
+ * Local Spaces that use it, this one included.
+ */
+ public var sharedWith: UInt32
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Spaces with the same key share the same blocks.
+ */key: String,
+ /**
+ * The image reference it came from (`ghcr.io/trycua/linux:24.04`).
+ */image: String,
+ /**
+ * What it takes on this Mac, once; none when the runtime cannot tell
+ * it apart from the Spaces' own data.
+ */bytes: UInt64?,
+ /**
+ * Local Spaces that use it, this one included.
+ */sharedWith: UInt32) {
+ self.key = key
+ self.image = image
+ self.bytes = bytes
+ self.sharedWith = sharedWith
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSharedBase: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSharedBase: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSharedBase {
+ return
+ try AppSharedBase(
+ key: FfiConverterString.read(from: &buf),
+ image: FfiConverterString.read(from: &buf),
+ bytes: FfiConverterOptionUInt64.read(from: &buf),
+ sharedWith: FfiConverterUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppSharedBase, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.key, into: &buf)
+ FfiConverterString.write(value.image, into: &buf)
+ FfiConverterOptionUInt64.write(value.bytes, into: &buf)
+ FfiConverterUInt32.write(value.sharedWith, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSharedBase_lift(_ buf: RustBuffer) throws -> AppSharedBase {
+ return try FfiConverterTypeAppSharedBase.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSharedBase_lower(_ value: AppSharedBase) -> RustBuffer {
+ return FfiConverterTypeAppSharedBase.lower(value)
+}
+
+
public struct AppSidebarRow: Equatable, Hashable {
/**
* Space id.
@@ -38960,9 +39052,13 @@ public struct AppSpaceResources: Equatable, Hashable {
*/
public var usage: AppGuestUsage?
/**
- * What it costs this Mac; none for a container.
+ * What it costs this Mac: its own data only, never the base it shares.
*/
public var diskOnHost: AppDiskOnHost?
+ /**
+ * The base image it is a copy-on-write copy of, counted once.
+ */
+ public var base: AppSharedBase?
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -38986,8 +39082,11 @@ public struct AppSpaceResources: Equatable, Hashable {
* The guest's own numbers; none while it is off or unreachable.
*/usage: AppGuestUsage?,
/**
- * What it costs this Mac; none for a container.
- */diskOnHost: AppDiskOnHost?) {
+ * What it costs this Mac: its own data only, never the base it shares.
+ */diskOnHost: AppDiskOnHost?,
+ /**
+ * The base image it is a copy-on-write copy of, counted once.
+ */base: AppSharedBase?) {
self.id = id
self.powerState = powerState
self.cpuAllocated = cpuAllocated
@@ -38995,6 +39094,7 @@ public struct AppSpaceResources: Equatable, Hashable {
self.diskAllocated = diskAllocated
self.usage = usage
self.diskOnHost = diskOnHost
+ self.base = base
}
@@ -39019,7 +39119,8 @@ public struct FfiConverterTypeAppSpaceResources: FfiConverterRustBuffer {
memoryAllocated: FfiConverterUInt64.read(from: &buf),
diskAllocated: FfiConverterUInt64.read(from: &buf),
usage: FfiConverterOptionTypeAppGuestUsage.read(from: &buf),
- diskOnHost: FfiConverterOptionTypeAppDiskOnHost.read(from: &buf)
+ diskOnHost: FfiConverterOptionTypeAppDiskOnHost.read(from: &buf),
+ base: FfiConverterOptionTypeAppSharedBase.read(from: &buf)
)
}
@@ -39031,6 +39132,7 @@ public struct FfiConverterTypeAppSpaceResources: FfiConverterRustBuffer {
FfiConverterUInt64.write(value.diskAllocated, into: &buf)
FfiConverterOptionTypeAppGuestUsage.write(value.usage, into: &buf)
FfiConverterOptionTypeAppDiskOnHost.write(value.diskOnHost, into: &buf)
+ FfiConverterOptionTypeAppSharedBase.write(value.base, into: &buf)
}
}
@@ -40532,7 +40634,7 @@ public struct AppStreamRow: Equatable, Hashable {
*/
public var kind: AppStreamRowKind
/**
- * The one line ("Desktop (1280×800)", a window's title).
+ * The one line ("Desktop", a window's title).
*/
public var label: String
/**
@@ -40562,7 +40664,7 @@ public struct AppStreamRow: Equatable, Hashable {
* Desktop or window.
*/kind: AppStreamRowKind,
/**
- * The one line ("Desktop (1280×800)", a window's title).
+ * The one line ("Desktop", a window's title).
*/label: String,
/**
* The full label, for the tooltip when it is truncated.
@@ -70536,6 +70638,30 @@ fileprivate struct FfiConverterOptionTypeAppShareRemovalNote: FfiConverterRustBu
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppSharedBase: FfiConverterRustBuffer {
+ typealias SwiftType = AppSharedBase?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppSharedBase.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppSharedBase.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif