Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces-macos): a built-in gVisor Linux runtime, so Linux Spaces need no Docker on a Mac (#4493)
ddupont7d4fbac7f7ea
diff --git a/.github/workflows/cd-image-runtime-gvisor.yml b/.github/workflows/cd-image-runtime-gvisor.ymlnew file mode 100644index 0000000000..251c2a9f4c--- /dev/null+++ b/.github/workflows/cd-image-runtime-gvisor.yml@@ -0,0 +1,100 @@+name: "CD: Image runtime-gvisor"++# Builds the disk of the built-in Linux runtime (cua_vmm::managed), the VM a+# Mac with no Docker runs Linux Spaces in, and publishes it to+# ghcr.io/trycua/runtime-gvisor:+#+# build (arch) libs/images/runtime-gvisor/build.sh: Colima's Ubuntu Docker+# disk with gVisor's runsc baked in (versions.env pins every+# input by digest); prints the .raw.gz's sha256 and size+# publish libs/images/runtime-gvisor/push.sh <tag>: <tag>-<arch>+# artifacts (one gzip raw-disk layer each) and the <tag>+# index. Tags are written once (check-tag-safety.sh): there is+# no floating tag, the SDK pins each arch's layer digest in+# libs/cua/crates/cua-vmm/src/managed.rs, so a new disk ships+# with the SDK release that pins it.+#+# Pull requests build only. Publishing runs on runtime-gvisor-v<tag> tags and+# on workflow_dispatch with publish=true; <tag> is versions.env's+# RUNTIME_VERSION, or RUNTIME_VERSION-rcN for a pre-release.+#+# The image is not a Spaces image (no cua-spacesd), so the doctor reports and+# ledger of the Spaces images do not apply. Its gate is the SDK's opt-in test+# on a Mac (sets up the runtime from these bytes, boots it, checks runsc is+# Docker's default runtime): see libs/images/README.md.++on:+ push:+ tags: ["runtime-gvisor-v*"]+ pull_request:+ paths:+ - "libs/images/runtime-gvisor/**"+ - ".github/workflows/cd-image-runtime-gvisor.yml"+ workflow_dispatch:+ inputs:+ tag:+ description: "Tag to publish (RUNTIME_VERSION or RUNTIME_VERSION-rcN)"+ required: true+ publish:+ description: "Push to ghcr.io/trycua/runtime-gvisor"+ type: boolean+ default: false++permissions:+ contents: read++concurrency:+ group: cd-image-runtime-gvisor-${{ github.ref }}+ cancel-in-progress: false++jobs:+ build:+ name: build (${{ matrix.arch }})+ runs-on: ubuntu-24.04+ strategy:+ matrix:+ arch: [arm64, amd64]+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - name: Build the disk+ run: |+ sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends bzip2 pigz+ sudo TMPDIR=/mnt libs/images/runtime-gvisor/build.sh "${{ matrix.arch }}" out+ sudo chown -R "$(id -u):$(id -g)" out+ {+ echo "### runtime-gvisor ${{ matrix.arch }}"+ echo '```'+ cat out/*.sha256+ ls -l out/*.raw.gz+ echo '```'+ } >>"$GITHUB_STEP_SUMMARY"+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: runtime-gvisor-${{ matrix.arch }}+ path: out/+ retention-days: 7++ publish:+ needs: build+ if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.publish)+ runs-on: ubuntu-24.04+ permissions:+ contents: read+ packages: write+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ pattern: runtime-gvisor-*+ path: out+ merge-multiple: true+ - name: Push tools+ run: scripts/images/install-release-tools.sh --push-only+ - name: Push+ env:+ TAG: ${{ github.event_name == 'push' && github.ref_name || inputs.tag }}+ run: |+ tag="${TAG#runtime-gvisor-v}"+ echo "${{ secrets.GITHUB_TOKEN }}" | crane auth login ghcr.io -u "${{ github.actor }}" --password-stdin+ echo "${{ secrets.GITHUB_TOKEN }}" | oras login ghcr.io -u "${{ github.actor }}" --password-stdin+ libs/images/runtime-gvisor/push.sh "$tag" out | tee -a "$GITHUB_STEP_SUMMARY"diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex 21507760a2..5ab4927b83 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -139,7 +139,7 @@ public final class AppModel {defaultLocation: settings.defaultLocation, cloudAvailable: false,localAvailable: true, localReason: nil, localBackends: nil, localDetails: nil,maxCpus: UInt32(max(2, min(16, ProcessInfo.processInfo.activeProcessorCount))),- hostArch: Self.hostArch, lumeSource: nil, storage: nil, cloudPricing: nil, clouds: [], hosts: [],+ hostArch: Self.hostArch, lumeSource: nil, linuxSource: nil, storage: nil, cloudPricing: nil, clouds: [], hosts: [],experiments: settings.experiments, gpus: nil))self.notch = NotchModel()// The notch tiles and the preview cover read one thumbnail store,@@ -383,6 +383,7 @@ public final class AppModel {async let hostsProbe = backend.hosts()let cloud = await backend.cloudAvailable()lumeSource = await backend.lumeSource()+ linuxSource = await backend.linuxSource()await self.cloud.refresh()let (runtimes, storage, pricing, gpus) = await (runtimesProbe, storageProbe, pricingProbe, gpusProbe)hosts = await hostsProbe@@ -404,17 +405,29 @@ public final class AppModel {/// Which Lume macOS Spaces run on (`runtime.lume`), once read.public private(set) var lumeSource: String?+ /// Which engine local Linux Spaces run on (`runtime.linux`), once read.+ public private(set) var linuxSource: String?- /// New Space's "Use built-in Lume": switches `runtime.lume`, then the- /// open wizard reads the runtimes again (This Mac can run it now).+ /// New Space's "Use built-in Lume" / "Use built-in runtime": switches+ /// `runtime.lume` or `runtime.linux`, then the open wizard reads the+ /// runtimes again (This Mac can run it now).public func applyRuntimeSwitch(_ change: AppRuntimeSwitch) async {+ let linux = change.setting == "runtime.linux"do {- try await backend.setLumeSource(change.value)+ if linux {+ try await backend.setLinuxSource(change.value)+ } else {+ try await backend.setLumeSource(change.value)+ }} catch {show(error: LiveSpacesBackend.words(error))return}- lumeSource = await backend.lumeSource() ?? change.value+ if linux {+ linuxSource = await backend.linuxSource() ?? change.value+ } else {+ lumeSource = await backend.lumeSource() ?? change.value+ }let runtimes = await backend.localRuntimes()var e = wizard.envlet backends = runtimes?.ready@@ -423,6 +436,7 @@ public final class AppModel {e.localBackends = backendse.localDetails = runtimes?.detailse.lumeSource = lumeSource+ e.linuxSource = linuxSourcewizard.update(env: e)}@@ -444,7 +458,8 @@ public final class AppModel {localAvailable: backends.map { !$0.isEmpty } ?? true,localReason: backends?.isEmpty == true ? "No local runtime found (Docker or Lume)." : nil,localBackends: backends, localDetails: runtimes?.details, maxCpus: wizard.env.maxCpus,- hostArch: Self.hostArch, lumeSource: lumeSource, storage: storage.map(Self.wizardStorage),+ hostArch: Self.hostArch, lumeSource: lumeSource, linuxSource: linuxSource,+ storage: storage.map(Self.wizardStorage),cloudPricing: available ? pricing : nil, clouds: [], hosts: [],experiments: settings.experiments, gpus: gpus))}@@ -681,7 +696,7 @@ public final class AppModel {experiments: settings.experiments, keyvaultAutoWipe: keyvault.autoWipe,keyvaultUnlockPrompt: keyvault.unlockPromptShows,keyvaultSiteIcons: settings.keyvaultSiteIcons, keyvaultProtection: keyvault.page.protection,- autoConnect: settings.autoConnect, lumeSource: lumeSource))+ autoConnect: settings.autoConnect, lumeSource: lumeSource, linuxSource: linuxSource))}/// Settings, General with Settings, Storage after General while the Cua@@ -774,6 +789,7 @@ public final class AppModel {/// Reads what Settings shows (telemetry, the coding agents).public func loadSettings() async {lumeSource = await backend.lumeSource()+ linuxSource = await backend.linuxSource()telemetryInput = telemetry?.status()readLoginItem()await storage.load()@@ -824,6 +840,13 @@ public final class AppModel {} catch {show(error: LiveSpacesBackend.words(error))}+ case "linux-runtime":+ do {+ try await backend.setLinuxSource(option)+ linuxSource = await backend.linuxSource() ?? option+ } catch {+ show(error: LiveSpacesBackend.words(error))+ }case "default-location":settings.defaultLocation = option == "cloud" ? .cloud : .localsaveSettings()diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swiftindex aa5c0de010..4f2230cdbd 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpacesBackend.swift@@ -49,6 +49,11 @@ public protocol SpacesBackend: AnyObject, Sendable {func lumeSource() async -> String?/// Sets `runtime.lume`.func setLumeSource(_ value: String) async throws+ /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ /// `builtin`, `system`), when known.+ func linuxSource() async -> String?+ /// Sets `runtime.linux`.+ func setLinuxSource(_ value: String) async throws/// Free space where local Spaces are written and which images are/// pulled (`local().storage()`), when known.func localStorage() async -> LocalStorage?@@ -103,6 +108,8 @@ public extension SpacesBackend {func unshare(id: String, who: String) async throws -> [AppShareEntryInput] { [] }func lumeSource() async -> String? { nil }func setLumeSource(_ value: String) async throws {}+ func linuxSource() async -> String? { nil }+ func setLinuxSource(_ value: String) async throws {}}/// The wizard's GPU choices from the SDK's `gpu_support`: the first option@@ -273,10 +280,12 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {try await cua.local().doctor()}guard case .success(let report) = result else { return nil }- // Lume counts as ready when cua sets it up by itself on the first- // macOS create (the built-in Lume): nothing for the person to do.+ // Lume and the built-in Linux runtime count as ready when cua sets+ // them up by itself on the first create that needs them (or boots+ // them): nothing for the person to do.+ let setsUpItself: Set<String> = ["lume", "managed"]let ready = report.checks- .filter { $0.status == .ok || ($0.status == .installable && $0.name.lowercased() == "lume") }+ .filter { $0.status == .ok || ($0.status == .installable && setsUpItself.contains($0.name.lowercased())) }.map { $0.name.lowercased() }var details: [String: String] = [:]for check in report.checks where check.status != .ok { details[check.name.lowercased()] = check.detail }@@ -291,6 +300,14 @@ public final class LiveSpacesBackend: SpacesBackend, @unchecked Sendable {_ = try configSet(key: "runtime.lume", value: value)}+ public func linuxSource() async -> String? {+ (try? configGet(key: "runtime.linux"))?.value+ }++ public func setLinuxSource(_ value: String) async throws {+ _ = try configSet(key: "runtime.linux", value: value)+ }+public func localStorage() async -> LocalStorage? {let result = await withTimeout(seconds: Self.probeSeconds) { [cua] intry await cua.local().storage()@@ -705,6 +722,10 @@ public final class FixtureSpacesBackend: SpacesBackend, @unchecked Sendable {public var fixtureLumeSource: String? = "auto"public func lumeSource() async -> String? { await MainActor.run { fixtureLumeSource } }public func setLumeSource(_ value: String) async throws { await MainActor.run { fixtureLumeSource = value } }+ /// The fixture Mac's `runtime.linux`.+ public var fixtureLinuxSource: String? = "auto"+ public func linuxSource() async -> String? { await MainActor.run { fixtureLinuxSource } }+ public func setLinuxSource(_ value: String) async throws { await MainActor.run { fixtureLinuxSource = value } }public func localBackends() async -> [String]? { await MainActor.run { fixtureBackends } }/// The fixture Mac's free space and pulled images (none: the wizard/// shows no room lines).diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swiftindex c21d34a6db..56f22cfc83 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/SnapshotTests.swift@@ -315,6 +315,36 @@ struct SnapshotTests {try assertSnapshot(Sidebar(model: m).frame(width: 260), "sidebar", size: CGSize(width: 260, height: 520))}+ /// The first Linux Space on a Mac with no Docker: the built-in Linux+ /// runtime's download shows on the new Space's row, in words, with its+ /// bytes (simulated progress).+ @Test func mainWindowSidebarSettingUpLinuxRuntime() async throws {+ let m = try await model()+ let now = Int64(Date().timeIntervalSince1970 * 1000)+ m.sendCreate(.start(id: "pending:linux", name: "linux-dev", os: .linux, provider: .local, now: now,+ image: "ghcr.io/trycua/linux:24.04", kind: .container, hostArch: "arm64",+ gpu: false))+ m.sendCreate(.progress(id: "pending:linux", phase: "preparing", fraction: 0.4, now: now,+ bytesDone: 192 << 20, bytesTotal: 478 << 20, bytesPerSecond: 24e6))+ let space = try #require(m.spaces.first { $0.id == "pending:linux" })+ let detail = m.detail(space)+ #expect(detail.progressText?.contains("of 478 MB") == true)+ let cover = m.cover(detail, requested: false, stream: .noSession)+ let view = HStack(spacing: 0) {+ Sidebar(model: m).frame(width: 260)+ Form {+ Section {+ PreviewCard(session: nil) {+ DesktopCoverView(cover: cover, image: nil, progress: detail.progress,+ progressText: detail.progressText)+ }+ }+ }+ .formStyle(.grouped)+ }+ try assertSnapshot(view, "setting-up-linux-runtime", size: CGSize(width: 820, height: 420))+ }+/// The power button next to Delete on the rows: a suspended Space/// (selected: Resume), a macOS VM turning off (a spinner), and one whose/// turn-off failed (why, inline).diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/setting-up-linux-runtime.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/setting-up-linux-runtime.pngnew file mode 100644index 0000000000..1923ddb0f0Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/setting-up-linux-runtime.png differdiff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.pngindex 8c549355af..ff279a1872 100644Binary files a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/settings-keyvault.png differdiff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swiftindex 8ffe8900c0..2d76bf2af2 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift@@ -371,6 +371,15 @@ struct ViewModelTests {#expect(model.lumeSource == "builtin")#expect(model.settingsPage.sections.first { $0.id == "runtimes" }!.rows[0].options.first(where: \.active)?.id == "builtin")+ // Linux picks runtime.linux (the built-in Linux runtime).+ let linux = model.settingsPage.sections.first { $0.id == "runtimes" }!.rows+ .first { $0.id == "linux-runtime" }!+ #expect(linux.label == "Linux")+ #expect(linux.options.first(where: \.active)?.id == "auto")+ await model.choose(row: "linux-runtime", option: "system")+ #expect(model.linuxSource == "system")+ #expect(model.settingsPage.sections.first { $0.id == "runtimes" }!.rows+ .first { $0.id == "linux-runtime" }!.options.first(where: \.active)?.id == "system")#expect(model.chrome.signInLabel == "Sign in")await model.press(row: "sign-in")#expect(model.identity == "[email protected]")diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdxindex 7329eb5c3b..e3c328a9ab 100644--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/new-space.mdx@@ -309,6 +309,7 @@ Returned by [`app_wizard_env_from_json`](#app_wizard_env_from_json).| `max_cpus` / `maxCpus` | `u32` | | Upper bound for the CPU slider. || `host_arch` / `hostArch` | `Option<String>` | | This machine's architecture (`arm64`, `amd64`), when known. || `lume_source` / `lumeSource` | `Option<String>` | | Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`, `system`), when known. |+| `linux_source` / `linuxSource` | `Option<String>` | | Which engine local Linux Spaces run on (`runtime.linux`: `auto`, `builtin`, `system`), when known (a Mac). || `storage` | [`Option<AppLocalStorage>`](#applocalstorage-record) | | Free space and pulled images here (the SDK's `Local.storage()`), when known. || `cloud_pricing` / `cloudPricing` | [`Option<AppCloudPricing>`](#appcloudpricing-record) | | This account's Cua Cloud rates, when known (no estimate without). || `clouds` | [`Vec<AppConnectedCloud>`](/cua-sdk/reference/spaces/app-core/cloud#appconnectedcloud-record) | | The user's connected clouds (`cloud_status`), for "Your cloud" (offered only while its experiment is on: `offered_clouds`). |diff --git a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdxindex 13436a8314..7f5c8b4d9f 100644--- a/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/app-core/window.mdx@@ -625,6 +625,7 @@ Returned by [`app_settings_input_from_json`](#app_settings_input_from_json).| `keyvault_protection` / `keyvaultProtection` | [`Vec<AppFact>`](#appfact-record) | | The Keyvault's protection facts (Touch ID, the daemon's signature), shown in the section. || `auto_connect` / `autoConnect` | `Option<bool>` | | "Connect to the desktop automatically" (none: no row; a shell without the preview cover leaves it out). || `lume_source` / `lumeSource` | `Option<String>` | | Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`, `system`); none: no Runtimes section. |+| `linux_source` / `linuxSource` | `Option<String>` | | Which engine local Linux Spaces run on (`runtime.linux`: `auto`, `builtin`, `system`); none: no Linux row. |## `AppSettingsOption` recorddiff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rsindex 1e99adb128..e4dc421299 100644--- a/libs/cua/crates/cua-daemon/src/local.rs+++ b/libs/cua/crates/cua-daemon/src/local.rs@@ -35,6 +35,7 @@ use cua_vmm::{auto::{self, DoctorReport},container::{ContainerConfig, ContainerRuntime},lume::LumeRuntime,+ managed::{self, LinuxSource},qemu::{QemuConfig, QemuRuntime},};use std::{path::Path, sync::Arc};@@ -413,11 +414,22 @@ fn endpoints_of(e: Endpoints) -> LocalEndpoints {/// `cua-vmm` behind [`LocalRuntime`].pub struct VmmLocal {container_cfg: ContainerConfig,- container: tokio::sync::OnceCell<Arc<ContainerRuntime>>,+ /// The container engine, and the `runtime.linux` setting it was chosen+ /// for (chosen again when the setting changes).+ container: tokio::sync::Mutex<Option<(LinuxSource, Engine)>>,qemu: Arc<QemuRuntime>,lume: Arc<LumeRuntime>,}+/// The container engine [`VmmLocal`] uses.+#[derive(Clone)]+enum Engine {+ /// This Mac's own (Docker Desktop, Colima, OrbStack, a Linux dockerd).+ System(Arc<ContainerRuntime>),+ /// The built-in Linux runtime (its VM boots on demand).+ Builtin(Arc<managed::ManagedContainers>),+}+impl Default for VmmLocal {fn default() -> Self {Self::new(ContainerConfig::default())@@ -434,22 +446,47 @@ impl VmmLocal {});Self {container_cfg,- container: tokio::sync::OnceCell::new(),+ container: tokio::sync::Mutex::new(None),qemu: Arc::new(qemu),lume: Arc::new(LumeRuntime::with_defaults()),}}- /// The container backend (connects to the engine on first use).+ /// The engine local Linux Spaces use ([`managed::choose`]): this Mac's+ /// own, or the built-in runtime. Chosen on first use, without booting+ /// anything.+ async fn engine(&self) -> std::result::Result<Engine, VmmError> {+ let source = LinuxSource::current();+ let mut slot = self.container.lock().await;+ if let Some((s, e)) = slot.as_ref()+ && *s == source+ {+ return Ok(e.clone());+ }+ let e = match managed::choose(self.container_cfg.clone(), source).await? {+ managed::Choice::System(rt) => Engine::System(Arc::new(*rt)),+ managed::Choice::Builtin(m) => Engine::Builtin(m),+ };+ *slot = Some((source, e.clone()));+ Ok(e)+ }++ /// The container backend (connects to the engine on first use, and+ /// boots the built-in Linux runtime when that is the engine).pub async fn container(&self) -> std::result::Result<Arc<ContainerRuntime>, VmmError> {- self.container- .get_or_try_init(|| async {- Ok(Arc::new(- ContainerRuntime::connect(self.container_cfg.clone()).await?,- ))- })- .await- .cloned()+ match self.engine().await? {+ Engine::System(rt) => Ok(rt),+ Engine::Builtin(m) => m.engine().await,+ }+ }++ /// The container backend when its engine is up; never boots the+ /// built-in Linux runtime.+ pub async fn container_if_up(&self) -> Option<Arc<ContainerRuntime>> {+ match self.engine().await.ok()? {+ Engine::System(rt) => Some(rt),+ Engine::Builtin(m) => m.engine_if_running().await,+ }}/// The QEMU backend.@@ -462,7 +499,10 @@ impl VmmLocal {kind: BackendKind,) -> std::result::Result<Arc<dyn VmmRuntime>, VmmError> {Ok(match kind {- BackendKind::Container => self.container().await? as Arc<dyn VmmRuntime>,+ BackendKind::Container => match self.engine().await? {+ Engine::System(rt) => rt as Arc<dyn VmmRuntime>,+ Engine::Builtin(m) => m as Arc<dyn VmmRuntime>,+ },BackendKind::Lume => self.lume.clone() as Arc<dyn VmmRuntime>,_ => self.qemu.clone() as Arc<dyn VmmRuntime>,})@@ -649,11 +689,18 @@ impl LocalRuntime for VmmLocal {out.push(self.lume.gpu_support());}out.push(self.qemu.gpu_support().await);- match self.container().await {- Ok(rt) => {+ match self.engine().await {+ Ok(Engine::System(rt)) => {out.push(rt.gpu_support_for("container").await);out.push(rt.gpu_support_for("gvisor").await);}+ // The built-in runtime's VM has no GPU (and is not booted to+ // say so).+ Ok(Engine::Builtin(_)) => {+ for r in ["container", "gvisor"] {+ out.push(cua_vmm::gpu::container_support("macos", r, false));+ }+ }Err(e) => {for r in ["container", "gvisor"] {out.push(cua_sandbox_core::gpu::GpuSupport::none(@@ -852,11 +899,16 @@ impl LocalRuntime for VmmLocal {}/// Containers pause in memory (`docker pause`) and QEMU VMs pause over- /// QMP; Lume has no pause, so a Lume VM stops and boots again.+ /// QMP; Lume has no pause, so a Lume VM stops and boots again. On the+ /// built-in Linux runtime containers stop too, so its VM can stop once+ /// no Linux Space runs (a paused one would hold it up).fn power_control(&self, runtime_type: &str) -> Option<cua_sandbox_core::PowerControl> {use cua_sandbox_core::PowerControl;match runtime_type.trim().to_ascii_lowercase().as_str() {"lume" => Some(PowerControl::Stop),+ "gvisor" | "runsc" | "runc" | "container" | "docker" if managed::in_use() => {+ Some(PowerControl::Stop)+ }"gvisor" | "runsc" | "runc" | "container" | "docker" | "qemu-docker" | "qemu" => {Some(PowerControl::Suspend)}diff --git a/libs/cua/crates/cua-daemon/src/storage.rs b/libs/cua/crates/cua-daemon/src/storage.rsindex 1b85efb53d..5472ce1511 100644--- a/libs/cua/crates/cua-daemon/src/storage.rs+++ b/libs/cua/crates/cua-daemon/src/storage.rs@@ -112,11 +112,9 @@ async fn pulled_containers(entries: &[&cua_image::catalog::CatalogEntry]) -> Vecif wanted.is_empty() {return vec![];}- let Ok(Ok(rt)) = tokio::time::timeout(- PROBE,- cua_vmm::container::ContainerRuntime::connect(Default::default()),- )- .await+ // The engine Linux Spaces use; the built-in runtime only while it runs.+ let Ok(Some(rt)) =+ tokio::time::timeout(PROBE, cua_vmm::managed::connect_if_up(Default::default())).awaitelse {return vec![];};diff --git a/libs/cua/crates/cua-disk/src/docker.rs b/libs/cua/crates/cua-disk/src/docker.rsindex 95cf77234e..ec25f624c8 100644--- a/libs/cua/crates/cua-disk/src/docker.rs+++ b/libs/cua/crates/cua-disk/src/docker.rs@@ -83,14 +83,13 @@ pub trait DockerApi: Send + Sync {async fn remove_volume(&self, name: &str) -> Result<(), String>;}-/// The engine the SDK would use (discovered like the docker CLI), when it-/// answers within a few seconds. Never starts an engine.+/// The engine the SDK would use (this Mac's own, discovered like the docker+/// CLI, or the built-in Linux runtime while it runs), when it answers within+/// a few seconds. Never starts an engine.pub async fn connect() -> Option<Arc<dyn DockerApi>> {- let fut = cua_vmm::container::ContainerRuntime::connect(- cua_vmm::container::ContainerConfig::default(),- );+ let fut = cua_vmm::managed::connect_if_up(cua_vmm::container::ContainerConfig::default());match tokio::time::timeout(Duration::from_secs(5), fut).await {- Ok(Ok(rt)) => Some(Arc::new(Engine(rt.docker().clone()))),+ Ok(Some(rt)) => Some(Arc::new(Engine(rt.docker().clone()))),_ => None,}}diff --git a/libs/cua/crates/cua-sandbox-core/src/lib.rs b/libs/cua/crates/cua-sandbox-core/src/lib.rsindex 08c3ed97e0..4b142f8741 100644--- a/libs/cua/crates/cua-sandbox-core/src/lib.rs+++ b/libs/cua/crates/cua-sandbox-core/src/lib.rs@@ -29,11 +29,14 @@ pub use cua_vmm::gpu;/// the guest), reported to the [`progress::scope`] that started it.pub use cua_vmm::progress;-/// Deletes the runtimes cua set up itself (the built-in Lume under-/// `$CUA_HOME/runtimes`). A runtime the user installed is never touched;-/// the built-in one is set up again the next time a Space needs it.-pub fn remove_builtin_runtimes() -> std::result::Result<(), String> {- cua_vmm::lume::builtin::remove().map_err(|e| e.to_string())+/// Deletes the runtimes cua set up itself under `$CUA_HOME/runtimes`: the+/// built-in Lume, and the built-in Linux runtime's VM with its disks. A+/// runtime the user installed is never touched; a built-in one is set up+/// again the next time a Space needs it.+pub async fn remove_builtin_runtimes() -> std::result::Result<(), String> {+ let lume = cua_vmm::lume::builtin::remove().map_err(|e| e.to_string());+ let linux = cua_vmm::managed::remove().await.map_err(|e| e.to_string());+ lume.and(linux)}/// Cancels a create ([`Sandboxes::create_cancellable`]).pub use tokio_util::sync::CancellationToken;diff --git a/libs/cua/crates/cua-sandbox-core/src/settings.rs b/libs/cua/crates/cua-sandbox-core/src/settings.rsindex ac135af2c2..f5c04e77cd 100644--- a/libs/cua/crates/cua-sandbox-core/src/settings.rs+++ b/libs/cua/crates/cua-sandbox-core/src/settings.rs@@ -36,7 +36,7 @@ pub struct Key {}/// Every setting, in display order.-pub const KEYS: [Key; 8] = [+pub const KEYS: [Key; 9] = [Key {name: "default.on",env: "CUA_DEFAULT_ON",@@ -85,6 +85,12 @@ pub const KEYS: [Key; 8] = [default: "auto",description: "the Lume macOS Spaces run on: auto (this Mac's own, else built-in), builtin (cua's pinned, signed Lume, set up on first use) or system (only this Mac's own; nothing is downloaded)",},+ Key {+ name: "runtime.linux",+ env: "CUA_RUNTIME_LINUX",+ default: "auto",+ description: "the engine local Linux Spaces run on, on a Mac: auto (a working Docker engine on this Mac, else built-in; built-in once it exists), builtin (cua's own VM with Docker and gVisor, set up on first use) or system (only this Mac's own engine; nothing is downloaded)",+ },];/// Short names `cua config` accepts for a setting.@@ -428,6 +434,14 @@ pub fn normalize(key: Key, value: &str) -> Result<String, SettingsError> {})?.as_str().to_string(),+ "runtime.linux" => cua_vmm::managed::LinuxSource::parse(v)+ .ok_or_else(|| {+ SettingsError(format!(+ "runtime.linux: expected auto, builtin or system, got {v:?}"+ ))+ })?+ .as_str()+ .to_string(),"telemetry.enabled" => match v.to_ascii_lowercase().as_str() {"1" | "true" | "yes" | "on" => "on".into(),"0" | "false" | "no" | "off" => "off".into(),diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex cf63609d43..2a4412b7e7 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -610,9 +610,10 @@ impl Host {let home = self.home.clone();run(async move {cua_host::Host::new(home).remove().await?;- // Then the runtimes cua set up itself (the built-in Lume, set up- // again on the next create that needs it); the user's own stay.- if let Err(e) = cua_sandbox_core::remove_builtin_runtimes() {+ // Then the runtimes cua set up itself (the built-in Lume and the+ // built-in Linux runtime, set up again on the next create that+ // needs them); the user's own stay.+ if let Err(e) = cua_sandbox_core::remove_builtin_runtimes().await {tracing::warn!("could not remove the built-in runtimes: {e}");}Ok(())diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rsindex 6ee068fba1..5c1cbee742 100644--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs@@ -275,6 +275,10 @@ pub struct SettingsInput {/// `system`); none: no Runtimes section.#[serde(default)]pub lume_source: Option<String>,+ /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ /// `builtin`, `system`); none: no Linux row.+ #[serde(default)]+ pub linux_source: Option<String>,}impl Default for SettingsInput {@@ -300,6 +304,7 @@ impl Default for SettingsInput {keyvault_protection: vec![],auto_connect: None,lume_source: None,+ linux_source: None,}}}@@ -664,8 +669,11 @@ pub fn page(input: &SettingsInput) -> SettingsPage {},];- if let Some(source) = input.lume_source.as_deref() {- sections.push(runtimes_section(source));+ if input.lume_source.is_some() || input.linux_source.is_some() {+ sections.push(runtimes_section(+ input.lume_source.as_deref(),+ input.linux_source.as_deref(),+ ));}if let Some(t) = &input.telemetry {@@ -750,30 +758,48 @@ pub fn page(input: &SettingsInput) -> SettingsPage {pub const MACOS_RUNTIME_HELP: &str ="Built-in is Cua\u{2019}s signed Lume, downloaded the first time you need it (6 MB).";-/// Settings, Runtimes: one row per local runtime Cua can provide itself.-/// macOS VMs: Automatic, Built-in (Cua's signed Lume, set up on first use)-/// or System (this Mac's own Lume only). The row's id is `macos-runtime`;-/// its options are `runtime.lume`'s values.-pub fn runtimes_section(lume_source: &str) -> SettingsSection {+/// The help under Settings, Runtimes, Linux.+pub const LINUX_RUNTIME_HELP: &str =+ "Built-in is a gVisor Linux VM, downloaded the first time you need it (480 MB).";++/// Settings, Runtimes: one row per local runtime Cua can provide itself,+/// each Automatic, Built-in or System.+/// * macOS VMs (`macos-runtime`, `runtime.lume`'s values): Built-in is+/// Cua's signed Lume, set up on first use; System this Mac's own Lume.+/// * Linux (`linux-runtime`, `runtime.linux`'s values): Built-in is Cua's+/// own VM with Docker and gVisor, set up on first use; System this Mac's+/// own container engine; Automatic Docker when it runs, else built-in.+pub fn runtimes_section(lume_source: Option<&str>, linux_source: Option<&str>) -> SettingsSection {use SettingsRowKind::*;- let source = match lume_source {- "builtin" | "system" => lume_source,- _ => "auto",+ let choice = |id: &str, label: &str, source: &str| {+ let source = match source {+ "builtin" | "system" => source,+ _ => "auto",+ };+ let mut r = row(id, Choice, label);+ r.options = vec![+ opt("auto", "Automatic", source == "auto"),+ opt("builtin", "Built-in", source == "builtin"),+ opt("system", "System", source == "system"),+ ];+ r};- let mut macos = row("macos-runtime", Choice, "macOS VMs");- macos.options = vec![- opt("auto", "Automatic", source == "auto"),- opt("builtin", "Built-in", source == "builtin"),- opt("system", "System", source == "system"),- ];- let note = row("macos-runtime-note", Note, MACOS_RUNTIME_HELP);+ let mut rows = vec![];+ if let Some(source) = lume_source {+ rows.push(choice("macos-runtime", "macOS VMs", source));+ rows.push(row("macos-runtime-note", Note, MACOS_RUNTIME_HELP));+ }+ if let Some(source) = linux_source {+ rows.push(choice("linux-runtime", "Linux", source));+ rows.push(row("linux-runtime-note", Note, LINUX_RUNTIME_HELP));+ }SettingsSection {id: "runtimes".into(),title: "Runtimes".into(),button: None,button_enabled: false,button_help: None,- rows: vec![macos, note],+ rows,}}@@ -837,6 +863,39 @@ mod tests {assert_eq!(ids, ["Automatic", "Built-in", "System"]);}+ #[test]+ fn the_runtimes_section_shows_the_linux_choice() {+ let page = page(&SettingsInput {+ lume_source: Some("auto".into()),+ linux_source: Some("builtin".into()),+ ..Default::default()+ });+ let s = page.sections.iter().find(|s| s.id == "runtimes").unwrap();+ let ids: Vec<_> = s.rows.iter().map(|r| r.id.as_str()).collect();+ assert_eq!(+ ids,+ [+ "macos-runtime",+ "macos-runtime-note",+ "linux-runtime",+ "linux-runtime-note"+ ]+ );+ let linux = &s.rows[2];+ assert_eq!(linux.label, "Linux");+ let active: Vec<_> = linux+ .options+ .iter()+ .filter(|o| o.active)+ .map(|o| o.id.as_str())+ .collect();+ assert_eq!(active, ["builtin"]);+ // An unknown word reads as Automatic.+ let r = runtimes_section(None, Some("docker"));+ assert_eq!(r.rows[0].id, "linux-runtime");+ assert!(r.rows[0].options[0].active);+ }+#[test]fn hotkeys_need_a_modifier() {let c = KeyCombo {diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rsindex 1234caaa8d..18ceda2550 100644--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs@@ -686,6 +686,13 @@ pub fn reduce(state: &CreatesState, action: &CreateAction) -> CreatesState {}p.phase = phase.clone();p.fraction = *fraction;+ // Setting up a runtime: its download done, its boot reports+ // a fraction only (no bytes left to show).+ if phase == "preparing" && bytes_done.is_none() && fraction.is_some() {+ p.bytes_done = None;+ p.bytes_total = None;+ p.bytes_per_second = None;+ }if bytes_done.is_some() {p.bytes_done = *bytes_done;p.bytes_total = bytes_total.or(p.bytes_total);@@ -885,10 +892,11 @@ pub fn deleting_space(space: &Space) -> Space {s}-/// Bytes move while the create is still preparing: the SDK is setting up-/// the local runtime it needs (downloaded once, on first use).+/// The create is still preparing but moves (bytes, or a fraction): the+/// SDK is setting up the local runtime it needs (downloaded once, on first+/// use, then booted: the built-in Linux runtime's VM).fn setting_up_runtime(p: &PendingCreate) -> bool {- p.phase == "preparing" && p.bytes_total.is_some_and(|t| t > 0)+ p.phase == "preparing" && (p.bytes_total.is_some_and(|t| t > 0) || p.fraction.is_some())}/// A pending create as a Space row.@@ -905,10 +913,10 @@ pub fn pending_space(p: &PendingCreate) -> Space {} else if setting_up_runtime(p) {// Bytes before the image: the runtime cua sets up on first use// (the built-in Lume for a macOS Space).- if p.os == SpaceOs::Macos {- "Setting up Lume\u{2026}".to_string()- } else {- "Setting up the runtime\u{2026}".to_string()+ match p.os {+ SpaceOs::Macos => "Setting up Lume\u{2026}".to_string(),+ SpaceOs::Linux => "Setting up Linux runtime\u{2026}".to_string(),+ _ => "Setting up the runtime\u{2026}".to_string(),}} else {phase_label(&p.phase).to_string()@@ -1086,6 +1094,57 @@ mod tests {);}+ /// The first Linux create on a Mac with no Docker: the built-in Linux+ /// runtime's download, then its VM's boot, show on the Space's row.+ #[test]+ fn the_linux_runtime_set_up_shows_its_download_then_its_boot() {+ let s = reduce(+ &CreatesState::default(),+ &start("pending:l", "", SpaceOs::Linux),+ );+ let prep = |fraction: f64, bytes: Option<(u64, u64)>| CreateAction::Progress {+ id: "pending:l".into(),+ phase: "preparing".into(),+ fraction: Some(fraction),+ now: Some(2_000),+ bytes_done: bytes.map(|b| b.0),+ bytes_total: bytes.map(|b| b.1),+ bytes_per_second: bytes.map(|_| 5e7),+ };+ let s = reduce(&s, &prep(0.5, Some((240 << 20, 480 << 20))));+ let row = pending_space(&s.pending[0]);+ assert_eq!(+ row.detail,+ "This Mac \u{b7} Setting up Linux runtime\u{2026}"+ );+ assert!(row.progress.unwrap().transfer.unwrap().contains("MB"));+ // The boot: still setting up, no bytes any more.+ let s = reduce(&s, &prep(0.3, None));+ let p = pending_space(&s.pending[0]).progress.unwrap();+ assert_eq!(p.label, "Setting up Linux runtime\u{2026}");+ assert!(p.transfer.is_none());+ // Plain preparing (resolving the image) says what it always did.+ let plain = reduce(+ &reduce(+ &CreatesState::default(),+ &start("pending:p", "", SpaceOs::Linux),+ ),+ &CreateAction::Progress {+ id: "pending:p".into(),+ phase: "preparing".into(),+ fraction: None,+ now: Some(2_000),+ bytes_done: None,+ bytes_total: None,+ bytes_per_second: None,+ },+ );+ assert_ne!(+ pending_space(&plain.pending[0]).progress.unwrap().label,+ "Setting up Linux runtime\u{2026}"+ );+ }+#[test]fn a_download_shows_its_bytes_rate_and_time_left() {let s = reduce(diff --git a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs b/libs/cua/crates/cua-spaces-app-core/src/wizard.rsindex 7df3d13e3a..00514d50c2 100644--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs@@ -814,14 +814,26 @@ fn follow_to_host(state: &mut WizardState, env: &WizardEnv) {}}-/// Switching to the built-in Lume, when macOS VMs are set to use this-/// Mac's own Lume (`runtime.lume = system`) and it is missing. Otherwise-/// cua sets up its built-in Lume by itself on the first macOS create.+/// Switching to a built-in runtime, when the setting says to use only+/// this Mac's own and it is missing: the built-in Lume for macOS VMs+/// (`runtime.lume = system`), the built-in Linux runtime for containers+/// (`runtime.linux = system`). Otherwise cua sets up its built-in one by+/// itself on the first create that needs it.fn runtime_switch(image: &SandboxImage, env: &WizardEnv) -> Option<RuntimeSwitch> {- if image.local != Some(LocalEngine::Lume) || local_ready(image, env) {+ if local_ready(image, env) {return None;}- if env.lume_source.as_deref() != Some("system") {+ if image.local == Some(LocalEngine::Container) {+ return (env.linux_source.as_deref() == Some("system")).then(|| RuntimeSwitch {+ setting: "runtime.linux".into(),+ value: "builtin".into(),+ label: "Use built-in runtime".into(),+ detail: "Cua sets up its own Linux runtime, a small VM that runs Spaces under \+ gVisor (about 480 MB), the first time you create a Linux Space."+ .into(),+ });+ }+ if image.local != Some(LocalEngine::Lume) || env.lume_source.as_deref() != Some("system") {return None;}if env.host_arch.as_deref().is_some_and(|a| a != "arm64") {@@ -1020,6 +1032,10 @@ pub struct WizardEnv {/// `system`), when known.#[serde(default)]pub lume_source: Option<String>,+ /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ /// `builtin`, `system`), when known (a Mac).+ #[serde(default)]+ pub linux_source: Option<String>,/// Free space and pulled images here (the SDK's `Local.storage()`),/// when known.#[serde(default)]@@ -2617,9 +2633,12 @@ pub fn view(state: &WizardState, env: &WizardEnv) -> WizardView {Location::Host => host_why.clone().unwrap_or_else(|| "Choose a machine.".to_string()),- Location::Local if runtime_switch.is_some() => {- "This Mac\u{2019}s own Lume isn\u{2019}t installed.".to_string()- }+ Location::Local if runtime_switch.is_some() => match image.local {+ Some(LocalEngine::Container) => {+ "No container engine is running on this Mac.".to_string()+ }+ _ => "This Mac\u{2019}s own Lume isn\u{2019}t installed.".to_string(),+ },Location::Local => {if env.local_available {let what = match image.local {@@ -2996,6 +3015,7 @@ mod tests {max_cpus: 8,host_arch: Some("arm64".into()),lume_source: None,+ linux_source: None,storage: None,cloud_pricing: None,clouds: vec![],@@ -3842,6 +3862,57 @@ mod tests {assert!(view(&s, &intel).runtime_switch.is_none());}+ /// A Linux Space with no Docker: the built-in Linux runtime counts as+ /// ready (set up on the first create). Set to use only this Mac's own+ /// engine and with none running, the error says so and offers the+ /// built-in runtime in one click.+ #[test]+ fn linux_runs_on_the_builtin_runtime_or_offers_it() {+ let builtin = WizardEnv {+ local_backends: Some(vec!["managed".into()]),+ linux_source: Some("auto".into()),+ ..env()+ };+ let s = reduce(+ &initial(&builtin),+ &WizardAction::ChooseOs { os: SpaceOs::Linux },+ &builtin,+ );+ let v = view(&s, &builtin);+ assert_eq!(v.placement_id, "local");+ assert!(v.placement_error.is_none() && v.runtime_switch.is_none());+ assert!(v.can_continue);++ let system = WizardEnv {+ local_available: false,+ local_reason: Some("No local runtime found (Docker or Lume).".into()),+ local_backends: Some(vec![]),+ linux_source: Some("system".into()),+ ..env()+ };+ let v = view(&s, &system);+ assert_eq!(+ v.placement_error.as_deref(),+ Some("No container engine is running on this Mac.")+ );+ let switch = v.runtime_switch.expect("built-in offered");+ assert_eq!(+ (+ switch.setting.as_str(),+ switch.value.as_str(),+ switch.label.as_str()+ ),+ ("runtime.linux", "builtin", "Use built-in runtime")+ );+ assert!(!v.can_continue);+ // Automatic needs no switch: cua sets the built-in one up itself.+ let auto = WizardEnv {+ linux_source: Some("auto".into()),+ ..system.clone()+ };+ assert!(view(&s, &auto).runtime_switch.is_none());+ }+/// With your other Mac online and This Mac unable to run the image,/// New Space starts on that Mac, by name; a choice the person made/// stays.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.rsindex 0e289ab143..3538190fc6 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@@ -3130,6 +3130,9 @@ pub struct AppWizardEnv {/// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,/// `system`), when known.pub lume_source: Option<String>,+ /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ /// `builtin`, `system`), when known (a Mac).+ pub linux_source: Option<String>,/// Free space and pulled images here (the SDK's `Local.storage()`),/// when known.pub storage: Option<AppLocalStorage>,@@ -6307,6 +6310,9 @@ pub struct AppSettingsInput {/// Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,/// `system`); none: no Runtimes section.pub lume_source: Option<String>,+ /// Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ /// `builtin`, `system`); none: no Linux row.+ pub linux_source: Option<String>,}/// How a Settings row draws.diff --git a/libs/cua/crates/cua-vmm/src/auto.rs b/libs/cua/crates/cua-vmm/src/auto.rsindex efd8ce1eca..d193518fcf 100644--- a/libs/cua/crates/cua-vmm/src/auto.rs+++ b/libs/cua/crates/cua-vmm/src/auto.rs@@ -316,21 +316,16 @@ pub async fn doctor() -> DoctorReport {.push("a Docker-API container engine".into());}}- if !container_status.ready {- container_status.provisioning.push(- "boot the managed cua-runtime VM (containerd + runsc) — see cua_vmm::managed".into(),- );+ let managed_status = managed_status(+ crate::managed::LinuxSource::current(),+ container_status.ready,+ );+ if !container_status.ready && managed_status.provisionable {+ container_status+ .provisioning+ .push("use the built-in Linux runtime (a VM with Docker and gVisor)".into());}- let managed_status = BackendStatus {- backend: BackendKind::Managed,- ready: false,- provisionable: qemu_status.ready || lume_status.ready,- detail: crate::managed::STATUS.into(),- missing: vec![],- provisioning: vec![],- };-DoctorReport {host,backends: vec![lume_status, qemu_status, container_status, managed_status],@@ -340,6 +335,46 @@ pub async fn doctor() -> DoctorReport {}}+/// The built-in Linux runtime ([`crate::managed`]) for `doctor`: ready+/// while its VM runs; else used (set up or booted on demand) when the+/// `runtime.linux` setting picks it here.+fn managed_status(source: crate::managed::LinuxSource, engine_ready: bool) -> BackendStatus {+ use crate::managed::{self, LinuxSource};+ let mb = managed::first_use_download() >> 20;+ let picked = source.allows_builtin()+ && (source == LinuxSource::Builtin || managed::exists() || !engine_ready);+ let running = picked && managed::running();+ BackendStatus {+ backend: BackendKind::Managed,+ ready: running,+ provisionable: picked && !running,+ detail: if !managed::supported() {+ "the built-in Linux runtime runs on macOS".into()+ } else if source == LinuxSource::System {+ "Linux Spaces are set to use this Mac's own container engine".into()+ } else if running {+ "built-in Linux runtime running (gVisor)".into()+ } else if picked && managed::exists() {+ "built-in Linux runtime, started on demand".into()+ } else if picked {+ format!("{}, about {mb} MB", managed::STATUS)+ } else {+ "not used: this Mac's own container engine runs Linux Spaces".into()+ },+ missing: vec![],+ provisioning: if picked && !running && !managed::exists() {+ vec![+ format!("download the built-in Linux runtime (about {mb} MB)"),+ "boot its VM".into(),+ ]+ } else if picked && !running {+ vec!["boot its VM".into()]+ } else {+ vec![]+ },+ }+}+/// Choose a backend for `req` given a [`doctor`] report.pub fn select(req: &SelectRequest, report: &DoctorReport) -> Result<Selection> {let host = &report.host;@@ -360,11 +395,18 @@ pub fn select(req: &SelectRequest, report: &DoctorReport) -> Result<Selection> {provisioning: c.provisioning,});}+ if let Some(m) = status(BackendKind::Managed).filter(|m| m.ready || m.provisionable) {+ return Ok(Selection {+ backend: BackendKind::Container,+ reason: "the built-in Linux runtime (Docker in a VM); isolation: gVisor".into(),+ provisioning: m.provisioning,+ });+ }Err(VmmError::missing("a container engine",format!(- "{}. The managed cua-runtime VM is not available yet; install Colima (`brew install colima docker && colima start`) \- or Docker Engine",+ "{}. Install Docker (or Colima), or set `runtime.linux` to `auto` to use \+ the built-in Linux runtime on a Mac",c.detail),))diff --git a/libs/cua/crates/cua-vmm/src/managed.rs b/libs/cua/crates/cua-vmm/src/managed.rsindex f74b5a81e1..796d067678 100644--- a/libs/cua/crates/cua-vmm/src/managed.rs+++ b/libs/cua/crates/cua-vmm/src/managed.rs@@ -1,48 +1,1235 @@-//! The managed **cua-runtime** VM: a container engine the SDK boots itself-//! when the host has none.+//! The built-in Linux runtime: a small VM cua sets up and boots itself, so+//! Linux Spaces run on a Mac with no Docker, under gVisor, with no setup.//!-//! # Design+//! # How it works//!-//! Goal (plan §1.1): run gVisor rootfs images with zero pre-setup on hosts-//! with no Docker-compatible engine (a bare Mac, a CI box without Docker).-//!-//! * **Image.** A small Linux VM image, `ghcr.io/trycua/cua-runtime:<ver>`,-//! published as a multi-arch containerDisk (`FROM scratch` + `/disk/disk.img`,-//! amd64 + arm64). Debian genericcloud base + `containerd`, `runsc`-//! (registered as the default runtime), `dockerd` for the Docker Engine API,-//! and nothing else. Built by the `cua-image` local builder from an-//! `images.cua.ai/v1alpha1` spec, so it dogfoods the builder.-//! * **Boot.** macOS Apple Silicon: the [`crate::lume`] backend (VZ, raw disk,-//! cloud-init seed via `--mount`), falling back to [`crate::qemu`] with HVF.-//! Linux: [`crate::qemu`] with KVM. One instance per user, named-//! `cua-runtime`, state under `~/.cua/vmm/<backend>/cua-runtime`.-//! * **API socket.** dockerd listens on a unix socket inside the guest. The-//! host reaches it through an SSH-forwarded unix socket-//! (`ssh -L ~/.cua/runtime/docker.sock:/run/docker.sock`) authenticated with-//! a per-install key injected by cloud-init. The forward is owned by the SDK-//! (or `cua daemon`) and is only readable by the user. A TCP hostfwd is-//! deliberately *not* used: it would expose an unauthenticated root API to-//! every local user.-//! * **Use.** [`crate::container::ContainerRuntime`] connects with-//! `ContainerConfig { endpoint: Some("unix://~/.cua/runtime/docker.sock") }`,-//! so containers, exec, checkpoints and port publishing work unchanged.-//! Published container ports are bound inside the VM; the runtime adds-//! matching SSH `-L` forwards (or QEMU `hostfwd`s) per sandbox.-//! * **Lifecycle.** Started lazily on first container request, stopped by-//! `cua runtime stop` or after an idle timeout by the daemon. Upgrades: a new-//! image version boots a fresh instance; images are re-pulled by the engine.-//! * **doctor.** Reports `managed` as provisionable whenever QEMU or Lume is-//! ready, with the pull size and first-boot estimate.-//!-//! # Status-//!-//! Not implemented yet: selecting a container backend on a host without an-//! engine returns an actionable error from [`crate::auto::select`]. The pieces-//! it needs (VM boot with cloud-init seeds, SSH exec, container backend over an-//! arbitrary endpoint) exist and are exercised by the e2e suite.+//! * **Colima, pinned.** A pinned [Colima](https://github.com/abiosoft/colima)+//! ([`COLIMA_VERSION`]) and [Lima](https://lima-vm.io) ([`LIMA_VERSION`]),+//! SHA-256 checked, run the VM on Apple's Virtualization.framework (`vz`).+//! They live in cua's own directory ([`root`]) and run with their own+//! `HOME` and `COLIMA_HOME` there, in a profile named [`PROFILE`], so a+//! Colima, Lima or Docker of the user's is never read or touched. Colima+//! needs a `docker` CLI only to manage Docker contexts; cua gives it a+//! no-op one, so no Docker context is ever created.+//! * **The disk.** `ghcr.io/trycua/runtime-gvisor` (`libs/images/runtime-gvisor`):+//! Colima's own Ubuntu Docker disk with gVisor's `runsc` baked in, pinned+//! by its layer digest ([`DISK_SHA256_ARM64`]), so the first boot+//! downloads no packages. The profile registers `runsc` as Docker's+//! default runtime.+//! * **The socket.** Lima forwards the guest's Docker socket to+//! `<root>/vm/cua/docker.sock` ([`socket`]) over its SSH connection, mode+//! 0600: only this user, and only the SDK knows it is there (it is not a+//! Docker context and not a well-known socket path).+//! [`crate::container::ContainerRuntime`] connects to it unchanged:+//! containers, exec, checkpoints and published ports work as on any+//! engine. Ports published on the VM's 127.0.0.1 are forwarded to the+//! Mac's 127.0.0.1 by Lima.+//! * **No host files.** The VM mounts no host directory.+//! * **Lifecycle.** Set up and booted on the first Linux Space that needs+//! it ([`ensure`]), with the downloads and the boot reported as the+//! create's progress. One VM for every Linux Space; [`ManagedContainers`]+//! stops it when no Linux Space runs any more and boots it again on the+//! next start. [`remove`] (Remove host setup) deletes it and everything+//! it downloaded.+//! * **Which engine.** [`LinuxSource`] (`cua config set runtime.linux`, the+//! apps' Settings): `auto` uses a working Docker engine on this Mac and+//! the built-in runtime otherwise (and keeps using the built-in one once+//! it exists, so its Spaces stay reachable); `builtin` always the built-in+//! one; `system` only this Mac's own engine, never downloading anything.++use std::path::{Path, PathBuf};++use crate::error::{Result, VmmError};+use crate::host;++/// Colima's profile (its Lima instance is `colima-cua`).+pub const PROFILE: &str = "cua";+/// Fixed instance name of the runtime VM, as Lima names it.+pub const INSTANCE_NAME: &str = "colima-cua";++/// The pinned Colima release.+pub const COLIMA_VERSION: &str = "0.10.3";+/// The pinned Lima release.+pub const LIMA_VERSION: &str = "2.2.0";+/// The runtime disk's repository and pinned tag.+pub const DISK_REPOSITORY: &str = "trycua/runtime-gvisor";+/// The pinned tag (for people; the digests below are what is checked).+pub const DISK_TAG: &str = "0.1.0-rc1";+/// gVisor release baked into the disk.+pub const GVISOR_VERSION: &str = "20260921.0";++/// The arm64 disk layer's digest (sha256 of the `.raw.gz`) and size.+pub const DISK_SHA256_ARM64: &str =+ "0fa448f22f97dc54416cff056ae82d3bb194ec8ec58dd0983440eaecb2921fa0";+pub const DISK_SIZE_ARM64: u64 = 424_641_499;+/// The amd64 disk layer's digest and size.+pub const DISK_SHA256_AMD64: &str =+ "3f2b0446e7694417a0956c786c7de76a083fe9e3ad0794879a99d3b69044bd4a";+pub const DISK_SIZE_AMD64: u64 = 457_760_272;++/// One pinned download.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Pin {+ pub url: &'static str,+ pub sha256: &'static str,+ pub size: u64,+}++/// Colima for this Mac's architecture.+pub fn colima_pin() -> Pin {+ if cfg!(target_arch = "x86_64") {+ Pin {+ url: "https://github.com/abiosoft/colima/releases/download/v0.10.3/colima-Darwin-x86_64",+ sha256: "3082737fe8a98afda11cba7d9a20b6e56fe80c6153464beda04bec630758770b",+ size: 16_954_240,+ }+ } else {+ Pin {+ url: "https://github.com/abiosoft/colima/releases/download/v0.10.3/colima-Darwin-arm64",+ sha256: "980ad8bf61a4ca370243f4cb41401a61276dcd2c2502bee7b9b86f9250169f34",+ size: 15_656_320,+ }+ }+}++/// Lima for this Mac's architecture.+pub fn lima_pin() -> Pin {+ if cfg!(target_arch = "x86_64") {+ Pin {+ url: "https://github.com/lima-vm/lima/releases/download/v2.2.0/lima-2.2.0-Darwin-x86_64.tar.gz",+ sha256: "0d6f99c19f6e4bc3c92730c4c29d929e6927f0cb0a0ba1a84383367135a8ff31",+ size: 24_415_554,+ }+ } else {+ Pin {+ url: "https://github.com/lima-vm/lima/releases/download/v2.2.0/lima-2.2.0-Darwin-arm64.tar.gz",+ sha256: "bbdef91774885a0d05f7b048c4eb89ae2bcf3a0c252ae7ca7934e63df76d93c3",+ size: 37_586_365,+ }+ }+}++/// The runtime disk's layer for this Mac's architecture: its digest is+/// checked after the download.+pub fn disk_pin() -> Pin {+ if cfg!(target_arch = "x86_64") {+ Pin {+ url: "",+ sha256: DISK_SHA256_AMD64,+ size: DISK_SIZE_AMD64,+ }+ } else {+ Pin {+ url: "",+ sha256: DISK_SHA256_ARM64,+ size: DISK_SIZE_ARM64,+ }+ }+}++/// Everything the first Linux Space downloads, in bytes.+pub fn first_use_download() -> u64 {+ colima_pin().size + lima_pin().size + disk_pin().size+}/// One-line status for `doctor`.-pub const STATUS: &str = "managed cua-runtime VM (containerd + runsc) not implemented yet; install Colima/Docker for containers";+pub const STATUS: &str =+ "built-in Linux runtime (a small VM with Docker and gVisor), set up on first use";++/// The setting that picks the Linux engine: `runtime.linux` in+/// `$CUA_HOME/config.toml`, overridden by `CUA_RUNTIME_LINUX`.+pub const SETTING_ENV: &str = "CUA_RUNTIME_LINUX";++/// Which engine local Linux Spaces run on.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum LinuxSource {+ /// A working Docker engine on this Mac, else the built-in runtime.+ #[default]+ Auto,+ /// Always the built-in runtime.+ Builtin,+ /// Only this Mac's own engine (nothing is downloaded).+ System,+}++impl LinuxSource {+ /// `auto`, `builtin` or `system`.+ pub fn parse(word: &str) -> Option<Self> {+ match word.trim().to_ascii_lowercase().as_str() {+ "auto" | "" => Some(Self::Auto),+ "builtin" | "built-in" => Some(Self::Builtin),+ "system" => Some(Self::System),+ _ => None,+ }+ }++ /// The setting's word.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Auto => "auto",+ Self::Builtin => "builtin",+ Self::System => "system",+ }+ }++ /// The setting now: the environment, else the config file, else auto.+ /// Read on every use, so a change in Settings applies at once.+ pub fn current() -> Self {+ if let Some(s) = std::env::var(SETTING_ENV)+ .ok()+ .and_then(|v| Self::parse(&v))+ {+ return s;+ }+ Self::from_config(&host::cua_home().join("config.toml"))+ }++ /// `[runtime] linux = "..."` in `path` (auto when absent or unreadable).+ pub fn from_config(path: &Path) -> Self {+ std::fs::read_to_string(path)+ .ok()+ .and_then(|t| t.parse::<toml_edit::DocumentMut>().ok())+ .and_then(|d| {+ d.get("runtime")?+ .get("linux")?+ .as_str()+ .and_then(Self::parse)+ })+ .unwrap_or_default()+ }++ /// Whether the built-in runtime may be used (and downloaded).+ pub fn allows_builtin(self) -> bool {+ self != Self::System && supported()+ }+}++/// The built-in runtime runs on macOS 13+ (Virtualization.framework).+pub fn supported() -> bool {+ cfg!(target_os = "macos")+}++/// Local Linux Spaces run on the built-in runtime here, as [`choose`]+/// decides without probing an engine: `builtin`, or `auto` once the+/// built-in runtime exists.+pub fn in_use() -> bool {+ supported()+ && match LinuxSource::current() {+ LinuxSource::Builtin => true,+ LinuxSource::Auto => exists(),+ LinuxSource::System => false,+ }+}++/// `$CUA_HOME/runtimes/linux`: everything the built-in runtime has.+pub fn root() -> PathBuf {+ host::cua_home().join("runtimes").join("linux")+}++/// The pinned Colima and Lima.+fn tools_dir() -> PathBuf {+ root().join(format!("colima-{COLIMA_VERSION}-lima-{LIMA_VERSION}"))+}++/// Colima's `COLIMA_HOME` (Lima's home is `<vm>/_lima`).+fn vm_dir() -> PathBuf {+ root().join("vm")+}++/// The `HOME` Colima and Lima run with (their caches, a Docker config+/// nothing reads).+fn home() -> PathBuf {+ root().join("home")+}++/// The Docker API socket of the runtime VM, while it runs.+pub fn socket() -> PathBuf {+ vm_dir().join(PROFILE).join("docker.sock")+}++/// The socket as an engine endpoint.+pub fn endpoint() -> String {+ format!("unix://{}", socket().display())+}++/// Whether an engine endpoint is the built-in runtime's.+pub fn is_endpoint(uri: &str) -> bool {+ Path::new(uri.trim_start_matches("unix://")).starts_with(root())+}++/// Lima's directory for the VM (it exists once the VM was created).+fn instance_dir() -> PathBuf {+ vm_dir().join("_lima").join(INSTANCE_NAME)+}++/// The VM was created (it may be stopped).+pub fn exists() -> bool {+ instance_dir().join("lima.yaml").is_file()+}++/// The VM runs and its Docker engine answers on [`socket`].+pub fn running() -> bool {+ #[cfg(unix)]+ {+ std::os::unix::net::UnixStream::connect(socket()).is_ok()+ }+ #[cfg(not(unix))]+ {+ false+ }+}++/// Lima's sockets live in the VM's directory and must fit a Unix socket+/// path (104 bytes on macOS, with the suffix Lima adds).+fn check_path_length() -> Result<()> {+ let longest = instance_dir().join("ssh.sock.1234567890123456");+ let len = longest.as_os_str().len();+ if len >= 104 {+ return Err(VmmError::other(format!(+ "the built-in Linux runtime cannot run from {} (its path is {len} bytes; Unix \+ sockets allow 103): set CUA_HOME to a shorter directory",+ root().display()+ )));+ }+ Ok(())+}++/// Container names the engine had when the VM last stopped: their Spaces+/// are stopped, not gone, while the VM is down.+fn stopped_names_file() -> PathBuf {+ root().join("stopped-spaces.json")+}++fn stopped_names() -> Vec<String> {+ std::fs::read(stopped_names_file())+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .unwrap_or_default()+}++/// The pinned Colima and Lima, once installed and checked.+#[derive(Clone, Debug)]+struct Tools {+ colima: PathBuf,+ bin: PathBuf,+ lima_bin: PathBuf,+}++/// Written last, once every tool passed its checks.+const VERIFIED: &str = ".verified";++fn installed_tools() -> Option<Tools> {+ let d = tools_dir();+ let t = Tools {+ colima: d.join("bin/colima"),+ bin: d.join("bin"),+ lima_bin: d.join("lima/bin"),+ };+ (t.colima.is_file() && t.lima_bin.join("limactl").is_file() && d.join(VERIFIED).is_file())+ .then_some(t)+}++/// The no-op `docker` Colima's docker runtime asks for (it only manages+/// Docker contexts with it, which cua never wants).+const DOCKER_SHIM: &str = "#!/bin/sh\n# Cua's built-in Linux runtime: Colima manages Docker contexts with this\n# command; cua uses none, so it does nothing.\nexit 0\n";++/// The profile Colima starts the VM from. (The disk is a `start` flag:+/// Colima does not read `diskImage` from its profile.)+pub fn profile_yaml(arch: &str, cpus: u32, memory_gib: u32) -> String {+ format!(+ "# Written by cua (cua_vmm::managed) before every start.\n\+ cpu: {cpus}\n\+ memory: {memory_gib}\n\+ disk: 60\n\+ rootDisk: 20\n\+ arch: {arch}\n\+ runtime: docker\n\+ autoActivate: false\n\+ hostname: cua-runtime\n\+ vmType: vz\n\+ rosetta: false\n\+ binfmt: false\n\+ nestedVirtualization: false\n\+ sshConfig: false\n\+ forwardAgent: false\n\+ portForwarder: ssh\n\+ network:\n address: false\n\+ kubernetes:\n enabled: false\n\+ forceDiskImage: true\n\+ docker:\n default-runtime: runsc\n runtimes:\n runsc:\n path: /usr/local/bin/runsc\n"+ )+}++/// What the runtime VM gets: up to 4 CPUs and 4 GiB (Spaces share it).+fn vm_size() -> (u32, u32) {+ let cpus = std::thread::available_parallelism()+ .map(|n| n.get() as u32)+ .unwrap_or(4);+ (cpus.clamp(1, 4), 4)+}++/// A `colima` command that sees only cua's own Colima, Lima and VM.+fn colima(tools: &Tools) -> tokio::process::Command {+ let mut c = tokio::process::Command::new(&tools.colima);+ c.env_clear()+ .env("HOME", home())+ .env("COLIMA_HOME", vm_dir())+ .env("LIMA_HOME", vm_dir().join("_lima"))+ .env("DOCKER_CONFIG", home().join(".docker"))+ .env(+ "PATH",+ format!(+ "{}:{}:/usr/bin:/bin:/usr/sbin:/sbin",+ tools.bin.display(),+ tools.lima_bin.display()+ ),+ )+ .env("TMPDIR", std::env::temp_dir());+ for k in ["USER", "LOGNAME", "LANG"] {+ if let Some(v) = std::env::var_os(k) {+ c.env(k, v);+ }+ }+ c.stdin(std::process::Stdio::null());+ c+}++async fn run_colima(tools: &Tools, args: &[&str], secs: u64) -> Result<String> {+ let mut c = colima(tools);+ c.args(["--profile", PROFILE]).args(args);+ c.kill_on_drop(true);+ let out = tokio::time::timeout(std::time::Duration::from_secs(secs), c.output())+ .await+ .map_err(|_| {+ VmmError::other(format!("colima {} timed out after {secs}s", args.join(" ")))+ })??;+ if out.status.success() {+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())+ } else {+ Err(VmmError::other(format!(+ "colima {}: {}",+ args.join(" "),+ last_error(&String::from_utf8_lossy(&out.stderr))+ )))+ }+}++/// Colima's last `fatal`/`error` message, else its last line.+fn last_error(stderr: &str) -> String {+ let lines: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty()).collect();+ let pick = lines+ .iter()+ .rev()+ .find(|l| l.contains("level=fatal") || l.contains("level=error"))+ .or(lines.last())+ .copied()+ .unwrap_or("failed");+ match pick.find("msg=") {+ Some(i) => pick[i + 4..].trim().trim_matches('"').to_string(),+ None => pick.trim().to_string(),+ }+}++/// How far a boot is, from Colima's log line (it prints no progress).+pub fn boot_fraction(line: &str) -> Option<f64> {+ const STEPS: &[(&str, f64)] = &[+ ("starting colima", 0.05),+ ("creating and starting", 0.1),+ ("Starting VZ", 0.3),+ ("SSH Local Port", 0.5),+ ("Guest agent is running", 0.65),+ ("final requirement", 0.75),+ ("READY", 0.85),+ ("provisioning", 0.9),+ ("starting ...", 0.95),+ ("msg=done", 1.0),+ ];+ STEPS+ .iter()+ .rev()+ .find(|(needle, _)| line.contains(needle))+ .map(|(_, f)| *f)+}++/// One setup at a time in this process (a second create waits for it).+static SETUP: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++/// Words on the create while the runtime is being set up.+pub const SETTING_UP: &str = "Setting up the Linux runtime";++/// Sets up and boots the built-in runtime when it is not running; its+/// engine endpoint. The downloads and the boot are the running create's+/// progress.+#[cfg(feature = "lume")]+pub async fn ensure() -> Result<String> {+ if running() {+ return Ok(endpoint());+ }+ let _one = SETUP.lock().await;+ if running() {+ return Ok(endpoint());+ }+ if !supported() {+ return Err(VmmError::missing(+ "a container engine",+ "the built-in Linux runtime runs on macOS; install Docker",+ ));+ }+ check_path_length()?;+ let started = std::time::Instant::now();+ let fresh = !exists();+ let mut dl = Downloads::new(+ if installed_tools().is_none() {+ colima_pin().size + lima_pin().size+ } else {+ 0+ } + if fresh { disk_pin().size } else { 0 },+ );+ let tools = ensure_tools(&mut dl).await?;+ let disk = if fresh {+ Some(ensure_disk(&mut dl).await?)+ } else {+ None+ };+ let (cpus, mem) = vm_size();+ let arch = if cfg!(target_arch = "x86_64") {+ "x86_64"+ } else {+ "aarch64"+ };+ let profile_dir = vm_dir().join(PROFILE);+ std::fs::create_dir_all(&profile_dir)?;+ std::fs::create_dir_all(home())?;+ std::fs::write(+ profile_dir.join("colima.yaml"),+ profile_yaml(arch, cpus, mem),+ )?;+ boot(&tools, disk.as_deref()).await?;+ wait_engine().await?;+ // The VM runs cua's disk (gVisor baked in), not one Colima chose.+ if let Err(e) = run_colima(+ &tools,+ &["ssh", "--", "test", "-x", "/usr/local/bin/runsc"],+ 60,+ )+ .await+ {+ return Err(VmmError::other(format!(+ "the built-in Linux runtime booted without gVisor ({e}); remove it (Remove host \+ setup) and try again"+ )));+ }+ if let Some(d) = disk {+ // Lima unpacked it into the VM's own disk: the download and Lima's+ // copy of it are not needed again.+ let _ = std::fs::remove_file(d);+ let _ = std::fs::remove_dir_all(home().join("Library/Caches"));+ }+ let _ = std::fs::remove_file(stopped_names_file());+ tracing::info!(+ fresh,+ secs = started.elapsed().as_secs_f64(),+ "built-in Linux runtime is up"+ );+ Ok(endpoint())+}++/// `colima start`, its log turned into boot progress. A VM left half-up+/// (a crash, a sleep) is stopped and started once more.+#[cfg(feature = "lume")]+async fn boot(tools: &Tools, disk: Option<&Path>) -> Result<()> {+ match start_once(tools, disk).await {+ Ok(()) => Ok(()),+ Err(first) if exists() => {+ tracing::warn!("built-in Linux runtime did not start ({first}); restarting it");+ let _ = run_colima(tools, &["stop", "--force"], 120).await;+ start_once(tools, disk).await+ }+ Err(e) => Err(e),+ }+}++#[cfg(feature = "lume")]+async fn start_once(tools: &Tools, disk: Option<&Path>) -> Result<()> {+ use crate::progress::{Phase, Progress, report};+ use tokio::io::AsyncBufReadExt as _;+ report(+ Progress::phase(Phase::Preparing)+ .detail(SETTING_UP)+ .fraction(0.0),+ );+ let mut c = colima(tools);+ c.args(["--profile", PROFILE, "start"]);+ if let Some(d) = disk {+ // The VM is created from cua's disk (not Colima's own download).+ c.arg("--disk-image").arg(d).arg("--force-disk-image");+ }+ c.stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::piped())+ .kill_on_drop(true);+ let mut child = c.spawn()?;+ let stderr = child.stderr.take().expect("piped");+ let mut lines = tokio::io::BufReader::new(stderr).lines();+ let mut tail: Vec<String> = Vec::new();+ let mut at = 0.0;+ let read = async {+ while let Ok(Some(line)) = lines.next_line().await {+ if let Some(f) = boot_fraction(&line).filter(|f| *f > at) {+ at = f;+ report(+ Progress::phase(Phase::Preparing)+ .detail(SETTING_UP)+ .fraction(f),+ );+ }+ tail.push(line);+ if tail.len() > 40 {+ tail.remove(0);+ }+ }+ };+ let status = tokio::time::timeout(std::time::Duration::from_secs(600), async {+ read.await;+ child.wait().await+ })+ .await+ .map_err(|_| VmmError::other("the built-in Linux runtime did not start within 10 minutes"))??;+ if status.success() {+ Ok(())+ } else {+ Err(VmmError::other(format!(+ "the built-in Linux runtime did not start: {}",+ last_error(&tail.join("\n"))+ )))+ }+}++/// Docker in the VM answers on the forwarded socket.+#[cfg(feature = "lume")]+async fn wait_engine() -> Result<()> {+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(90);+ loop {+ if running() {+ return Ok(());+ }+ if tokio::time::Instant::now() > deadline {+ return Err(VmmError::other(+ "the built-in Linux runtime started but its Docker engine does not answer",+ ));+ }+ tokio::time::sleep(std::time::Duration::from_millis(250)).await;+ }+}++/// Stops the VM (its Spaces stop with it). Nothing to do when it is down.+pub async fn stop(names: &[String]) -> Result<()> {+ let Some(tools) = installed_tools() else {+ return Ok(());+ };+ if !exists() {+ return Ok(());+ }+ let _one = SETUP.lock().await;+ std::fs::write(stopped_names_file(), serde_json::to_vec(names)?)?;+ run_colima(&tools, &["stop"], 180).await.map(drop)+}++/// Deletes the built-in runtime: the VM, its disks and every download.+/// A Colima, Lima or Docker of the user's is elsewhere and stays.+pub async fn remove() -> Result<()> {+ let _one = SETUP.lock().await;+ if let Some(tools) = installed_tools()+ && exists()+ && let Err(e) = run_colima(&tools, &["delete", "--force", "--data"], 180).await+ {+ tracing::warn!("removing the built-in Linux runtime VM: {e}");+ }+ match std::fs::remove_dir_all(root()) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),+ _ => Ok(()),+ }+}++/// Bytes of every download of one setup, as one transfer.+struct Downloads {+ total: u64,+ done: u64,+ meter: crate::progress::Meter,+}++impl Downloads {+ fn new(total: u64) -> Self {+ Self {+ total,+ done: 0,+ meter: crate::progress::Meter::new(),+ }+ }++ fn add(&mut self, n: u64) {+ use crate::progress::{Phase, Progress, report};+ self.done += n;+ if let Some(t) = self+ .meter+ .sample_at(std::time::Instant::now(), self.done, self.total)+ {+ report(+ Progress::phase(Phase::Preparing)+ .detail(SETTING_UP)+ .bytes(t)+ .fraction(self.done as f64 / self.total.max(1) as f64),+ );+ }+ }+}++/// Installs the pinned Colima and Lima when they are not there yet.+#[cfg(feature = "lume")]+async fn ensure_tools(dl: &mut Downloads) -> Result<Tools> {+ if let Some(t) = installed_tools() {+ return Ok(t);+ }+ std::fs::create_dir_all(root())?;+ crate::disk::ensure_space(&root(), 200 << 20, "set up the built-in Linux runtime")?;+ let staging = tempfile::Builder::new()+ .prefix(".install-")+ .tempdir_in(root())?;+ let s = staging.path().join("tools");+ let s = s.as_path();+ std::fs::create_dir_all(s)?;+ let colima_pin = colima_pin();+ let lima_pin = lima_pin();+ std::fs::create_dir_all(s.join("bin"))?;+ download(colima_pin, None, &s.join("bin/colima"), dl).await?;+ let lima_tgz = s.join("lima.tar.gz");+ download(lima_pin, None, &lima_tgz, dl).await?;+ std::fs::create_dir_all(s.join("lima"))?;+ host::run(+ "/usr/bin/tar",+ &[+ "-xzf",+ &lima_tgz.to_string_lossy(),+ "-C",+ &s.join("lima").to_string_lossy(),+ "bin/limactl",+ "bin/lima",+ "share/lima",+ "libexec/lima",+ ],+ )+ .await?;+ std::fs::remove_file(&lima_tgz)?;+ std::fs::write(s.join("bin/docker"), DOCKER_SHIM)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ for f in ["bin/colima", "bin/docker"] {+ std::fs::set_permissions(s.join(f), std::fs::Permissions::from_mode(0o755))?;+ }+ }+ std::fs::write(+ s.join(VERIFIED),+ format!("colima {COLIMA_VERSION}\nlima {LIMA_VERSION}\n"),+ )?;+ let target = tools_dir();+ let _ = std::fs::remove_dir_all(&target);+ std::fs::rename(s, &target)?;+ tracing::info!(dir = %target.display(), "installed the built-in Linux runtime's Colima and Lima");+ installed_tools().ok_or_else(|| VmmError::other("the built-in Linux runtime did not install"))+}++/// The runtime disk, downloaded from ghcr.io and checked against its pin.+#[cfg(feature = "lume")]+async fn ensure_disk(dl: &mut Downloads) -> Result<PathBuf> {+ let pin = disk_pin();+ let dir = root().join("disk");+ std::fs::create_dir_all(&dir)?;+ let path = dir.join(format!("runtime-gvisor-{}.raw.gz", &pin.sha256[..12]));+ if path.is_file() && sha256_file(&path)? == pin.sha256 {+ dl.add(pin.size);+ return Ok(path);+ }+ // The disk unpacks to about 3.5 GB and grows with the images Spaces use.+ crate::disk::ensure_space(+ &dir,+ pin.size + (6 << 30),+ "set up the built-in Linux runtime",+ )?;+ let url = format!(+ "https://ghcr.io/v2/{DISK_REPOSITORY}/blobs/sha256:{}",+ pin.sha256+ );+ let token = ghcr_token().await?;+ download(Pin { url: "", ..pin }, Some((&url, &token)), &path, dl).await?;+ Ok(path)+}++/// A pull token for [`DISK_REPOSITORY`]: anonymous, or with the+/// `CUA_REGISTRY_USERNAME`/`PASSWORD` credentials container pulls use.+#[cfg(feature = "lume")]+async fn ghcr_token() -> Result<String> {+ let url =+ format!("https://ghcr.io/token?scope=repository:{DISK_REPOSITORY}:pull&service=ghcr.io");+ let mut req = http()?.get(url);+ if let (Ok(u), Ok(p)) = (+ std::env::var("CUA_REGISTRY_USERNAME"),+ std::env::var("CUA_REGISTRY_PASSWORD"),+ ) {+ req = req.basic_auth(u, Some(p));+ }+ let res = req+ .send()+ .await+ .and_then(|r| r.error_for_status())+ .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))?;+ let body: serde_json::Value = res+ .json()+ .await+ .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))?;+ body.get("token")+ .and_then(|t| t.as_str())+ .map(str::to_string)+ .ok_or_else(|| VmmError::other("ghcr.io gave no pull token for the built-in Linux runtime"))+}++#[cfg(feature = "lume")]+fn http() -> Result<reqwest::Client> {+ reqwest::Client::builder()+ .connect_timeout(std::time::Duration::from_secs(20))+ .read_timeout(std::time::Duration::from_secs(60))+ .build()+ .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))+}++/// Streams a pinned file to `to` (via `<to>.partial`), checking its size+/// and SHA-256 before it is renamed into place.+#[cfg(feature = "lume")]+async fn download(+ pin: Pin,+ bearer: Option<(&str, &str)>,+ to: &Path,+ dl: &mut Downloads,+) -> Result<()> {+ use sha2::{Digest, Sha256};+ use tokio::io::AsyncWriteExt as _;+ let (url, token) = match bearer {+ Some((u, t)) => (u, Some(t)),+ None => (pin.url, None),+ };+ let mut req = http()?.get(url);+ if let Some(t) = token {+ req = req.bearer_auth(t);+ }+ let mut res = req+ .send()+ .await+ .and_then(|r| r.error_for_status())+ .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))?;+ let partial = to.with_extension("partial");+ let mut file = tokio::fs::File::create(&partial).await?;+ let mut hash = Sha256::new();+ let mut got = 0u64;+ while let Some(chunk) = res+ .chunk()+ .await+ .map_err(|e| VmmError::other(format!("download the built-in Linux runtime: {e}")))?+ {+ got += chunk.len() as u64;+ if got > pin.size {+ let _ = tokio::fs::remove_file(&partial).await;+ return Err(VmmError::other(+ "a built-in Linux runtime download is larger than its pin",+ ));+ }+ hash.update(&chunk);+ file.write_all(&chunk).await?;+ dl.add(chunk.len() as u64);+ }+ file.flush().await?;+ drop(file);+ let digest: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();+ if digest != pin.sha256 || got != pin.size {+ let _ = tokio::fs::remove_file(&partial).await;+ return Err(VmmError::other(format!(+ "a built-in Linux runtime download did not match its checksum (got {digest}); try again"+ )));+ }+ tokio::fs::rename(&partial, to).await?;+ Ok(())+}++fn sha256_file(path: &Path) -> Result<String> {+ use sha2::{Digest, Sha256};+ use std::io::Read as _;+ let mut f = std::fs::File::open(path)?;+ let mut h = Sha256::new();+ let mut buf = vec![0u8; 256 * 1024];+ loop {+ let n = f.read(&mut buf)?;+ if n == 0 {+ break;+ }+ h.update(&buf[..n]);+ }+ Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())+}++#[cfg(all(feature = "container", feature = "lume"))]+pub use engine_impl::{Choice, ManagedContainers, choose, connect_if_up};++#[cfg(all(feature = "container", feature = "lume"))]+mod engine_impl {+ use std::sync::Arc;++ use async_trait::async_trait;++ use super::*;+ use crate::container::{ContainerConfig, ContainerRuntime};+ use crate::exec::GuestExec;+ use crate::runtime::Runtime;+ use crate::types::{+ BackendKind, CheckpointInfo, Endpoints, ImageSource, Instance, InstanceSummary, StartSpec,+ Status,+ };++ /// The engine Linux Spaces use here.+ pub enum Choice {+ /// This Mac's own engine (Docker Desktop, Colima, OrbStack, ...).+ System(Box<ContainerRuntime>),+ /// The built-in runtime (booted on demand).+ Builtin(Arc<ManagedContainers>),+ }++ /// Picks the engine for `source` without booting anything.+ pub async fn choose(cfg: ContainerConfig, source: LinuxSource) -> Result<Choice> {+ if cfg.endpoint.is_some() {+ return ContainerRuntime::connect(cfg)+ .await+ .map(|rt| Choice::System(Box::new(rt)));+ }+ let builtin = |cfg| Ok(Choice::Builtin(Arc::new(ManagedContainers::new(cfg))));+ match source {+ LinuxSource::Builtin if supported() => builtin(cfg),+ LinuxSource::Builtin => Err(VmmError::missing(+ "a container engine",+ "the built-in Linux runtime runs on macOS; set runtime.linux to auto or system",+ )),+ LinuxSource::System => ContainerRuntime::connect(cfg)+ .await+ .map(|rt| Choice::System(Box::new(rt))),+ // Once the built-in runtime exists it keeps its Spaces.+ LinuxSource::Auto if supported() && exists() => builtin(cfg),+ LinuxSource::Auto => match ContainerRuntime::connect(cfg.clone()).await {+ Ok(rt) => Ok(Choice::System(Box::new(rt))),+ Err(_) if supported() => builtin(cfg),+ Err(e) => Err(e),+ },+ }+ }++ /// The engine Linux Spaces use, when it answers now (the built-in+ /// runtime only while its VM runs). Never boots or downloads anything:+ /// for views of what is there (disk use, downloaded images).+ pub async fn connect_if_up(cfg: ContainerConfig) -> Option<ContainerRuntime> {+ match choose(cfg.clone(), LinuxSource::current()).await.ok()? {+ Choice::System(rt) => Some(*rt),+ Choice::Builtin(_) if running() => ContainerRuntime::connect(ContainerConfig {+ endpoint: Some(endpoint()),+ ..cfg+ })+ .await+ .ok(),+ Choice::Builtin(_) => None,+ }+ }++ /// The built-in runtime as a container backend: boots the VM for+ /// anything that needs the engine, answers status and list from what+ /// it knew while the VM is down, and stops the VM once no Linux Space+ /// runs any more.+ pub struct ManagedContainers {+ cfg: ContainerConfig,+ engine: tokio::sync::Mutex<Option<Arc<ContainerRuntime>>>,+ }++ impl ManagedContainers {+ pub fn new(cfg: ContainerConfig) -> Self {+ Self {+ cfg,+ engine: tokio::sync::Mutex::new(None),+ }+ }++ /// The engine, booting the VM (and setting it up the first time).+ pub async fn engine(&self) -> Result<Arc<ContainerRuntime>> {+ let uri = ensure().await?;+ self.connect(uri).await+ }++ /// The engine when the VM is up; never boots it.+ pub async fn engine_if_running(&self) -> Option<Arc<ContainerRuntime>> {+ if !running() {+ return None;+ }+ self.connect(endpoint()).await.ok()+ }++ async fn connect(&self, uri: String) -> Result<Arc<ContainerRuntime>> {+ let mut slot = self.engine.lock().await;+ if let Some(rt) = slot.as_ref() {+ return Ok(rt.clone());+ }+ let rt = Arc::new(+ ContainerRuntime::connect(ContainerConfig {+ endpoint: Some(uri),+ ..self.cfg.clone()+ })+ .await?,+ );+ *slot = Some(rt.clone());+ Ok(rt)+ }++ /// Stops the VM when none of its containers runs (or is paused).+ pub async fn stop_if_idle(&self) {+ let Some(rt) = self.engine_if_running().await else {+ return;+ };+ let Ok(list) = rt.list().await else {+ return;+ };+ if list.iter().any(|s| s.status != Status::Stopped) {+ return;+ }+ let names: Vec<String> = list.into_iter().map(|s| s.name).collect();+ match stop(&names).await {+ Ok(()) => tracing::info!("stopped the built-in Linux runtime: no Linux Space runs"),+ Err(e) => tracing::warn!("stopping the idle built-in Linux runtime: {e}"),+ }+ }+ }++ #[async_trait]+ impl Runtime for ManagedContainers {+ fn kind(&self) -> BackendKind {+ BackendKind::Container+ }++ async fn ensure_base(+ &self,+ image: &ImageSource,+ base_name: &str,+ ) -> Result<CheckpointInfo> {+ self.engine().await?.ensure_base(image, base_name).await+ }++ async fn start(&self, spec: &StartSpec) -> Result<Instance> {+ self.engine().await?.start(spec).await+ }++ async fn stop(&self, name: &str) -> Result<()> {+ let Some(rt) = self.engine_if_running().await else {+ return if stopped_names().iter().any(|n| n == name) {+ Ok(())+ } else {+ Err(VmmError::NotFound(name.into()))+ };+ };+ rt.stop(name).await?;+ self.stop_if_idle().await;+ Ok(())+ }++ async fn suspend(&self, name: &str) -> Result<()> {+ self.engine().await?.suspend(name).await+ }++ async fn resume(&self, name: &str) -> Result<Instance> {+ self.engine().await?.resume(name).await+ }++ async fn fork(&self, source: &str, new_name: &str) -> Result<()> {+ self.engine().await?.fork(source, new_name).await+ }++ async fn checkpoint(&self, name: &str, checkpoint: &str) -> Result<CheckpointInfo> {+ self.engine().await?.checkpoint(name, checkpoint).await+ }++ async fn delete_checkpoint(&self, checkpoint: &str) -> Result<()> {+ self.engine().await?.delete_checkpoint(checkpoint).await+ }++ async fn list(&self) -> Result<Vec<InstanceSummary>> {+ match self.engine_if_running().await {+ Some(rt) => rt.list().await,+ None => Ok(stopped_names()+ .into_iter()+ .map(|name| InstanceSummary {+ name,+ backend: BackendKind::Container,+ status: Status::Stopped,+ })+ .collect()),+ }+ }++ async fn status(&self, name: &str) -> Result<Status> {+ match self.engine_if_running().await {+ Some(rt) => rt.status(name).await,+ None if stopped_names().iter().any(|n| n == name) => Ok(Status::Stopped),+ None => Err(VmmError::NotFound(name.into())),+ }+ }++ async fn delete(&self, name: &str) -> Result<()> {+ if !running() && !stopped_names().iter().any(|n| n == name) {+ return Err(VmmError::NotFound(name.into()));+ }+ self.engine().await?.delete(name).await?;+ self.stop_if_idle().await;+ Ok(())+ }++ async fn endpoints(&self, name: &str) -> Result<Endpoints> {+ match self.engine_if_running().await {+ Some(rt) => rt.endpoints(name).await,+ None => Err(VmmError::other(format!(+ "{name} is stopped (the built-in Linux runtime is not running)"+ ))),+ }+ }++ async fn guest_tcp_listening(&self, name: &str, guest_port: u16) -> Result<Option<bool>> {+ match self.engine_if_running().await {+ Some(rt) => rt.guest_tcp_listening(name, guest_port).await,+ None => Ok(Some(false)),+ }+ }++ async fn guest_exec(&self, name: &str) -> Result<Option<Arc<dyn GuestExec>>> {+ self.engine().await?.guest_exec(name).await+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_setting_parses_and_defaults_to_auto() {+ assert_eq!(LinuxSource::parse("Built-in"), Some(LinuxSource::Builtin));+ assert_eq!(LinuxSource::parse("system"), Some(LinuxSource::System));+ assert_eq!(LinuxSource::parse("docker"), None);+ let d = tempfile::tempdir().unwrap();+ let p = d.path().join("config.toml");+ assert_eq!(LinuxSource::from_config(&p), LinuxSource::Auto);+ std::fs::write(&p, "[runtime]\nlume = \"system\"\nlinux = \"builtin\"\n").unwrap();+ assert_eq!(LinuxSource::from_config(&p), LinuxSource::Builtin);+ assert!(!LinuxSource::System.allows_builtin());+ assert_eq!(+ LinuxSource::Auto.allows_builtin(),+ cfg!(target_os = "macos")+ );+ }++ /// The pins here and the image's versions.env name the same releases+ /// (the image is built from the file; the SDK downloads by these).+ #[test]+ fn the_pins_match_the_image_build() {+ let env = include_str!("../../../../images/runtime-gvisor/versions.env");+ let get = |k: &str| {+ env.lines()+ .find_map(|l| l.strip_prefix(&format!("{k}=")))+ .unwrap_or_else(|| panic!("{k} in versions.env"))+ .to_string()+ };+ assert_eq!(get("COLIMA_VERSION"), COLIMA_VERSION);+ assert_eq!(get("LIMA_VERSION"), LIMA_VERSION);+ assert_eq!(get("GVISOR_VERSION"), GVISOR_VERSION);+ assert!(DISK_TAG.starts_with(&get("RUNTIME_VERSION")));+ for p in [colima_pin(), lima_pin(), disk_pin()] {+ assert_eq!(p.sha256.len(), 64);+ assert!(p.size > 1 << 20);+ }+ assert!(colima_pin().url.contains(&format!("v{COLIMA_VERSION}/")));+ assert!(+ lima_pin()+ .url+ .contains(&format!("v{LIMA_VERSION}/lima-{LIMA_VERSION}-Darwin"))+ );+ // A few hundred MB in all.+ assert!(first_use_download() < 600 << 20);+ }++ #[test]+ fn the_profile_runs_gvisor_by_default_and_shares_nothing() {+ let y = profile_yaml("aarch64", 4, 4);+ assert!(y.contains("default-runtime: runsc"));+ assert!(y.contains("path: /usr/local/bin/runsc"));+ assert!(y.contains("vmType: vz"));+ assert!(y.contains("autoActivate: false"));+ assert!(y.contains("forceDiskImage: true"));+ // No `mounts:` key: Colima then mounts nothing (an empty list would+ // mount the home directory).+ assert!(!y.contains("mounts"));+ }++ #[test]+ fn boot_progress_follows_colima_s_log() {+ assert_eq!(+ boot_fraction(r#"level=info msg="[hostagent] Starting VZ (hint: ...)""#),+ Some(0.3)+ );+ assert_eq!(boot_fraction(r#"level=info msg=done"#), Some(1.0));+ assert_eq!(boot_fraction("unrelated"), None);+ assert_eq!(+ last_error("a\ntime=x level=fatal msg=\"error starting vm: boom\"\n"),+ "error starting vm: boom"+ );+ }++ #[test]+ fn its_socket_is_recognised_and_not_a_user_engine() {+ let ep = endpoint();+ assert!(is_endpoint(&ep));+ assert!(!is_endpoint("unix:///Users/me/.colima/default/docker.sock"));+ // engine::classify must not mistake it for the user's Colima.+ #[cfg(feature = "container")]+ assert!(!matches!(+ crate::container::engine::classify(&ep),+ crate::container::engine::EngineKind::Colima { .. }+ ));+ }-/// Fixed instance name of the managed runtime VM.-pub const INSTANCE_NAME: &str = "cua-runtime";+ /// Opt-in (network, boots a VM, about 480 MB): sets up the built-in+ /// runtime in a temporary `CUA_HOME`, runs a container under runsc,+ /// stops and removes it.+ /// `CUA_HOME=<tmp> CUA_RUNTIME_LINUX=builtin cargo test -p cua-vmm --lib managed -- --ignored`+ #[cfg(all(feature = "container", feature = "lume", target_os = "macos"))]+ #[tokio::test(flavor = "multi_thread")]+ #[ignore = "downloads and boots the built-in Linux runtime (network, a VM)"]+ async fn sets_up_boots_and_removes_the_builtin_runtime() {+ let home = std::env::var("CUA_HOME").expect("set CUA_HOME to a temporary directory");+ assert!(+ !home.is_empty() && !home.ends_with("/.cua"),+ "never the real cua home"+ );+ let uri = ensure().await.unwrap();+ assert!(running());+ let rt = crate::container::ContainerRuntime::connect(crate::container::ContainerConfig {+ endpoint: Some(uri),+ ..Default::default()+ })+ .await+ .unwrap();+ assert!(rt.runtimes().await.unwrap().iter().any(|r| r == "runsc"));+ let info = rt.docker().info().await.unwrap();+ assert_eq!(info.default_runtime.as_deref(), Some("runsc"));+ stop(&[]).await.unwrap();+ assert!(!running());+ remove().await.unwrap();+ assert!(!root().exists());+ }+}diff --git a/libs/images/README.md b/libs/images/README.mdindex b8440a69ad..f74c1a4309 100644--- a/libs/images/README.md+++ b/libs/images/README.md@@ -60,6 +60,15 @@ Pass the same `--stamp` (and `--work`, when set) to every run of one release. `t- **Identity:** `/etc/cua-image/manifest.json` (from `image.json` claims and `cua-spacesd build-info`), `/etc/cua-image/spacesd-source`, `/etc/cua-image/variant` (`lume`).- **Gate:** `doctor-gate.sh` runs `cua-spacesd doctor --strict` in the guest over `lume ssh` after a reboot, then `tools/ax_probe.py` (the official MCP SDK against the image's `/mcp`: permissions, an AX tree read, CGEvent clicks in Calculator and a session-keyed `move_cursor` that must return). The build fails unless both pass. The release's `input/arm64/lume` gate (`live-input-gate.sh`) then boots a clone of the built VM and runs `libs/cua/crates/cua-spaces-ext/tests/e2e_macos_input.rs`: a Dock click on a whole-display stream must be delivered and change the screen. The pushed VM itself never boots again after its sanitize.+## Built-in Linux runtime (`runtime-gvisor`)++`runtime-gvisor/` builds `ghcr.io/trycua/runtime-gvisor`, the disk of the VM a Mac with no Docker runs Linux Spaces in (`cua_vmm::managed`, the Linux row of Settings → Runtimes, `cua config set runtime.linux auto|builtin|system`). It is not a Space image and not in the catalog.++- **Contents:** Colima's own Ubuntu 24.04 Docker disk (colima-core, Docker Engine and containerd) with gVisor's `runsc` and its sentry baked into `/usr/local/bin`; every input is pinned by digest in `runtime-gvisor/versions.env`. The SDK's Colima profile makes `runsc` Docker's default runtime, mounts no host directory, and Lima forwards the guest's Docker socket to `$CUA_HOME/runtimes/linux/vm/cua/docker.sock` (mode 0600).+- **Build:** `sudo runtime-gvisor/build.sh arm64|amd64 out/` on any Linux (loop devices; it only adds files, so one runner builds both arches). About 425 MB (arm64) and 460 MB (amd64) compressed.+- **Publish:** `runtime-gvisor/push.sh <tag> out/` (`.github/workflows/cd-image-runtime-gvisor.yml` on `runtime-gvisor-v*` tags) pushes `<tag>-<arch>` OCI artifacts (one gzip raw-disk layer each) and the `<tag>` index. Tags are written once; there is no floating tag. The SDK pins each arch's layer digest and size in `managed.rs` (a unit test checks the pins against `versions.env`), so a new disk ships with the SDK release that pins it.+- **Gate:** the opt-in `managed::tests::sets_up_boots_and_removes_the_builtin_runtime` on an Apple silicon Mac downloads the pinned bytes into a temporary `CUA_HOME`, boots the VM and checks `runsc` is Docker's default runtime. A pre-release tag (`<version>-rcN`) can be tested before the SDK pin moves.+## Image references`sandbox-images.json` is the one list of images the repo points at: the apps, the CLI (`cua images ls`), the docs tables and cua-bench read it. Benchmark entries name their `bench/<id>/lock.json` pins and the benchmarks they run.diff --git a/libs/images/runtime-gvisor/build.sh b/libs/images/runtime-gvisor/build.shnew file mode 100755index 0000000000..368549c2fe--- /dev/null+++ b/libs/images/runtime-gvisor/build.sh@@ -0,0 +1,80 @@+#!/usr/bin/env bash+# Builds the disk of ghcr.io/trycua/runtime-gvisor for one arch: Colima's+# Ubuntu Docker disk (versions.env) with gVisor's runsc and sentry baked into+# /usr/local/bin, so the built-in Linux runtime's first boot downloads+# nothing. Colima registers runsc as Docker's default runtime from the+# profile cua-vmm writes (managed.rs), not from the disk.+#+# sudo libs/images/runtime-gvisor/build.sh arm64 out/+#+# Runs on Linux as root (loop devices): a CI runner, or any Linux VM. Writes+# <out>/runtime-gvisor-<version>-<arch>.raw.gz and its .sha256. Only files are+# added to the base filesystem, so the build needs no emulation and one+# runner builds both arches.+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=versions.env+. "$here/versions.env"++arch="${1:?usage: build.sh arm64|amd64 OUT_DIR}"+out="${2:?usage: build.sh arm64|amd64 OUT_DIR}"+case "$arch" in arm64 | amd64) ;; *) echo "arch must be arm64 or amd64" >&2; exit 2 ;; esac+[ "$(id -u)" = 0 ] || { echo "run as root (loop devices)" >&2; exit 2; }+for t in curl sha512sum bzip2 losetup; do command -v "$t" >/dev/null || { echo "needs $t" >&2; exit 2; }; done++base_url="BASE_URL_$arch"; base_sha="BASE_SHA512_$arch"+gv_url="GVISOR_URL_$arch"; gv_sha="GVISOR_SHA512_$arch"+mkdir -p "$out"+out="$(cd "$out" && pwd)"+work="$(mktemp -d "${TMPDIR:-/var/tmp}/runtime-gvisor.XXXXXX")"+mnt="$work/root"+loop=""+cleanup() {+ mountpoint -q "$mnt" 2>/dev/null && umount "$mnt"+ [ -n "$loop" ] && losetup -d "$loop" 2>/dev/null+ rm -rf "$work"+}+trap cleanup EXIT++fetch() { # url sha512 dest+ curl -fsSL --retry 3 -o "$3" "$1"+ echo "$2 $3" | sha512sum -c --quiet -+}++echo "==> base disk (colima-core $COLIMA_CORE_VERSION, $arch)"+fetch "${!base_url}" "${!base_sha}" "$work/base.raw.gz"+gzip -dc "$work/base.raw.gz" > "$work/disk.raw"+rm "$work/base.raw.gz"++echo "==> gVisor $GVISOR_VERSION"+fetch "${!gv_url}" "${!gv_sha}" "$work/gvisor.tar.bz2"+mkdir "$work/gvisor"+tar -xjf "$work/gvisor.tar.bz2" -C "$work/gvisor" runsc gvisor-bin/gvisor_sentry+rm "$work/gvisor.tar.bz2"++echo "==> bake"+loop="$(losetup --find --show --partscan "$work/disk.raw")"+udevadm settle 2>/dev/null || true+mkdir "$mnt"+# Partition 1 is the root filesystem (cloudimg layout: 1 root, 15 ESP, 16 /boot).+mount "${loop}p1" "$mnt"+install -d -m 0755 "$mnt/usr/local/bin/gvisor-bin" "$mnt/etc/cua-runtime"+install -m 0755 "$work/gvisor/runsc" "$mnt/usr/local/bin/"+install -m 0755 "$work/gvisor/gvisor-bin/gvisor_sentry" "$mnt/usr/local/bin/gvisor-bin/"+cat > "$mnt/etc/cua-runtime/release.json" <<EOF+{"image":"runtime-gvisor","version":"$RUNTIME_VERSION","arch":"$arch","base":"colima-core $COLIMA_CORE_VERSION","gvisor":"$GVISOR_VERSION","colima":"$COLIMA_VERSION","lima":"$LIMA_VERSION"}+EOF+# The baked files are the verified ones.+cmp "$work/gvisor/runsc" "$mnt/usr/local/bin/runsc"+cmp "$work/gvisor/gvisor-bin/gvisor_sentry" "$mnt/usr/local/bin/gvisor-bin/gvisor_sentry"+sync+umount "$mnt"+losetup -d "$loop"+loop=""++echo "==> compress"+name="runtime-gvisor-$RUNTIME_VERSION-$arch.raw.gz"+if command -v pigz >/dev/null; then pigz -n -c "$work/disk.raw"; else gzip -n -c "$work/disk.raw"; fi > "$out/$name"+(cd "$out" && sha256sum "$name" > "$name.sha256")+cat "$out/$name.sha256"+ls -l "$out/$name"diff --git a/libs/images/runtime-gvisor/push.sh b/libs/images/runtime-gvisor/push.shnew file mode 100755index 0000000000..bcaec60c26--- /dev/null+++ b/libs/images/runtime-gvisor/push.sh@@ -0,0 +1,52 @@+#!/usr/bin/env bash+# Pushes the disks build.sh wrote to ghcr.io/trycua/runtime-gvisor as OCI+# artifacts: one manifest per arch (<tag>-<arch>, a single gzip raw-disk+# layer) and an index (<tag>). Tags are written once and never moved (no+# floating tag: the SDK pins each arch's layer digest in cua-vmm's+# managed.rs), so check-tag-safety.sh refuses a re-push of a different disk.+#+# libs/images/runtime-gvisor/push.sh 0.1.0-rc1 out/+#+# Needs oras and a registry login (oras login ghcr.io, or REGISTRY_CONFIG).+# Prints each arch's layer digest and size for managed.rs.+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+root="$(cd "$here/../../.." && pwd)"+# shellcheck source=versions.env+. "$here/versions.env"++tag="${1:?usage: push.sh TAG OUT_DIR}"+out="${2:?usage: push.sh TAG OUT_DIR}"+repo="${REPO:-ghcr.io/trycua/runtime-gvisor}"+case "$tag" in+"$RUNTIME_VERSION" | "$RUNTIME_VERSION"-rc[0-9]*) ;;+*) echo "tag must be $RUNTIME_VERSION or $RUNTIME_VERSION-rcN (versions.env)" >&2; exit 2 ;;+esac+cfg=()+[ -n "${REGISTRY_CONFIG:-}" ] && cfg=(--registry-config "$REGISTRY_CONFIG")++children=()+for arch in arm64 amd64; do+ file="runtime-gvisor-$RUNTIME_VERSION-$arch.raw.gz"+ [ -f "$out/$file" ] || continue+ (cd "$out" && shasum -a 256 -c "$file.sha256" >/dev/null)+ "$root/scripts/images/check-tag-safety.sh" "$repo:$tag-$arch"+ (cd "$out" && oras push "${cfg[@]}" "$repo:$tag-$arch" \+ --artifact-type application/vnd.trycua.runtime.v1 \+ --annotation "org.opencontainers.image.source=https://github.com/trycua/cua" \+ --annotation "org.opencontainers.image.version=$tag" \+ --annotation "org.opencontainers.image.description=Cua built-in Linux runtime VM disk (Colima $COLIMA_VERSION, gVisor $GVISOR_VERSION)" \+ --annotation "ai.cua.runtime.arch=$arch" \+ --annotation "ai.cua.runtime.gvisor=$GVISOR_VERSION" \+ --annotation "ai.cua.runtime.colima=$COLIMA_VERSION" \+ "$file:application/vnd.trycua.runtime.disk.raw.v1+gzip" >/dev/null)+ children+=("$repo:$tag-$arch")+ digest="sha256:$(cut -d' ' -f1 "$out/$file.sha256")"+ size="$(wc -c < "$out/$file" | tr -d ' ')"+ echo "$arch layer $digest size $size"+done+[ ${#children[@]} -gt 0 ] || { echo "no disks in $out" >&2; exit 2; }+"$root/scripts/images/check-tag-safety.sh" "$repo:$tag"+oras manifest index create "${cfg[@]}" "$repo:$tag" "${children[@]}" \+ --annotation "org.opencontainers.image.source=https://github.com/trycua/cua" >/dev/null+echo "pushed $repo:$tag (${children[*]})"diff --git a/libs/images/runtime-gvisor/versions.env b/libs/images/runtime-gvisor/versions.envnew file mode 100644index 0000000000..63a3a9e20c--- /dev/null+++ b/libs/images/runtime-gvisor/versions.env@@ -0,0 +1,31 @@+# Pinned inputs of ghcr.io/trycua/runtime-gvisor: the disk of the built-in+# Linux runtime VM (cua_vmm::managed). One place: a rebuild changes nothing+# unless this file changes. Every download is checked against its digest+# before it is used. cua-vmm's managed.rs pins the same Colima, Lima and+# image digests (a test there reads this file).+# Sourced by bash; KEY=value only.++# The image's own version (its tag is <version>, pre-releases <version>-rcN).+RUNTIME_VERSION=0.1.0++# The base disk: Colima's own Ubuntu 24.04 minimal cloud image with Docker+# Engine and containerd, the one Colima COLIMA_VERSION verifies by default.+COLIMA_CORE_VERSION=0.10.4+BASE_URL_arm64=https://github.com/abiosoft/colima-core/releases/download/v0.10.4/ubuntu-24.04-minimal-cloudimg-arm64-docker.raw.gz+BASE_SHA512_arm64=32242674b046b5057e60c4aba334b51e3665f05412cda89ed081cc2de153ae5c41f6b105b5c442cbe48d78e2cc21e9ba1950e406b6fb4fc2fd1dd2259240abbd+BASE_URL_amd64=https://github.com/abiosoft/colima-core/releases/download/v0.10.4/ubuntu-24.04-minimal-cloudimg-amd64-docker.raw.gz+BASE_SHA512_amd64=27652801b6606b457f4f34836358c0e9978aeb98757d0271165e3f09672f930ccc2d957e15726f7e7f22c302b20a3d30c64ead68adaa5f24a4f959cd34b56b5b++# gVisor: runsc (the default Docker runtime) and its sentry sidecar, from the+# release tarball (scripts/images/install-gvisor.sh pins the same release).+GVISOR_VERSION=20260921.0+GVISOR_URL_arm64=https://storage.googleapis.com/gvisor/releases/release/20260921.0/aarch64/gvisor.tar.bz2+GVISOR_SHA512_arm64=9438f926b8fadee8c0b8c5c2c954cfc957618acd5d9e1d669e442a9366412dd8794e210b9ce8c7a880a49c8ee9f4f040943a11edae00893d2b22ca844c61de93+GVISOR_URL_amd64=https://storage.googleapis.com/gvisor/releases/release/20260921.0/x86_64/gvisor.tar.bz2+GVISOR_SHA512_amd64=7c899979bed334f0987888c41e545cede8e1f7e67a257978c8de244c3867e32bc30d08491e9af36720273c502acd01d8d86c9844ebcbe125790c43fe6bdf563e++# The host side the SDK downloads next to the disk (not in the image; listed+# so the pins live together). Colima drives Lima, Lima drives+# Virtualization.framework.+COLIMA_VERSION=0.10.3+LIMA_VERSION=2.2.0diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 176613a040..520044dc38 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -25440,6 +25440,11 @@ public struct AppSettingsInput: Equatable, Hashable {* `system`); none: no Runtimes section.*/public var lumeSource: String?+ /**+ * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ * `builtin`, `system`); none: no Linux row.+ */+ public var linuxSource: String?// Default memberwise initializers are never public by default, so we// declare one manually.@@ -25510,7 +25515,11 @@ public struct AppSettingsInput: Equatable, Hashable {/*** Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,* `system`); none: no Runtimes section.- */lumeSource: String?) {+ */lumeSource: String?,+ /**+ * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ * `builtin`, `system`); none: no Linux row.+ */linuxSource: String?) {self.identity = identityself.apiKeyClient = apiKeyClientself.signIn = signIn@@ -25531,6 +25540,7 @@ public struct AppSettingsInput: Equatable, Hashable {self.keyvaultProtection = keyvaultProtectionself.autoConnect = autoConnectself.lumeSource = lumeSource+ self.linuxSource = linuxSource}@@ -25568,7 +25578,8 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {keyvaultSiteIcons: FfiConverterBool.read(from: &buf),keyvaultProtection: FfiConverterSequenceTypeAppFact.read(from: &buf),autoConnect: FfiConverterOptionBool.read(from: &buf),- lumeSource: FfiConverterOptionString.read(from: &buf)+ lumeSource: FfiConverterOptionString.read(from: &buf),+ linuxSource: FfiConverterOptionString.read(from: &buf))}@@ -25593,6 +25604,7 @@ public struct FfiConverterTypeAppSettingsInput: FfiConverterRustBuffer {FfiConverterSequenceTypeAppFact.write(value.keyvaultProtection, into: &buf)FfiConverterOptionBool.write(value.autoConnect, into: &buf)FfiConverterOptionString.write(value.lumeSource, into: &buf)+ FfiConverterOptionString.write(value.linuxSource, into: &buf)}}@@ -30906,6 +30918,11 @@ public struct AppWizardEnv: Equatable, Hashable {* `system`), when known.*/public var lumeSource: String?+ /**+ * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ * `builtin`, `system`), when known (a Mac).+ */+ public var linuxSource: String?/*** Free space and pulled images here (the SDK's `Local.storage()`),* when known.@@ -30968,6 +30985,10 @@ public struct AppWizardEnv: Equatable, Hashable {* Which Lume macOS Spaces run on (`runtime.lume`: `auto`, `builtin`,* `system`), when known.*/lumeSource: String?,+ /**+ * Which engine local Linux Spaces run on (`runtime.linux`: `auto`,+ * `builtin`, `system`), when known (a Mac).+ */linuxSource: String?,/*** Free space and pulled images here (the SDK's `Local.storage()`),* when known.@@ -30999,6 +31020,7 @@ public struct AppWizardEnv: Equatable, Hashable {self.maxCpus = maxCpusself.hostArch = hostArchself.lumeSource = lumeSource+ self.linuxSource = linuxSourceself.storage = storageself.cloudPricing = cloudPricingself.clouds = clouds@@ -31032,6 +31054,7 @@ public struct FfiConverterTypeAppWizardEnv: FfiConverterRustBuffer {maxCpus: FfiConverterUInt32.read(from: &buf),hostArch: FfiConverterOptionString.read(from: &buf),lumeSource: FfiConverterOptionString.read(from: &buf),+ linuxSource: FfiConverterOptionString.read(from: &buf),storage: FfiConverterOptionTypeAppLocalStorage.read(from: &buf),cloudPricing: FfiConverterOptionTypeAppCloudPricing.read(from: &buf),clouds: FfiConverterSequenceTypeAppConnectedCloud.read(from: &buf),@@ -31051,6 +31074,7 @@ public struct FfiConverterTypeAppWizardEnv: FfiConverterRustBuffer {FfiConverterUInt32.write(value.maxCpus, into: &buf)FfiConverterOptionString.write(value.hostArch, into: &buf)FfiConverterOptionString.write(value.lumeSource, into: &buf)+ FfiConverterOptionString.write(value.linuxSource, into: &buf)FfiConverterOptionTypeAppLocalStorage.write(value.storage, into: &buf)FfiConverterOptionTypeAppCloudPricing.write(value.cloudPricing, into: &buf)FfiConverterSequenceTypeAppConnectedCloud.write(value.clouds, into: &buf)diff --git a/scripts/images/image-refs-allowlist.json b/scripts/images/image-refs-allowlist.jsonindex 4606d7fad9..77ca214cef 100644--- a/scripts/images/image-refs-allowlist.json+++ b/scripts/images/image-refs-allowlist.json@@ -628,6 +628,7 @@"ghcr.io/trycua/cua-desktop-linux": "legacy name of ghcr.io/trycua/linux (frozen, read-only; see legacy)","ghcr.io/trycua/localhost": "resolver test message (a host:port prefix is not a repo)","ghcr.io/trycua/macos-sequoia-vanilla": "tag-safety guard list of repos never to re-tag",+ "ghcr.io/trycua/runtime-gvisor": "disk of the built-in Linux runtime VM (cua_vmm::managed), pinned by layer digest; not a Space image, so not in the catalog","public.ecr.aws/k5j5w0x5/cua-omarchy-workspace": "cloud-built Fleet workspace repo (cloud repo owned)","public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04": "cloud-built Fleet workspace repo (cloud repo owned)","public.ecr.aws/k5j5w0x5/cua-windows-2022": "cloud-built Fleet workspace repo (cloud repo owned); source of ghcr.io/trycua/windows:2022-disk"diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lockindex 63dc65dbc7..21ff15d8b4 100644--- a/tests/e2e/local-runtimes/Cargo.lock+++ b/tests/e2e/local-runtimes/Cargo.lock@@ -143,6 +143,59 @@ dependencies = ["pkg-config",]+[[package]]+name = "axum"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"+dependencies = [+ "axum-core",+ "base64 0.22.1",+ "bytes",+ "form_urlencoded",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "serde_core",+ "serde_json",+ "serde_path_to_error",+ "serde_urlencoded",+ "sha1",+ "sync_wrapper",+ "tokio",+ "tokio-tungstenite",+ "tower",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "axum-core"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+]+[[package]]name = "base64"version = "0.22.1"@@ -237,18 +290,40 @@ dependencies = ["serde_repr",]+[[package]]+name = "bstr"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"+dependencies = [+ "memchr",+ "serde_core",+]+[[package]]name = "bumpalo"version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+[[package]]name = "byteorder"version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"+[[package]]name = "bytes"version = "1.12.1"@@ -382,6 +457,35 @@ dependencies = ["unicode-xid",]+[[package]]+name = "cookie"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"+dependencies = [+ "percent-encoding",+ "time",+ "version_check",+]++[[package]]+name = "cookie_store"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206"+dependencies = [+ "cookie",+ "document-features",+ "idna",+ "indexmap",+ "log",+ "serde",+ "serde_derive",+ "serde_json",+ "time",+ "url",+]+[[package]]name = "core-foundation"version = "0.9.4"@@ -435,6 +539,31 @@ dependencies = ["cfg-if",]+[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"+[[package]]name = "crypto-common"version = "0.1.7"@@ -454,6 +583,38 @@ dependencies = ["hybrid-array",]+[[package]]+name = "cua-agent-setup"+version = "0.1.0"+dependencies = [+ "chrono",+ "hex",+ "include_dir",+ "jsonc-parser",+ "serde",+ "serde_json",+ "serde_yaml_ng",+ "sha2 0.10.9",+ "thiserror 2.0.20",+ "toml_edit",+]++[[package]]+name = "cua-agents"+version = "0.1.0"+dependencies = [+ "cua-agent-setup",+ "cua-proto",+ "cua-spacesd-client",+ "hex",+ "rand 0.9.5",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "thiserror 2.0.20",+ "tokio",+]+[[package]]name = "cua-auth"version = "0.1.0"@@ -531,11 +692,14 @@ dependencies = [name = "cua-e2e-local-runtimes"version = "0.0.0"dependencies = [+ "base64 0.22.1","cua-daemon","cua-image","cua-sandbox-core",+ "cua-spaces","cua-vmm","serde_json",+ "tempfile","tokio","tracing-subscriber",]@@ -571,6 +735,50 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "cua-host"+version = "0.1.0"+dependencies = [+ "async-trait",+ "base64 0.22.1",+ "cua-auth",+ "cua-home",+ "flate2",+ "hex",+ "libc",+ "rand 0.9.5",+ "reqwest 0.12.28",+ "ring",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tar",+ "thiserror 2.0.20",+ "tokio",+ "tracing",+ "url",+]++[[package]]+name = "cua-hotspot"+version = "0.1.0"+dependencies = [+ "futures-util",+ "tokio",+]++[[package]]+name = "cua-icon-cache"+version = "0.1.0"+dependencies = [+ "cua-home",+ "hex",+ "image",+ "sha2 0.10.9",+ "tokio",+ "tracing",+]+[[package]]name = "cua-image"version = "0.1.0"@@ -641,6 +849,57 @@ dependencies = ["url",]+[[package]]+name = "cua-spaces"+version = "0.1.0"+dependencies = [+ "async-trait",+ "axum",+ "base64 0.22.1",+ "bytes",+ "chrono",+ "cua-agents",+ "cua-fleet",+ "cua-home",+ "cua-host",+ "cua-hotspot",+ "cua-icon-cache",+ "cua-image",+ "cua-proto",+ "cua-sandbox-core",+ "cua-spaces-contract",+ "cua-spacesd-client",+ "cua-telemetry",+ "futures-util",+ "hex",+ "http",+ "humantime",+ "ignore",+ "pbjson-types",+ "prost",+ "rand 0.9.5",+ "reqwest 0.12.28",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tar",+ "thiserror 2.0.20",+ "tokio",+ "tokio-tungstenite",+ "tonic",+ "tracing",+ "url",+]++[[package]]+name = "cua-spaces-contract"+version = "0.1.0"+dependencies = [+ "schemars",+ "serde",+ "serde_json",+]+[[package]]name = "cua-spacesd-client"version = "0.1.0"@@ -675,6 +934,19 @@ dependencies = ["url",]+[[package]]+name = "cua-telemetry"+version = "0.1.0"+dependencies = [+ "hex",+ "rand 0.9.5",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "toml_edit",+ "ureq",+]+[[package]]name = "cua-vmm"version = "0.1.0"@@ -849,6 +1121,12 @@ dependencies = ["thiserror 2.0.20",]+[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"+[[package]]name = "derive_builder"version = "0.20.2"@@ -933,6 +1211,15 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]+[[package]]name = "dunce"version = "1.0.5"@@ -964,7 +1251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -1211,6 +1498,19 @@ version = "0.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"+[[package]]+name = "globset"+version = "0.4.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"+dependencies = [+ "aho-corasick",+ "bstr",+ "log",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "gloo-timers"version = "0.3.0"@@ -1588,6 +1888,54 @@ dependencies = ["icu_properties",]+[[package]]+name = "ignore"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f"+dependencies = [+ "crossbeam-deque",+ "globset",+ "log",+ "memchr",+ "regex-automata",+ "same-file",+ "walkdir",+ "winapi-util",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "png",+]++[[package]]+name = "include_dir"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd"+dependencies = [+ "include_dir_macros",+]++[[package]]+name = "include_dir_macros"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75"+dependencies = [+ "proc-macro2",+ "quote",+]+[[package]]name = "indexmap"version = "2.14.2"@@ -1737,6 +2085,15 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "jsonc-parser"+version = "0.33.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ff5a48f48971be8e762a6ff955725a0802b6e46c441057992da5a673db9fd3a"+dependencies = [+ "serde_json",+]+[[package]]name = "k8s-openapi"version = "0.28.0"@@ -1845,6 +2202,12 @@ version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"+[[package]]+name = "litrs"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"+[[package]]name = "lock_api"version = "0.4.14"@@ -1875,12 +2238,24 @@ dependencies = ["regex-automata",]+[[package]]+name = "matchit"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"+[[package]]name = "memchr"version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+[[package]]name = "minimal-lexical"version = "0.2.1"@@ -1918,6 +2293,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]+[[package]]name = "multimap"version = "0.10.1"@@ -1940,9 +2325,15 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",]+[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"+[[package]]name = "num-traits"version = "0.2.19"@@ -2192,6 +2583,12 @@ dependencies = ["zerovec",]+[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"+[[package]]name = "ppv-lite86"version = "0.2.21"@@ -2293,6 +2690,12 @@ dependencies = ["pulldown-cmark",]+[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"+[[package]]name = "quinn"version = "0.11.12"@@ -2347,7 +2750,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -2657,7 +3060,7 @@ dependencies = ["errno","libc","linux-raw-sys",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -2716,7 +3119,7 @@ dependencies = ["security-framework 3.7.0","security-framework-sys","webpki-root-certs",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -2928,6 +3331,17 @@ dependencies = ["zmij",]+[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]+[[package]]name = "serde_repr"version = "0.1.21"@@ -2973,6 +3387,19 @@ dependencies = ["unsafe-libyaml",]+[[package]]+name = "serde_yaml_ng"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f"+dependencies = [+ "indexmap",+ "itoa",+ "ryu",+ "serde",+ "unsafe-libyaml",+]+[[package]]name = "sha1"version = "0.10.7"@@ -3084,7 +3511,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -3205,7 +3632,7 @@ dependencies = ["getrandom 0.4.3","once_cell","rustix",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -3267,6 +3694,36 @@ dependencies = ["cfg-if",]+[[package]]+name = "time"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"+dependencies = [+ "num-conv",+ "time-core",+]+[[package]]name = "tinystr"version = "0.8.4"@@ -3824,6 +4281,37 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"+[[package]]+name = "ureq"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"+dependencies = [+ "base64 0.23.1",+ "cookie_store",+ "log",+ "percent-encoding",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "ureq-proto",+ "utf8-zero",+ "webpki-roots 1.0.9",+]++[[package]]+name = "ureq-proto"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"+dependencies = [+ "base64 0.23.1",+ "http",+ "httparse",+ "log",+]+[[package]]name = "url"version = "2.5.8"@@ -3836,6 +4324,12 @@ dependencies = ["serde",]+[[package]]+name = "utf8-zero"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"+[[package]]name = "utf8_iter"version = "1.0.4"@@ -4051,7 +4545,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]diff --git a/tests/e2e/local-runtimes/Cargo.toml b/tests/e2e/local-runtimes/Cargo.tomlindex 863544a1e2..d9b42e55d2 100644--- a/tests/e2e/local-runtimes/Cargo.toml+++ b/tests/e2e/local-runtimes/Cargo.toml@@ -11,6 +11,10 @@ cua-image = { path = "../../../libs/cua/crates/cua-image" }# fleet_catalog.rs drives the SDK's local provider end to end.cua-daemon = { path = "../../../libs/cua/crates/cua-daemon", default-features = false }cua-sandbox-core = { path = "../../../libs/cua/crates/cua-sandbox-core" }+# builtin_linux.rs creates a Space through the Spaces SDK the apps use.+cua-spaces = { path = "../../../libs/cua/crates/cua-spaces" }+base64 = "0.22"+tempfile = "3"tokio = { version = "1", features = ["full"] }tracing-subscriber = { version = "0.3", features = ["env-filter"] }serde_json = "1"diff --git a/tests/e2e/local-runtimes/src/lib.rs b/tests/e2e/local-runtimes/src/lib.rsindex e2a119ef4a..b086f94182 100644--- a/tests/e2e/local-runtimes/src/lib.rs+++ b/tests/e2e/local-runtimes/src/lib.rs@@ -10,6 +10,7 @@//! | `CUA_E2E_LUME=1` | Lume backend against `lume serve` |//! | `CUA_E2E_IMAGE=1` | cua-image registry pulls + local builder |//! | `CUA_E2E_FLEET_CATALOG=1` | every Fleet catalog image through the SDK local provider (`tests/fleet_catalog.rs`) |+//! | `CUA_E2E_BUILTIN_LINUX=1` | a Linux Space on the built-in Linux runtime (macOS; `tests/builtin_linux.rs`) |use std::time::Instant;diff --git a/tests/e2e/local-runtimes/tests/builtin_linux.rs b/tests/e2e/local-runtimes/tests/builtin_linux.rsnew file mode 100644index 0000000000..36dcf91d6c--- /dev/null+++ b/tests/e2e/local-runtimes/tests/builtin_linux.rs@@ -0,0 +1,266 @@+//! A Linux Space on the built-in Linux runtime, through the Spaces SDK the+//! apps use (`CUA_E2E_BUILTIN_LINUX=1`, macOS only).+//!+//! 1. creates `ghcr.io/trycua/linux:24.04` on This Mac with+//! `runtime.linux = builtin`: the runtime is set up (downloaded) and its+//! VM booted on demand, reported as the create's progress;+//! 2. checks the Space runs under gVisor (`dmesg` starts with gVisor's+//! banner), a shell, and computer use (the driver moves the pointer; a+//! capture of the painted desktop);+//! 3. stops the Space (the idle VM stops with it), starts it again (the VM+//! boots on demand), deletes it (the VM stops again).+//!+//! Timings print as `TIMING` lines. With `CUA_E2E_EVIDENCE=<dir>`, the+//! progress reports (`progress.json`), the timings (`timings.json`), the+//! guest's `dmesg` and the desktop capture go there.+//!+//! | env | meaning |+//! |---|---|+//! | `CUA_HOME` | required, a temporary directory (never `~/.cua`); keep it short (Unix socket paths) |+//! | `CUA_RUNTIME_LINUX=builtin` | required: the built-in runtime even with Docker on this Mac |+//! | `CUA_E2E_BUILTIN_LINUX_FRESH=1` | remove the built-in runtime first (measures the first use) |+//! | `CUA_E2E_BUILTIN_LINUX_REMOVE=1` | remove it at the end (what Remove host setup does) |+//! | `CUA_E2E_BUILTIN_LINUX_IMAGE` | image (default `ghcr.io/trycua/linux:24.04`) |++#![cfg(target_os = "macos")]++use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use cua_daemon::local::VmmLocal;+use cua_e2e_local_runtimes::{gated, init_tracing, run_id};+use cua_sandbox_core::placement::On;+use cua_spaces::{ProgressSink, SpaceCreate, SpaceCreated, Spaces};+use cua_vmm::managed::{self, LinuxSource};+use serde_json::{Map, Value, json};++#[tokio::test(flavor = "multi_thread")]+async fn a_linux_space_on_the_builtin_runtime() {+ if !gated("CUA_E2E_BUILTIN_LINUX") {+ return;+ }+ init_tracing();+ let home = std::env::var("CUA_HOME").expect("set CUA_HOME to a temporary directory");+ assert!(+ !home.is_empty() && !home.ends_with("/.cua"),+ "never the real cua home"+ );+ assert_eq!(+ LinuxSource::current(),+ LinuxSource::Builtin,+ "set CUA_RUNTIME_LINUX=builtin"+ );+ let evidence = std::env::var("CUA_E2E_EVIDENCE")+ .ok()+ .map(std::path::PathBuf::from);+ if let Some(d) = &evidence {+ std::fs::create_dir_all(d).unwrap();+ }+ let save = |name: &str, bytes: &[u8]| {+ if let Some(d) = &evidence {+ std::fs::write(d.join(name), bytes).unwrap();+ }+ };+ if std::env::var("CUA_E2E_BUILTIN_LINUX_FRESH").as_deref() == Ok("1") {+ managed::remove().await.unwrap();+ }+ let fresh = !managed::exists();+ let was_running = managed::running();+ let image = std::env::var("CUA_E2E_BUILTIN_LINUX_IMAGE")+ .unwrap_or_else(|_| "ghcr.io/trycua/linux:24.04".into());+ let mut timings = Map::new();+ let mut lap = |label: &str, secs: f64| {+ eprintln!("TIMING {label}: {secs:.1}s");+ timings.insert(label.into(), json!((secs * 10.0).round() / 10.0));+ };++ let reg = tempfile::tempdir().unwrap();+ let spaces = Spaces::builder()+ .home(reg.path())+ .download_dir(reg.path().join("downloads"))+ .operator_display(Arc::new(cua_spaces::operator::NoDisplay))+ .local_runtime(Arc::new(VmmLocal::default()))+ .probe_timeout(Duration::from_secs(20))+ .build();++ // 1. Create, recording every progress report.+ let t0 = Instant::now();+ let reports: Arc<Mutex<Vec<Value>>> = Arc::default();+ let sink = {+ let reports = reports.clone();+ ProgressSink::new(move |p| {+ reports.lock().unwrap().push(json!({+ "t": (t0.elapsed().as_secs_f64() * 10.0).round() / 10.0,+ "phase": p.phase.as_str(),+ "fraction": p.fraction,+ "detail": p.detail,+ "bytes": p.bytes.map(|b| json!([b.done, b.total])),+ }));+ })+ };+ let name = format!("e2e-builtin-{}", run_id());+ let created = spaces+ .create(SpaceCreate {+ image: Some(image.clone()),+ on: Some(On::Local),+ name: Some(name.clone()),+ cpus: Some(2),+ memory_mb: Some(3072),+ progress: Some(sink),+ ..Default::default()+ })+ .await+ .expect("create");+ let create_secs = t0.elapsed().as_secs_f64();+ let reports = reports.lock().unwrap().clone();+ save(+ "progress.json",+ &serde_json::to_vec_pretty(&reports).unwrap(),+ );+ // The runtime's set up is the create's own progress, in words.+ let setup: Vec<&Value> = reports+ .iter()+ .filter(|r| r["detail"] == managed::SETTING_UP)+ .collect();+ let mut setup_end = 0.0;+ if !was_running {+ assert!(+ !setup.is_empty(),+ "no runtime set-up progress: {reports:#?}"+ );+ setup_end = setup.last().unwrap()["t"].as_f64().unwrap();+ if fresh {+ let dl_end = setup+ .iter()+ .filter(|r| !r["bytes"].is_null())+ .map(|r| r["t"].as_f64().unwrap())+ .fold(0.0, f64::max);+ lap("first-use download", dl_end);+ lap("runtime VM cold boot", setup_end - dl_end);+ } else {+ lap("runtime VM boot", setup_end);+ }+ }+ lap("Space create (total)", create_secs);+ lap(+ "Space create after the runtime is up",+ create_secs - setup_end,+ );+ let SpaceCreated::Ready { info, .. } = created else {+ panic!("not ready: {created:?}");+ };+ assert!(managed::running());++ // 2. gVisor, a shell, computer use.+ let space = spaces.space(&info.id).await.unwrap();+ let dmesg = space+ .bash("dmesg | head -5; uname -r", Duration::from_secs(60))+ .await+ .unwrap();+ eprintln!("dmesg:\n{}", dmesg.stdout);+ save("dmesg.txt", dmesg.stdout.as_bytes());+ assert!(dmesg.success(), "{dmesg:?}");+ assert!(+ dmesg.stdout.contains("Starting gVisor"),+ "not gVisor: {}",+ dmesg.stdout+ );+ let echo = space+ .bash(+ "echo hi from $(whoami) && ls / | head -3",+ Duration::from_secs(60),+ )+ .await+ .unwrap();+ assert!(echo.success() && echo.stdout.starts_with("hi from"));+ let (tools, _) = space.list_tools(None).await.expect("driver tools");+ let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();+ eprintln!("{} driver tools: {names:?}", names.len());+ assert!(names.contains(&"get_desktop_state") && names.contains(&"move_cursor"));+ let args = |v: Value| v.as_object().cloned().unwrap();+ let desktop = json!({"kind": "desktop", "display_id": "primary"});+ // Computer use: move the pointer, check it moved from inside the guest.+ let moved = space+ .call_tool(+ None,+ "move_cursor",+ args(json!({"x": 211, "y": 157, "target": desktop})),+ Some(Duration::from_secs(60)),+ )+ .await+ .expect("move_cursor");+ assert!(!moved.is_error, "{:?}", moved.content);+ let pointer = space+ .bash(+ "DISPLAY=:1 xdotool getmouselocation",+ Duration::from_secs(30),+ )+ .await+ .unwrap();+ assert!(pointer.stdout.contains("x:211 y:157"), "{}", pointer.stdout);+ // And see the desktop (ready is cua-spacesd up; XFCE paints a few+ // seconds later).+ use base64::Engine as _;+ let mut png = Vec::new();+ for _ in 0..24 {+ let shot = space+ .call_tool(+ None,+ "get_desktop_state",+ Map::new(),+ Some(Duration::from_secs(60)),+ )+ .await+ .expect("get_desktop_state");+ assert!(!shot.is_error, "{:?}", shot.content);+ let data = shot+ .content+ .iter()+ .find(|c| c["type"] == "image")+ .and_then(|c| c["data"].as_str())+ .expect("an image part");+ png = base64::engine::general_purpose::STANDARD+ .decode(data)+ .unwrap();+ // A painted desktop compresses to tens of KB; a blank frame to+ // a few hundred bytes.+ if png.len() > 10_000 {+ break;+ }+ tokio::time::sleep(Duration::from_secs(5)).await;+ }+ save("desktop.png", &png);+ eprintln!("desktop capture: {} bytes", png.len());+ assert!(png.len() > 10_000, "a painted desktop, not a blank frame");++ // 3. Stop (the idle VM stops), start (it boots again), delete.+ let t = Instant::now();+ spaces.stop(&info.id).await.expect("stop");+ lap("Space stop (and idle VM stop)", t.elapsed().as_secs_f64());+ assert!(!managed::running(), "the idle VM stops with the last Space");+ let t = Instant::now();+ spaces.start(&info.id).await.expect("start");+ lap(+ "Space start (VM boots on demand)",+ t.elapsed().as_secs_f64(),+ );+ assert!(managed::running());+ let again = spaces.space(&info.id).await.unwrap();+ let out = again+ .bash("dmesg | head -1", Duration::from_secs(60))+ .await+ .unwrap();+ assert!(out.stdout.contains("gVisor"), "{out:?}");+ let t = Instant::now();+ spaces.delete(&info.id).await.expect("delete");+ lap("Space delete (and idle VM stop)", t.elapsed().as_secs_f64());+ assert!(!managed::running());+ save(+ "timings.json",+ &serde_json::to_vec_pretty(&Value::Object(timings)).unwrap(),+ );+ if std::env::var("CUA_E2E_BUILTIN_LINUX_REMOVE").as_deref() == Ok("1") {+ managed::remove().await.unwrap();+ assert!(!managed::root().exists());+ }+}