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
fix(cua-spaces): install or start Docker Desktop from New Space on Windows (CUA-1723) (#5265)
Francesco Bonacci4c06e50b655b
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 3b58d72ec6..4d4b3e4511 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -47,8 +47,9 @@ export const METHODS = [] as const;/** A live desktop's media ticket for the page's WebCodecs player, the- * first run's state (the SwiftUI app draws its first run natively), and- * presence over the page's video (the SwiftUI app draws it natively). */-export const ELECTRON_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream", "presence.join", "presence.publish", "presence.leave"] as const;+ * first run's state (the SwiftUI app draws its first run natively),+ * presence over the page's video (the SwiftUI app draws it natively), and+ * New Space's runtime fix on Windows ("Install Docker Desktop"). */+export const ELECTRON_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime"] as const;export type Method = (typeof METHODS)[number] | (typeof ELECTRON_METHODS)[number];diff --git a/apps/cua-spaces-desktop/src/bridge/spaces.ts b/apps/cua-spaces-desktop/src/bridge/spaces.tsindex 1728e35416..1894a5ebe3 100644--- a/apps/cua-spaces-desktop/src/bridge/spaces.ts+++ b/apps/cua-spaces-desktop/src/bridge/spaces.ts@@ -8,6 +8,7 @@import type { Native } from "../native/load";import type { AppCreateSpaceArgs, AppRuntime, AppSpace, AppWizardEnv, SpaceCreateProgress } from "../native/generated/index";import { AppModel } from "../model/app-model";+import type { RuntimeFix } from "../model/windows-runtime";import { kindOf, osOf } from "../model/backend";import { isCancelled } from "../model/errors";import { bool, string } from "./args";@@ -34,12 +35,14 @@ export function spacesState(model: AppModel) {* `NewSpaceOptions` (plus `macosVmsRunning`; `pending` while the launch is* still starting, when every probe would wait).*/-export function createOptions(env: AppWizardEnv, macosVmsRunning: number | null, pending: boolean) {+export function createOptions(env: AppWizardEnv, macosVmsRunning: number | null, pending: boolean, fix: RuntimeFix | null = null) {const out: Record<string, unknown> = {local: {available: env.localAvailable,backends: env.localBackends ?? [],error: env.localReason ?? null,+ // Windows without a runtime: what the app can do about it ("Install Docker Desktop").+ fix: env.localAvailable ? null : fix,hostArch: env.hostArch ?? null,storage: encode(env.storage),},@@ -114,7 +117,14 @@ export function spacesMethods(ctx: BridgeContext): Handlers {"spaces.createOptions": async () => {if (!model.servicesIn) return createOptions(model.knownNewSpaceEnv(), null, true);const env = await model.newSpaceEnv();- return createOptions(env, model.runningMacosVms, false);+ return createOptions(env, model.runningMacosVms, false, model.runtimeFix);+ },+ "spaces.fixRuntime": (args) => {+ const action = string(args, "action");+ if (action !== "install-docker" && action !== "start-docker") throw Failure.badArgs("action: install-docker | start-docker");+ if (!model.windowsRuntime) throw Failure.unsupported("no runtime fix on this system");+ model.fixRuntime(action);+ return null;},"spaces.create": async (args) => {const pendingId = string(args, "pendingId");diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.tsindex cbab4b8ccb..2d60e9b973 100644--- a/apps/cua-spaces-desktop/src/model/app-model.ts+++ b/apps/cua-spaces-desktop/src/model/app-model.ts@@ -46,6 +46,7 @@ import type { AccountRunning, TelemetryRunning } from "./services";import type { StartupModel } from "./startup";import { SpaceThumbnails } from "./thumbnails";import { noLocalRuntimeReason } from "./local-runtime";+import type { RuntimeFix, RuntimeFixAction, WindowsRuntime, WindowsRuntimeAdvice } from "./windows-runtime";import { TimeoutError, sleep, withTimeout } from "./time";/** What changed, for the page's events. */@@ -77,6 +78,8 @@ export interface AppModelDeps {checklistSeedPath?: string | null;/** The system this app runs on (names This machine on the Machines page). */hostOs?: AppSpaceOs;+ /** What New Space offers when Windows has no local runtime (null elsewhere). */+ windowsRuntime?: WindowsRuntime | null;}/** The create the daemon never took. */@@ -152,6 +155,9 @@ export class AppModel {linuxSource: string | null = null;/** Your machines that provide Spaces, as New Space last read them. */hosts: AppSpaceHost[] = [];+ /** Windows without a local runtime: why, and the fix New Space offers (null when one is ready). */+ runtimeAdvice: WindowsRuntimeAdvice | null = null;+ readonly windowsRuntime: WindowsRuntime | null;/** How long one read of the registry may take before a refresh gives up on it (s). */listTimeout = 20;/** How long the host's own reads in a refresh may take (s). */@@ -213,6 +219,7 @@ export class AppModel {this.checklist.telemetry = d.telemetry;this.checklist.onChange = () => this.changed("checklist");this.settingsPath = d.settingsPath;+ this.windowsRuntime = d.windowsRuntime ?? null;this.servicesInNow = d.servicesIn;this.maxCpus = Math.max(2, Math.min(16, d.cpus));this.settings = d.native.appSettingsLoad(d.settingsPath);@@ -538,9 +545,33 @@ export class AppModel {this.hosts = hosts;// Lume did not answer this time: keep what it said last.this.runningMacosVms = vms ?? this.runningMacosVms;+ await this.readRuntimeAdvice(runtimes);return this.wizardEnv(cloud, runtimes, storage, pricing, gpus);}+ /** Windows: what is missing for local Spaces and what the app can do about it. */+ private async readRuntimeAdvice(runtimes: LocalRuntimes | null): Promise<void> {+ const w = this.windowsRuntime;+ if (!w || !runtimes) return;+ if (runtimes.ready.length > 0) {+ w.settled();+ this.runtimeAdvice = null;+ return;+ }+ this.runtimeAdvice = await w.advice().catch(() => null);+ }++ /** The fix New Space shows beside the reason (Windows only). */+ get runtimeFix(): RuntimeFix | null {+ return this.runtimeAdvice?.fix ?? null;+ }++ /** Runs a New Space fix ("Install Docker Desktop"); the page reads the options again to follow it. */+ fixRuntime(action: RuntimeFixAction): void {+ if (!this.windowsRuntime) throw new Error("no runtime fix on this system");+ this.windowsRuntime.run(action);+ }+/** What New Space knows without asking anything: the env while the live services are still starting. */knownNewSpaceEnv(): AppWizardEnv {return this.wizardEnv(false, null, null, null, null);@@ -558,7 +589,10 @@ export class AppModel {defaultLocation: this.settings.defaultLocation,cloudAvailable: available,localAvailable: backends ? backends.length > 0 : true,- localReason: backends && backends.length === 0 ? noLocalRuntimeReason(process.platform, runtimes?.details.get("container")) : undefined,+ localReason:+ backends && backends.length === 0+ ? (this.runtimeAdvice?.reason ?? noLocalRuntimeReason(process.platform, runtimes?.details.get("container")))+ : undefined,localBackends: backends,localDetails: runtimes?.details,maxCpus: this.maxCpus,diff --git a/apps/cua-spaces-desktop/src/model/environment.ts b/apps/cua-spaces-desktop/src/model/environment.tsindex f5daa1f3b2..65635c161f 100644--- a/apps/cua-spaces-desktop/src/model/environment.ts+++ b/apps/cua-spaces-desktop/src/model/environment.ts@@ -29,6 +29,7 @@ import { LiveGate, PendingAccount, PendingSpacesBackend, type LiveServices } froimport { LiveAccount, LiveTelemetry, hostAccount } from "./services";import { BundledCuaKeychain, StartupModel } from "./startup";import { withTimeout } from "./time";+import { WindowsRuntime, nodeWindowsSystem } from "./windows-runtime";/** Whether the first run finished (`onboarding.json`'s `completed`); null when unknown. */export function readOnboardingCompleted(file: string): boolean | null {@@ -124,6 +125,7 @@ export function makeModel(o: EnvironmentOptions): Environment {checklistPath: path.join(path.dirname(settingsPath), "checklist.json"),checklistSeedPath: platform === "darwin" ? path.join(swiftSupportDir(env.HOME || os.homedir()), "checklist.json") : null,hostOs: platform === "win32" ? native.AppSpaceOs.Windows : platform === "linux" ? native.AppSpaceOs.Linux : native.AppSpaceOs.Macos,+ windowsRuntime: platform === "win32" ? new WindowsRuntime(nodeWindowsSystem(), path.join(os.tmpdir(), "cua-spaces")) : null,});// Signed out is null (setup signs in first); anything else is the error itself.diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.test.tsnew file mode 100644index 0000000000..113799b26f--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.test.ts@@ -0,0 +1,258 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";+import {+ ELEVATED_INSTALL_SCRIPT,+ START_PATIENCE_MS,+ WindowsRuntime,+ currentUser,+ installFailedText,+ parseInstallResult,+ parseVirtualization,+ signedByDocker,+ windowsRuntimeAdvice,+ type WindowsRuntimeFacts,+ type WindowsSystem,+} from "./windows-runtime";++const CLEAN: WindowsRuntimeFacts = { dockerInstalled: false, dockerRunning: false, virtualization: "on", restartPending: false };+const IDLE = { kind: "idle" } as const;++describe("windowsRuntimeAdvice", () => {+ it("offers the install on a clean PC (A10: no Docker Desktop)", () => {+ const a = windowsRuntimeAdvice(CLEAN, IDLE, 0);+ expect(a.reason).toMatch(/Docker Desktop, which isn't installed/);+ expect(a.fix).toMatchObject({ action: "install-docker", label: "Install Docker Desktop", busy: false });+ expect(a.fix?.note).toMatch(/administrator approval/);+ expect(a.fix?.termsUrl).toMatch(/^https:\/\/www\.docker\.com\//);+ });++ it("says virtualization is off and offers nothing to install", () => {+ const a = windowsRuntimeAdvice({ ...CLEAN, virtualization: "off" }, IDLE, 0);+ expect(a.reason).toMatch(/virtualization is turned off/);+ expect(a.reason).toMatch(/another computer/);+ expect(a.fix).toBeNull();+ });++ it("asks for a restart after the install, with no button", () => {+ const a = windowsRuntimeAdvice({ ...CLEAN, dockerInstalled: true, restartPending: true }, IDLE, 0);+ expect(a.reason).toMatch(/^Restart this PC/);+ expect(a.fix).toBeNull();+ });++ it("offers to start an installed Docker Desktop that isn't running", () => {+ const a = windowsRuntimeAdvice({ ...CLEAN, dockerInstalled: true }, IDLE, 0);+ expect(a.reason).toMatch(/installed but not running/);+ expect(a.fix).toMatchObject({ action: "start-docker", busy: false });+ });++ it("waits while Docker Desktop starts, then says where to look", () => {+ const facts = { ...CLEAN, dockerInstalled: true, dockerRunning: true };+ const soon = windowsRuntimeAdvice(facts, { kind: "starting", since: 0 }, 10_000);+ expect(soon.reason).toMatch(/is starting/);+ expect(soon.fix).toMatchObject({ action: null, busy: true });+ const late = windowsRuntimeAdvice(facts, { kind: "starting", since: 0 }, START_PATIENCE_MS + 1);+ expect(late.reason).toMatch(/finish it there/);+ });++ it("shows the download's progress and the install as busy", () => {+ expect(windowsRuntimeAdvice(CLEAN, { kind: "downloading", percent: 42 }, 0).fix).toMatchObject({ label: "Downloading Docker Desktop… 42%", busy: true, action: null });+ expect(windowsRuntimeAdvice(CLEAN, { kind: "installing" }, 0).fix).toMatchObject({ busy: true, action: null });+ });++ it("says why an install failed and offers it again", () => {+ const a = windowsRuntimeAdvice(CLEAN, { kind: "failed", message: installFailedText(new Error("cancelled")) }, 0);+ expect(a.reason).toMatch(/prompt was declined/);+ expect(a.fix?.action).toBe("install-docker");+ });+});++describe("probe parsing", () => {+ it("counts a running hypervisor as virtualization on (it hides the firmware flag)", () => {+ expect(parseVirtualization("True|False")).toBe("on");+ expect(parseVirtualization("False|True")).toBe("on");+ expect(parseVirtualization("False|False")).toBe("off");+ expect(parseVirtualization("")).toBe("unknown");+ });++ it("accepts only Docker's valid signature", () => {+ const subject = "CN=Docker Inc, O=Docker Inc, L=Palo Alto, S=California, C=US";+ expect(signedByDocker(`Valid|${subject}`)).toBe(true);+ expect(signedByDocker(`HashMismatch|${subject}`)).toBe(false);+ expect(signedByDocker("Valid|CN=Someone Else, O=Evil Corp")).toBe(false);+ expect(signedByDocker("NotSigned|")).toBe(false);+ });++ it("reads the elevated script's result", () => {+ expect(parseInstallResult("0|False|True\r\n")).toEqual({ installer: 0, addedToGroup: false, wslReady: true });+ expect(parseInstallResult("3010|True|False")).toEqual({ installer: 3010, addedToGroup: true, wslReady: false });+ expect(parseInstallResult("")).toBeNull();+ });++ it("names the signed-in user for docker-users", () => {+ expect(currentUser({ USERDOMAIN: "PC", USERNAME: "ana" })).toBe("PC\\ana");+ expect(currentUser({ USERNAME: "ana" })).toBe("ana");+ expect(currentUser({})).toBe("");+ });++ it("installs with Docker's documented silent flags and the WSL package", () => {+ expect(ELEVATED_INSTALL_SCRIPT).toContain("'install','--quiet','--accept-license','--backend=wsl-2'");+ expect(ELEVATED_INSTALL_SCRIPT).toContain("Add-LocalGroupMember -Group 'docker-users'");+ expect(ELEVATED_INSTALL_SCRIPT).toContain("wsl.exe --install --no-distribution --web-download");+ });+});++/** A Windows that answers from `state`, recording what was run. */+function fakeSystem(state: {+ installed?: boolean;+ running?: boolean;+ hv?: string;+ rebootPending?: boolean;+ signature?: string;+ result?: string;+ elevated?: { code: number; stderr?: string };+}) {+ const ran: string[] = [];+ const files = new Map<string, string>();+ const sys: WindowsSystem = {+ exists: async () => state.installed ?? false,+ running: async () => state.running ?? false,+ async powershell(script) {+ ran.push(script);+ if (script.includes("Win32_ComputerSystem")) return { code: 0, stdout: state.hv ?? "True|True", stderr: "" };+ if (script.includes("RebootPending")) return { code: 0, stdout: state.rebootPending ? "pending" : "clear", stderr: "" };+ if (script.includes("Get-AuthenticodeSignature")) return { code: 0, stdout: state.signature ?? "Valid|CN=Docker Inc, O=Docker Inc", stderr: "" };+ if (script.includes("-Verb RunAs")) {+ const r = state.elevated ?? { code: 0 };+ const result = [...files.keys()].find((k) => k.endsWith(".result"));+ if (result && state.result !== undefined) files.set(result, state.result);+ return { code: r.code, stdout: "", stderr: r.stderr ?? "" };+ }+ return { code: 1, stdout: "", stderr: "unexpected" };+ },+ async download(_url, _to, progress) {+ ran.push("download");+ progress(50);+ },+ async writeFile(path, text) {+ files.set(path, text);+ },+ readFile: async (path) => files.get(path) ?? "",+ launch(path) {+ ran.push(`launch ${path}`);+ state.running = true;+ },+ };+ return { sys, ran, files };+}++const settle = () => new Promise((r) => setTimeout(r, 0));++describe("WindowsRuntime", () => {+ it("installs, then starts Docker Desktop when no restart is needed", async () => {+ const f = fakeSystem({ result: "0|False|True" });+ const w = new WindowsRuntime(f.sys, "C:\\tmp", () => 1_000);+ expect((await w.advice()).fix?.action).toBe("install-docker");+ w.run("install-docker");+ await settle();+ await settle();+ await settle();+ expect(f.ran).toContain("download");+ const elevated = f.ran.find((s) => s.includes("-Verb RunAs"))!;+ expect(elevated).toContain("'-File','C:\\tmp");+ expect(f.files.get([...f.files.keys()].find((k) => k.endsWith(".ps1"))!)).toBe(ELEVATED_INSTALL_SCRIPT);+ expect(f.ran.some((s) => s.startsWith("launch ") && s.endsWith("Docker Desktop.exe"))).toBe(true);+ f.sys.exists = async () => true;+ expect((await w.advice()).fix).toMatchObject({ busy: true, label: "Waiting for Docker Desktop…" });+ w.settled();+ });++ it("asks for a restart when Windows turned WSL 2 on", async () => {+ const f = fakeSystem({ result: "0|False|False" });+ const w = new WindowsRuntime(f.sys, "C:\\tmp");+ w.run("install-docker");+ for (let i = 0; i < 5; i++) await settle();+ f.sys.exists = async () => true;+ const a = await w.advice();+ expect(a.reason).toMatch(/^Restart this PC/);+ expect(f.ran.some((s) => s.startsWith("launch "))).toBe(false);+ });++ it("asks for a restart when the user just joined docker-users", async () => {+ const f = fakeSystem({ result: "0|True|True" });+ const w = new WindowsRuntime(f.sys, "C:\\tmp");+ w.run("install-docker");+ for (let i = 0; i < 5; i++) await settle();+ expect((await w.advice()).reason).toMatch(/^Restart this PC/);+ });++ it("refuses an installer not signed by Docker", async () => {+ const f = fakeSystem({ signature: "Valid|CN=Mallory, O=Mallory" });+ const w = new WindowsRuntime(f.sys, "C:\\tmp");+ w.run("install-docker");+ for (let i = 0; i < 5; i++) await settle();+ expect((await w.advice()).reason).toMatch(/isn't signed by Docker/);+ expect(f.ran.some((s) => s.includes("-Verb RunAs"))).toBe(false);+ });++ it("says so when the UAC prompt is declined", async () => {+ const f = fakeSystem({ elevated: { code: 1, stderr: "This command cannot be run due to the error: The operation was canceled by the user." } });+ const w = new WindowsRuntime(f.sys, "C:\\tmp");+ w.run("install-docker");+ for (let i = 0; i < 5; i++) await settle();+ const a = await w.advice();+ expect(a.reason).toMatch(/prompt was declined/);+ expect(a.fix?.action).toBe("install-docker");+ });++ it("starts an installed Docker Desktop", async () => {+ const f = fakeSystem({ installed: true });+ const w = new WindowsRuntime(f.sys, "C:\\tmp");+ expect((await w.advice()).fix?.action).toBe("start-docker");+ w.run("start-docker");+ expect(f.ran.some((s) => s.startsWith("launch "))).toBe(true);+ expect((await w.advice()).fix?.busy).toBe(true);+ });++ it("reads virtualization once", async () => {+ const f = fakeSystem({ hv: "False|False" });+ const w = new WindowsRuntime(f.sys, "C:\\tmp");+ expect((await w.advice()).reason).toMatch(/virtualization is turned off/);+ await w.advice();+ expect(f.ran.filter((s) => s.includes("Win32_ComputerSystem"))).toHaveLength(1);+ });+});++describe("nodeWindowsSystem.download", () => {+ it("writes every byte (no chunk lost before the file opens) and reports progress", async () => {+ const { mkdtemp, readFile } = await import("node:fs/promises");+ const { tmpdir } = await import("node:os");+ const { join } = await import("node:path");+ const { nodeWindowsSystem } = await import("./windows-runtime");+ const chunks = Array.from({ length: 64 }, (_, i) => new Uint8Array(4096).fill(i));+ const total = chunks.length * 4096;+ const body = new ReadableStream<Uint8Array>({+ start(c) {+ for (const ch of chunks) c.enqueue(ch);+ c.close();+ },+ });+ const fetchImpl = (async () => new Response(body, { headers: { "content-length": String(total) } })) as unknown as typeof fetch;+ const dir = await mkdtemp(join(tmpdir(), "w2-dl-"));+ const seen: (number | null)[] = [];+ await nodeWindowsSystem(fetchImpl).download("https://x/i.exe", join(dir, "i.exe"), (p) => seen.push(p));+ expect((await readFile(join(dir, "i.exe"))).length).toBe(total);+ expect(seen.at(-1)).toBe(100);+ });++ it("refuses a short download", async () => {+ const { mkdtemp } = await import("node:fs/promises");+ const { tmpdir } = await import("node:os");+ const { join } = await import("node:path");+ const { nodeWindowsSystem } = await import("./windows-runtime");+ const fetchImpl = (async () => new Response(new Uint8Array(10), { headers: { "content-length": "20" } })) as unknown as typeof fetch;+ const dir = await mkdtemp(join(tmpdir(), "w2-dl-"));+ await expect(nodeWindowsSystem(fetchImpl).download("https://x/i.exe", join(dir, "i.exe"), () => undefined)).rejects.toThrow(/incomplete/);+ });+});diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.tsnew file mode 100644index 0000000000..2c08f69e84--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.ts@@ -0,0 +1,418 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Local Spaces on Windows run in Docker Desktop (its WSL 2 engine). A clean+ * Windows 11 PC has neither, so New Space and onboarding used to stop at a+ * red line with a docs link. This finds out what is missing and fixes what+ * it can from the app:+ *+ * - Docker Desktop not installed: downloads Docker's signed installer,+ * checks its signature, and runs Docker's documented silent install+ * (`install --quiet --accept-license --backend=wsl-2`) through one UAC+ * prompt. The installer turns on WSL 2 itself.+ * - Installed but not running: starts it.+ * - Starting: says so; the page asks again until the engine answers.+ * - Needs a restart (Windows turned on WSL 2 or the installer said so): says so.+ * - Virtualization off in the firmware: nothing to install; says how to+ * turn it on, or to use another computer.+ *+ * Everything that touches the system goes through {@link WindowsSystem}, so+ * the decisions are tested without Windows.+ */++import { createWriteStream } from "node:fs";+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";+import { execFile, spawn } from "node:child_process";+import { join } from "node:path";+import { Readable, Transform } from "node:stream";+import { pipeline } from "node:stream/promises";++/** What the page's fix button does (`spaces.fixRuntime {action}`). */+export type RuntimeFixAction = "install-docker" | "start-docker";++/** A step the page can offer next to the "no local runtime" reason. */+export interface RuntimeFix {+ /** What the button runs; null while something runs, or when only the person can act (restart, firmware). */+ action: RuntimeFixAction | null;+ /** The button's label ("Install Docker Desktop"). */+ label: string;+ /** One line under the button: what happens, how long, what Windows asks. */+ note: string | null;+ /** Something runs now (download, install, start): the page polls the options until it settles. */+ busy: boolean;+ /** Terms the action accepts (Docker's), linked beside the note. */+ termsUrl: string | null;+}++/** What the probe found out about this PC. */+export interface WindowsRuntimeFacts {+ /** `Docker Desktop.exe` is installed. */+ dockerInstalled: boolean;+ /** Its process runs (the engine may still be starting). */+ dockerRunning: boolean;+ /** Hardware virtualization: on (or a hypervisor already runs), off in the firmware, or unknown. */+ virtualization: "on" | "off" | "unknown";+ /** Windows waits for a restart to finish turning on WSL 2 / the install. */+ restartPending: boolean;+}++/** Where a fix the app started is now. */+export type FixPhase =+ | { kind: "idle" }+ | { kind: "downloading"; percent: number | null }+ | { kind: "installing" }+ | { kind: "starting"; since: number }+ | { kind: "failed"; message: string };++/** The reason and the fix New Space shows when no local runtime is ready. */+export interface WindowsRuntimeAdvice {+ reason: string;+ fix: RuntimeFix | null;+}++const DOCKER_TERMS = "https://www.docker.com/legal/docker-subscription-service-agreement/";+/** After this long "starting", say where to look instead of waiting quietly. */+export const START_PATIENCE_MS = 3 * 60_000;++/**+ * The reason and the fix for a PC where no local runtime answered.+ * `containerDetail` is the runtime doctor's word for the container engine.+ */+export function windowsRuntimeAdvice(facts: WindowsRuntimeFacts, phase: FixPhase, now: number): WindowsRuntimeAdvice {+ if (facts.virtualization === "off") {+ return {+ reason:+ "This PC can't run local Spaces: virtualization is turned off. Turn on Intel VT-x or AMD-V (SVM) in the PC's firmware (BIOS/UEFI) settings, or run Spaces on another computer.",+ fix: null,+ };+ }+ switch (phase.kind) {+ case "downloading":+ return {+ reason: "Getting Docker Desktop, which runs local Spaces on Windows.",+ fix: {+ action: null,+ label: phase.percent === null ? "Downloading Docker Desktop…" : `Downloading Docker Desktop… ${phase.percent}%`,+ note: "About 600 MB. Windows asks for administrator approval when it's in.",+ busy: true,+ termsUrl: null,+ },+ };+ case "installing":+ return {+ reason: "Installing Docker Desktop, which runs local Spaces on Windows.",+ fix: { action: null, label: "Installing Docker Desktop…", note: "Approve the Windows prompt. This takes a few minutes.", busy: true, termsUrl: null },+ };+ case "failed":+ return {+ reason: phase.message,+ fix: facts.dockerInstalled ? startFix() : installFix(),+ };+ default:+ break;+ }+ if (facts.restartPending) {+ return {+ reason: "Restart this PC to finish setting up Docker Desktop (Windows turned on WSL 2). Then open Cua Spaces again.",+ fix: null,+ };+ }+ if (!facts.dockerInstalled) {+ return {+ reason: "Local Spaces on Windows run in Docker Desktop, which isn't installed yet.",+ fix: installFix(),+ };+ }+ if (facts.dockerRunning || phase.kind === "starting") {+ const waited = phase.kind === "starting" ? now - phase.since : 0;+ return {+ reason:+ waited > START_PATIENCE_MS+ ? "Docker Desktop is still starting. If it shows a window (terms, sign-in or an update), finish it there; this updates when its engine runs."+ : "Docker Desktop is starting. This updates when its engine runs (about a minute).",+ fix: { action: null, label: "Waiting for Docker Desktop…", note: null, busy: true, termsUrl: null },+ };+ }+ return { reason: "Docker Desktop is installed but not running.", fix: startFix() };+}++function installFix(): RuntimeFix {+ return {+ action: "install-docker",+ label: "Install Docker Desktop",+ note: "About 600 MB. Windows asks for administrator approval (Windows PowerShell) and may need a restart. Installing accepts Docker's subscription terms; Docker Desktop is free for personal use and small businesses.",+ busy: false,+ termsUrl: DOCKER_TERMS,+ };+}++function startFix(): RuntimeFix {+ return { action: "start-docker", label: "Start Docker Desktop", note: null, busy: false, termsUrl: null };+}++/* ---- The system ------------------------------------------------------------ */++/** The Windows calls the fixes make (faked in tests). */+export interface WindowsSystem {+ exists(path: string): Promise<boolean>;+ /** Image names of running processes, lower case. */+ running(image: string): Promise<boolean>;+ /** PowerShell, no profile; stdout, or null when it failed. */+ powershell(script: string, timeoutMs: number): Promise<{ code: number; stdout: string; stderr: string }>;+ download(url: string, to: string, progress: (percent: number | null) => void): Promise<void>;+ writeFile(path: string, text: string): Promise<void>;+ readFile(path: string): Promise<string>;+ launch(path: string): void;+}++/**+ * Runs elevated (one UAC prompt): Docker Desktop's documented silent install+ * with the WSL 2 backend, the signed-in user into docker-users, then the WSL+ * package when `wsl --version` says it is missing. Writes+ * `<installer exit>|<added to docker-users>|<wsl ready>` to `-Result`.+ */+export const ELEVATED_INSTALL_SCRIPT = `param([string]$Installer, [string]$User, [string]$Result)+$ErrorActionPreference = 'Continue'+$added = $false+$wsl = $false+$p = Start-Process -FilePath $Installer -ArgumentList 'install','--quiet','--accept-license','--backend=wsl-2' -Wait -PassThru+$code = $p.ExitCode+if ($code -eq 0 -or $code -eq 3010 -or $code -eq 1641) {+ if ($User) {+ $member = Get-LocalGroupMember -Group 'docker-users' -ErrorAction SilentlyContinue | Where-Object { $_.Name -ieq $User }+ if (-not $member) {+ try { Add-LocalGroupMember -Group 'docker-users' -Member $User -ErrorAction Stop; $added = $true } catch { }+ }+ }+ & wsl.exe --version *> $null+ if ($LASTEXITCODE -ne 0) {+ & wsl.exe --install --no-distribution --web-download *> $null+ & wsl.exe --version *> $null+ }+ $wsl = ($LASTEXITCODE -eq 0)+}+"$code|$added|$wsl" | Set-Content -LiteralPath $Result -Encoding ascii+`;++/** The elevated script's result line, or null when it never wrote one. */+export function parseInstallResult(text: string): { installer: number; addedToGroup: boolean; wslReady: boolean } | null {+ const [code, added, wsl] = text.trim().split("|");+ if (code === undefined || code === "" || !/^-?\d+$/.test(code)) return null;+ return { installer: Number(code), addedToGroup: added?.toLowerCase() === "true", wslReady: wsl?.toLowerCase() === "true" };+}++/** `DOMAIN\\user` for docker-users (the signed-in user, not the approving administrator). */+export function currentUser(env: NodeJS.ProcessEnv = process.env): string {+ const user = env.USERNAME ?? "";+ if (!user) return "";+ return env.USERDOMAIN ? `${env.USERDOMAIN}\\${user}` : user;+}++export const DOCKER_INSTALLER_URL = "https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe";++export function dockerDesktopExe(env: NodeJS.ProcessEnv = process.env): string {+ return join(env.ProgramFiles ?? "C:\\Program Files", "Docker", "Docker", "Docker Desktop.exe");+}++/** Exit codes that mean "done, restart to finish" (Windows Installer's and Docker's). */+const RESTART_CODES = new Set([3010, 1641]);+/** UAC declined: `Start-Process -Verb RunAs` reports ERROR_CANCELLED. */+const CANCELLED = /cancel+ed by the user|ERROR_CANCELLED|\b1223\b/i;++/** Facts the probe reads; the virtualization answer does not change while the app runs. */+export class WindowsRuntime {+ private phase: FixPhase = { kind: "idle" };+ private virtualization: WindowsRuntimeFacts["virtualization"] | null = null;+ /** The installer asked for a restart (until this process ends, which a restart does). */+ private restartAsked = false;++ constructor(+ private readonly sys: WindowsSystem,+ private readonly tempDir: string,+ private readonly now: () => number = Date.now,+ ) {}++ async facts(): Promise<WindowsRuntimeFacts> {+ const exe = dockerDesktopExe();+ const [dockerInstalled, dockerRunning, virtualization, restartPending] = await Promise.all([+ this.sys.exists(exe),+ this.sys.running("Docker Desktop.exe"),+ this.readVirtualization(),+ this.restartAsked ? Promise.resolve(true) : this.readRestartPending(),+ ]);+ return { dockerInstalled, dockerRunning, virtualization, restartPending };+ }++ /** The advice now; a finished start (the engine answered) is the caller's to see. */+ async advice(): Promise<WindowsRuntimeAdvice> {+ const facts = await this.facts();+ // A start that ended with Docker Desktop gone (quit, crashed): offer it again.+ if (this.phase.kind === "starting" && !facts.dockerRunning && this.now() - this.phase.since > 20_000) this.phase = { kind: "idle" };+ return windowsRuntimeAdvice(facts, this.phase, this.now());+ }++ /** The engine answers: forget the fix. */+ settled(): void {+ this.phase = { kind: "idle" };+ }++ /** Runs `action` in the background; the page sees its progress in the options. */+ run(action: RuntimeFixAction): void {+ if (this.phase.kind === "downloading" || this.phase.kind === "installing") return;+ if (action === "start-docker") {+ this.start();+ return;+ }+ void this.install().catch((e: unknown) => {+ this.phase = { kind: "failed", message: installFailedText(e) };+ });+ }++ private start(): void {+ this.sys.launch(dockerDesktopExe());+ this.phase = { kind: "starting", since: this.now() };+ }++ private async install(): Promise<void> {+ this.phase = { kind: "downloading", percent: null };+ const file = join(this.tempDir, "DockerDesktopInstaller.exe");+ await this.sys.download(DOCKER_INSTALLER_URL, file, (percent) => {+ this.phase = { kind: "downloading", percent };+ });+ const sig = await this.sys.powershell(+ `$s = Get-AuthenticodeSignature -LiteralPath '${psQuote(file)}'; "$($s.Status)|$($s.SignerCertificate.Subject)"`,+ 60_000,+ );+ if (!signedByDocker(sig.stdout)) throw new Error(`the downloaded installer isn't signed by Docker (${sig.stdout.trim() || sig.stderr.trim()})`);+ this.phase = { kind: "installing" };+ // One UAC prompt for everything that needs an administrator: Docker's+ // silent install, this user in docker-users (an administrator who isn't+ // this user may approve the prompt) and the WSL package (Windows 11+ // ships only its stub; Docker Desktop can't start without it).+ const script = join(this.tempDir, "install-docker.ps1");+ const result = join(this.tempDir, "install-docker.result");+ await this.sys.writeFile(script, ELEVATED_INSTALL_SCRIPT);+ await this.sys.writeFile(result, "");+ const args = ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, "-Installer", file, "-User", currentUser(), "-Result", result]+ .map((a) => `'${psQuote(a)}'`)+ .join(",");+ const r = await this.sys.powershell(+ `$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList ${args} -Verb RunAs -WindowStyle Hidden -Wait -PassThru; exit $p.ExitCode`,+ 30 * 60_000,+ );+ if (CANCELLED.test(r.stderr) || CANCELLED.test(r.stdout)) throw new Error("cancelled");+ const outcome = parseInstallResult(await this.sys.readFile(result).catch(() => ""));+ if (!outcome) throw new Error(`the installer didn't finish${r.stderr.trim() ? ` (${r.stderr.trim().split(/\r?\n/)[0]})` : ""}`);+ if (outcome.installer !== 0 && !RESTART_CODES.has(outcome.installer)) throw new Error(`the installer exited with code ${outcome.installer}`);+ // A restart finishes it when the installer asks, when Windows has+ // features to turn on (WSL 2), or when this user just joined docker-users.+ if (RESTART_CODES.has(outcome.installer) || outcome.addedToGroup || !outcome.wslReady || (await this.readRestartPending())) {+ this.restartAsked = true;+ this.phase = { kind: "idle" };+ return;+ }+ this.start();+ }++ private async readVirtualization(): Promise<WindowsRuntimeFacts["virtualization"]> {+ if (this.virtualization) return this.virtualization;+ const r = await this.sys+ .powershell(+ "$c = Get-CimInstance Win32_ComputerSystem; $p = Get-CimInstance Win32_Processor | Select-Object -First 1; \"$($c.HypervisorPresent)|$($p.VirtualizationFirmwareEnabled)\"",+ 15_000,+ )+ .catch(() => null);+ this.virtualization = r && r.code === 0 ? parseVirtualization(r.stdout) : "unknown";+ return this.virtualization;+ }++ /** WSL 2 not usable yet although Windows has its parts: they wait for a restart. */+ private async readRestartPending(): Promise<boolean> {+ const r = await this.sys+ .powershell(+ "if (Test-Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending') { 'pending' } else { 'clear' }",+ 15_000,+ )+ .catch(() => null);+ return r?.stdout.trim() === "pending";+ }+}++/** `HypervisorPresent|VirtualizationFirmwareEnabled`. A running hypervisor+ * (Hyper-V, WSL 2) hides the firmware flag, so it counts as on. */+export function parseVirtualization(stdout: string): WindowsRuntimeFacts["virtualization"] {+ const [hypervisor, firmware] = stdout.trim().split("|").map((s) => s.trim().toLowerCase());+ if (hypervisor === "true" || firmware === "true") return "on";+ if (firmware === "false") return "off";+ return "unknown";+}++export function signedByDocker(stdout: string): boolean {+ const [status, subject = ""] = stdout.trim().split("|");+ return status === "Valid" && /\bO="?Docker Inc/i.test(subject);+}++export function installFailedText(e: unknown): string {+ const raw = e instanceof Error ? e.message : String(e);+ if (raw === "cancelled") return "Docker Desktop wasn't installed: the Windows prompt was declined. Try again and choose Yes.";+ return `Couldn't install Docker Desktop: ${raw}. Try again, or install it from https://docs.docker.com/desktop/setup/install/windows-install/.`;+}++const psQuote = (s: string) => s.replace(/'/g, "''");++/* ---- The real system ------------------------------------------------------- */++export function nodeWindowsSystem(fetchImpl: typeof fetch = fetch): WindowsSystem {+ const exec = (file: string, args: string[], timeoutMs: number) =>+ new Promise<{ code: number; stdout: string; stderr: string }>((resolve) => {+ execFile(file, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {+ const code = error ? (typeof (error as { code?: unknown }).code === "number" ? ((error as { code: number }).code) : 1) : 0;+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });+ });+ });+ return {+ exists: async (path) => (await stat(path).catch(() => null)) !== null,+ running: async (image) => {+ const r = await exec("tasklist.exe", ["/FI", `IMAGENAME eq ${image}`, "/FO", "CSV", "/NH"], 10_000);+ return r.stdout.toLowerCase().includes(`"${image.toLowerCase()}"`);+ },+ powershell: (script, timeoutMs) => exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script], timeoutMs),+ async download(url, to, progress) {+ const part = `${to}.part`;+ await mkdir(join(to, ".."), { recursive: true });+ await rm(part, { force: true });+ const res = await fetchImpl(url, { redirect: "follow" });+ if (!res.ok || !res.body) throw new Error(`download failed (HTTP ${res.status})`);+ const total = Number(res.headers.get("content-length")) || 0;+ let got = 0;+ let last = -1;+ // Progress counts in the pipeline itself: a 'data' listener on the+ // source would start it flowing before the file is open and drop chunks.+ const count = new Transform({+ transform(chunk: Buffer, _enc, done) {+ got += chunk.length;+ const pct = total ? Math.floor((got / total) * 100) : null;+ if (pct !== last) {+ last = pct ?? -1;+ progress(pct);+ }+ done(null, chunk);+ },+ });+ await pipeline(Readable.fromWeb(res.body as import("node:stream/web").ReadableStream), count, createWriteStream(part));+ if (total && got !== total) throw new Error(`download incomplete (${got} of ${total} bytes)`);+ await rename(part, to);+ },+ async writeFile(path, text) {+ await mkdir(join(path, ".."), { recursive: true });+ await writeFile(path, text, "utf8");+ },+ readFile: (path) => readFile(path, "utf8"),+ launch(path) {+ const child = spawn(path, [], { detached: true, stdio: "ignore", windowsHide: false });+ child.on("error", () => undefined);+ child.unref();+ },+ };+}diff --git a/apps/cua-spaces-web/src/__tests__/onboarding-first-space.test.tsx b/apps/cua-spaces-web/src/__tests__/onboarding-first-space.test.tsxindex f66ae6bc2b..dec838f67a 100644--- a/apps/cua-spaces-web/src/__tests__/onboarding-first-space.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/onboarding-first-space.test.tsx@@ -57,6 +57,8 @@ describe.skipIf(!wasmBuilt)("the first Space on the last onboarding page (real rawait screen.findByText("Create your first Space");await waitFor(() => expect(card("linux")?.querySelector("[data-first-space-blocked]")).toBeTruthy());for (const os of ["macos", "linux", "windows"]) expect(createOf(os).disabled, os).toBe(true);+ // Another computer can run them: Add a machine is right here.+ expect(await screen.findByRole("button", { name: "Add a machine" })).toBeTruthy();});// CUA-1712: Create sent no `kind`, and the Electron host (Linux, Windows)@@ -77,4 +79,58 @@ describe.skipIf(!wasmBuilt)("the first Space on the last onboarding page (real rexpect(creates[0]!.config.kind).toBe("container");expect(creates[0]!.config.image).toBeTruthy();});++ // A10 (15 Oct clean Windows 11): no Docker Desktop, and nothing to do+ // about it from the app. The host now offers the install; Windows' words.+ it("offers the host's runtime fix under the cards, and runs it", async () => {+ const fixes: unknown[] = [];+ await mountDone(+ (local) => ({+ ...local,+ available: false,+ backends: [],+ error: "Local Spaces on Windows run in Docker Desktop, which isn't installed yet.",+ fix: { action: "install-docker", label: "Install Docker Desktop", note: "About 600 MB.", busy: false, termsUrl: "https://www.docker.com/legal/" },+ }),+ (op, args) => {+ if (op === "spaces.fixRuntime") {+ fixes.push(args);+ return null;+ }+ return undefined;+ },+ );+ await screen.findByText("Create your first Space");+ const install = await screen.findByRole("button", { name: "Install Docker Desktop" });+ expect(screen.getByRole("button", { name: "Docker's terms" })).toBeTruthy();+ for (const os of ["macos", "linux", "windows"]) expect(createOf(os).disabled, os).toBe(true);+ fireEvent.click(install);+ await waitFor(() => expect(fixes).toEqual([{ action: "install-docker" }]));+ });++ it("shows a running fix as busy, with no action to press", async () => {+ await mountDone((local) => ({+ ...local,+ available: false,+ backends: [],+ error: "Docker Desktop is starting.",+ fix: { action: null, label: "Waiting for Docker Desktop…", note: null, busy: true, termsUrl: null },+ }));+ const waiting = (await screen.findByRole("button", { name: "Waiting for Docker Desktop…" })) as HTMLButtonElement;+ expect(waiting.disabled).toBe(true);+ });++ it("offers no fix once a runtime is ready", async () => {+ await mountDone((local) => ({+ ...local,+ backends: ["docker"],+ macosImage: null,+ hostArch: "amd64",+ fix: { action: "start-docker", label: "Start Docker Desktop", note: null, busy: false, termsUrl: null },+ }));+ await screen.findByText("Create your first Space");+ await waitFor(() => expect(createOf("linux").disabled).toBe(false));+ expect(screen.queryByRole("button", { name: "Start Docker Desktop" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Add a machine" })).toBeNull();+ });});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex abedb05925..f7c8ce2de9 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -100,6 +100,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"presence.join": { spaceId: SPACE },"presence.publish": { handle: "p1", x: 0.5, y: 0.5, visible: true },"presence.leave": { handle: "p1" },+ "spaces.fixRuntime": { action: "start-docker" },"about.get": {},"about.set": { channel: "beta" },"about.checkNow": {},@@ -145,6 +146,7 @@ export const DEMO_REFUSES: Partial<Record<OpName, string>> = {"presence.join": "the demo host has no video to draw cursors over","presence.publish": "the demo host has no video to draw cursors over","presence.leave": "the demo host has no video to draw cursors over",+ "spaces.fixRuntime": "the demo host has no local runtime to fix","checklist.get": "the demo host keeps no checklist; the page keeps its own","checklist.send": "the demo host keeps no checklist; the page keeps its own",};diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex 7c9c670c45..1cb6ce1aa8 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -17,6 +17,7 @@ import { STREAM_ARGS } from "../ops/stream";import { RELAY_USAGE_ARGS } from "../ops/relay-usage";import { CHECKLIST_ARGS } from "../ops/checklist";import { PRESENCE_ARGS } from "../ops/presence";+import { RUNTIME_FIX_ARGS } from "../ops/runtime-fix";import type { HostWindow } from "../detect";import { ELECTRON_BRIDGE_CHANNEL } from "../electron-channels";import { OPERATIONS, type OpArgs, type OpName } from "../protocol";@@ -125,6 +126,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {...RELAY_USAGE_ARGS,...CHECKLIST_ARGS,...PRESENCE_ARGS,+ ...RUNTIME_FIX_ARGS,};const unsupportedOn = (op: OpName, host: "webkit" | "tauri") =>diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 0fa95a9b41..f87de91d47 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -40,6 +40,7 @@ import { demoKeyvaultManageHandlers, demoKeyvaultManageState, withDemoCopies, tyimport { demoKeyvaultSetupHandlers, demoKeyvaultSetupState, demoNoVaultOverview, type DemoKeyvaultSetupState } from "./demo/keyvault-setup";import { unsupportedStreamOps } from "../ops/stream";import { unsupportedPresenceOps } from "../ops/presence";+import { unsupportedRuntimeFixOps } from "../ops/runtime-fix";import { unsupportedChecklistOps } from "../ops/checklist";import { demoTeleportHandlers } from "./demo/teleport";import { createDemoSettings } from "./demo/settings";@@ -478,6 +479,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...unsupportedStreamOps("demo"),...unsupportedChecklistOps("demo"),...unsupportedPresenceOps("demo"),+ ...unsupportedRuntimeFixOps("demo"),};return {diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 4979b67320..e8b8ad005e 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -59,6 +59,7 @@ import { STREAM_OPERATIONS } from "../ops/stream";import { RELAY_USAGE_OPERATIONS } from "../ops/relay-usage";import { CHECKLIST_OPERATIONS } from "../ops/checklist";import { PRESENCE_OPERATIONS } from "../ops/presence";+import { RUNTIME_FIX_OPERATIONS } from "../ops/runtime-fix";import { tauriTelemetryOps } from "../ops/telemetry";import { tauriStartupOps } from "../ops/startup";@@ -92,6 +93,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [...RELAY_USAGE_OPERATIONS,...CHECKLIST_OPERATIONS,...PRESENCE_OPERATIONS,+ ...RUNTIME_FIX_OPERATIONS,];/** `persistent_agent_list`'s snake_case agents, as `PersistentAgent`s (as `src/native/persistent.ts` maps them). */diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex d2c0c37b89..35fed745bc 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -61,6 +61,7 @@ import { unsupportedStreamOps, type StreamTicket } from "../ops/stream";import type { RelayUsage } from "../ops/relay-usage";import type { HostChecklistState } from "../ops/checklist";import { unsupportedPresenceOps, type PresenceJoinInfo } from "../ops/presence";+import { unsupportedRuntimeFixOps } from "../ops/runtime-fix";import type { SpaceRow } from "../contracts/spaces";import {isWebkitResponse,@@ -650,6 +651,10 @@ export function createWebkitAdapter("presence.leave": (args: OpArgs<"presence.leave">) => request<null>("presence.leave", { ...args }),}: unsupportedPresenceOps("webkit")),+ // Windows' "Install Docker Desktop": a Mac sets up its runtimes itself.+ ...(electron+ ? { "spaces.fixRuntime": (args: OpArgs<"spaces.fixRuntime">) => request<null>("spaces.fixRuntime", { ...args }) }+ : unsupportedRuntimeFixOps("webkit")),};const onEvent = (detail: WebkitEventDetail) => {diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex 8c78af5486..ccdb0f9ea4 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -1306,6 +1306,16 @@"null"]},+ "fix": {+ "anyOf": [+ {+ "$ref": "#/$defs/RuntimeFix"+ },+ {+ "type": "null"+ }+ ]+ },"hostArch": {"type": "string"},@@ -1968,6 +1978,43 @@"targetEpoch"]},+ "RuntimeFix": {+ "type": "object",+ "properties": {+ "action": {+ "enum": [+ "install-docker",+ "start-docker",+ null+ ]+ },+ "label": {+ "type": "string"+ },+ "note": {+ "type": [+ "string",+ "null"+ ]+ },+ "busy": {+ "type": "boolean"+ },+ "termsUrl": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "action",+ "label",+ "note",+ "busy",+ "termsUrl"+ ]+ },"SessionSnapshot": {"type": "object","properties": {@@ -4745,6 +4792,9 @@"type": "string"}},+ "spaces.fixRuntime": {+ "type": "null"+ },"spaces.list": {"type": "array","items": {diff --git a/apps/cua-spaces-web/src/bridge/contracts/new-space.ts b/apps/cua-spaces-web/src/bridge/contracts/new-space.tsindex c8c3f57415..4193ac9a85 100644--- a/apps/cua-spaces-web/src/bridge/contracts/new-space.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/new-space.ts@@ -49,10 +49,27 @@ export interface LocalStatus {containerImage?: string;macosImage?: string | null;error: string | null;+ /** What the host can do about `error` (Windows: install or start Docker Desktop). */+ fix?: RuntimeFix | null;hostArch?: string;storage?: LocalStorage | null;}+/** `spaces.fixRuntime`'s actions. */+export type RuntimeFixAction = "install-docker" | "start-docker";++/** A step the host offers next to "no local runtime" (`LocalStatus.fix`). */+export interface RuntimeFix {+ /** What the button runs; null while something runs, or when only the person can act. */+ action: RuntimeFixAction | null;+ label: string;+ note: string | null;+ /** Something runs now: read the options again until it settles. */+ busy: boolean;+ /** Terms the action accepts, linked beside the note. */+ termsUrl: string | null;+}+/** A runtime's GPU option (`gpu_support`). */export interface GpuChoice {runtime: string;diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex b66bc1c8bb..fc9cdca586 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -45,6 +45,7 @@ import type {ConnectedCloud,GpuChoice,LocalStatus,+ RuntimeFix,LocalStorage,NewSpaceOptions,StorageVolume,@@ -417,6 +418,12 @@ const LocalStatusShape = ref(containerImage: opt(str),macosImage: optNull(str),error: nullable(str),+ fix: optNull(+ ref(+ "RuntimeFix",+ obj<RuntimeFix>()({ action: nullable(oneOf("install-docker", "start-docker")), label: str, note: nullable(str), busy: bool, termsUrl: nullable(str) }),+ ),+ ),hostArch: opt(str),storage: optNull(LocalStorageShape),}),@@ -830,6 +837,7 @@ export const OP_SHAPES: Record<OpName, Schema> = {}),"presence.publish": nul,"presence.leave": nul,+ "spaces.fixRuntime": nul,"about.get": AboutShape,"about.set": AboutShape,diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 06e2164ca3..b0eea97b7d 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -42,6 +42,7 @@ import { STREAM_COVERAGE } from "./ops/stream";import { RELAY_USAGE_COVERAGE } from "./ops/relay-usage";import { CHECKLIST_COVERAGE } from "./ops/checklist";import { PRESENCE_COVERAGE } from "./ops/presence";+import { RUNTIME_FIX_COVERAGE } from "./ops/runtime-fix";import { TELEMETRY_COVERAGE } from "./ops/telemetry";import { STARTUP_COVERAGE } from "./ops/startup";@@ -165,6 +166,7 @@ export const HOST_COVERAGE = {...RELAY_USAGE_COVERAGE,...CHECKLIST_COVERAGE,...PRESENCE_COVERAGE,+ ...RUNTIME_FIX_COVERAGE,} as const satisfies Record<OpName, OpCoverage>;/**diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.tsindex a5c29efdbe..fbe99b30e3 100644--- a/apps/cua-spaces-web/src/bridge/index.ts+++ b/apps/cua-spaces-web/src/bridge/index.ts@@ -93,7 +93,17 @@ export type * from "./contracts/devices";export type * from "./contracts/notifications";export * from "./settings-hooks";export { hasNotch, passedSteps, signInCodeText, type SavedOnboarding } from "./onboarding";-export { useConnectCloud, useFirstSpaceOffers, useNewSpaceRequests, useNewSpaceWizard, type ConnectCloudHook, type FirstSpaceHook, type NewSpaceWizardHook } from "./new-space-hooks";+export {+ useConnectCloud,+ useFirstSpaceOffers,+ useNewSpaceRequests,+ useNewSpaceWizard,+ useRuntimeFix,+ type ConnectCloudHook,+ type FirstSpaceHook,+ type NewSpaceWizardHook,+ type RuntimeFixHook,+} from "./new-space-hooks";export { createFailedText, emptyHome, type EmptyHome, type EmptyTile, type FirstSpaceOffer } from "./new-space";export type * from "./contracts/volume";export * from "./volume";diff --git a/apps/cua-spaces-web/src/bridge/new-space-hooks.ts b/apps/cua-spaces-web/src/bridge/new-space-hooks.tsindex a2167b09de..172a91f078 100644--- a/apps/cua-spaces-web/src/bridge/new-space-hooks.ts+++ b/apps/cua-spaces-web/src/bridge/new-space-hooks.ts@@ -7,7 +7,7 @@ import { useContext, useEffect, useState, useSyncExternalStore } from "react";import { isUnsupported } from "./adapter";import { BridgeContext } from "./BridgeProvider";import type { CoreClient } from "./core";-import type { CloudConnectAction, CloudConnectView, RuntimeSwitch, WizardAction, WizardEnv, WizardView } from "./contracts/new-space";+import type { CloudConnectAction, CloudConnectView, RuntimeFix, RuntimeSwitch, WizardAction, WizardEnv, WizardView } from "./contracts/new-space";import type { Space, SpaceOs } from "./contracts/spaces";import { useMachines, useSession, useSettings, useSpaces } from "./hooks";import { newPendingId } from "./store";@@ -291,3 +291,55 @@ export function useConnectCloud(): ConnectCloudHook {},};}++/* ---- Windows: the runtime fix ("Install Docker Desktop") ------------------ */++/** How often the options are read again while a fix runs, and for how long after one started. */+export const RUNTIME_FIX_POLL_MS = 3_000;+export const RUNTIME_FIX_FOLLOW_MS = 15 * 60_000;++export interface RuntimeFixHook {+ /** What the host offers beside "no local runtime" (null when it offers nothing, or a runtime is ready). */+ fix: RuntimeFix | null;+ /** Starts the fix's action; the options are read again until it settles. */+ run(): Promise<void>;+ /** Why the host refused to start it. */+ error: string | null;+}++/**+ * The host's fix for a machine with no local runtime (Windows: install or+ * start Docker Desktop). While it runs, or for a while after it started,+ * the options are read again so the reason, the button and the wizard's+ * Continue follow the install and the engine's start.+ */+export function useRuntimeFix(): RuntimeFixHook {+ const ctx = useContext(BridgeContext)!;+ const s = useSyncExternalStore(subscribe, read, read);+ const local = s.options?.local;+ const fix = local && !local.available ? (local.fix ?? null) : null;+ const [startedAt, setStartedAt] = useState<number | null>(null);+ const [error, setError] = useState<string | null>(null);+ const following = Boolean(fix?.busy) || (startedAt !== null && Date.now() - startedAt < RUNTIME_FIX_FOLLOW_MS && !local?.available);+ useEffect(() => {+ if (!following) return;+ const timer = setInterval(() => void ctx.ready.then(loadHostData), RUNTIME_FIX_POLL_MS);+ return () => clearInterval(timer);+ }, [following, ctx.ready]);+ return {+ fix,+ error,+ async run() {+ const action = fix?.action;+ if (!action || !ctx.adapter) return;+ setError(null);+ try {+ await ctx.adapter.call("spaces.fixRuntime", { action });+ setStartedAt(Date.now());+ await ctx.ready.then(loadHostData);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ }+ },+ };+}diff --git a/apps/cua-spaces-web/src/bridge/ops/runtime-fix.ts b/apps/cua-spaces-web/src/bridge/ops/runtime-fix.tsnew file mode 100644index 0000000000..1a9d1706f4--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/runtime-fix.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * New Space's runtime fix on Windows: local Spaces run in Docker Desktop,+ * which a clean PC doesn't have. The Electron host says what is missing in+ * `spaces.createOptions` (`local.error`, and `local.fix` for what it can do)+ * and runs the fix in the background; the page reads the options again+ * until the engine answers.+ *+ * | Operation | Electron | SwiftUI | Tauri |+ * |---|---|---|---|+ * | `spaces.fixRuntime {action}` | the host method `spaces.fixRuntime` (`src/bridge/spaces.ts`) | unsupported: a Mac sets up its built-in runtimes itself | unsupported: the Tauri app isn't shipped on Windows |+ */++import { UnsupportedOperationError, type BridgeMode } from "../adapter";+import type { OpCoverage } from "../coverage";+import type { RuntimeFixAction } from "../contracts/new-space";++export interface RuntimeFixOps {+ /** Starts `action` ("install-docker", "start-docker"); it runs on in the host. */+ "spaces.fixRuntime": { args: { action: RuntimeFixAction }; result: null };+}++export const RUNTIME_FIX_OPERATIONS = ["spaces.fixRuntime"] as const satisfies readonly (keyof RuntimeFixOps)[];++export const RUNTIME_FIX_COVERAGE = {+ "spaces.fixRuntime": {+ webkit: { methods: [] },+ electron: { methods: ["spaces.fixRuntime"] },+ tauri: [],+ unsupported: {+ webkit: "a Mac sets up Lume and the built-in Linux runtime itself on the first create",+ tauri: "the Tauri app isn't shipped on Windows (the Electron app is)",+ },+ },+} as const satisfies Record<keyof RuntimeFixOps, OpCoverage>;++/** Hosts with no runtime fix. */+export function unsupportedRuntimeFixOps(mode: BridgeMode) {+ return {+ "spaces.fixRuntime": (() => Promise.reject(new UnsupportedOperationError(mode, "spaces.fixRuntime"))) as () => Promise<null>,+ };+}++/** Arguments that take it down its usual path (coverage tests). */+export const RUNTIME_FIX_ARGS = {+ "spaces.fixRuntime": { action: "start-docker" as RuntimeFixAction },+};diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex 836cbe6e7a..5ea913e9ad 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -47,6 +47,7 @@ import { STREAM_OPERATIONS, type StreamOps } from "./ops/stream";import { RELAY_USAGE_OPERATIONS, type RelayUsageOps } from "./ops/relay-usage";import { CHECKLIST_OPERATIONS, type ChecklistOps } from "./ops/checklist";import { PRESENCE_OPERATIONS, type PresenceOps } from "./ops/presence";+import { RUNTIME_FIX_OPERATIONS, type RuntimeFixOps } from "./ops/runtime-fix";import type { TelemetryOps } from "./ops/telemetry";import { STARTUP_EVENTS, STARTUP_OPERATIONS, type StartupHostEvent, type StartupOps } from "./ops/startup";@@ -186,7 +187,8 @@ export interface HostOperationsStreamOps,RelayUsageOps,ChecklistOps,- PresenceOps {+ PresenceOps,+ RuntimeFixOps {"spaces.list": { args: Record<string, never>; result: SpaceRow[] };/** `os`: the plan's OS, for a host that draws its own pending row (the SwiftUI app's notch). */"spaces.create": { args: { config: SpaceCreateConfig; pendingId: string; os?: SpaceOs }; result: SpaceRow };@@ -290,6 +292,7 @@ export const OPERATIONS = [...RELAY_USAGE_OPERATIONS,...CHECKLIST_OPERATIONS,...PRESENCE_OPERATIONS,+ ...RUNTIME_FIX_OPERATIONS,...SETTINGS_OPERATIONS,...NOTIFICATIONS_OPERATIONS,"telemetry.track",diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 7d81419f4a..31aef655ed 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -161,7 +161,7 @@ export type WebkitMethod = (typeof WEBKIT_METHODS)[number];* `onboarding.complete`); the Mac app draws video and its first run* natively. It also joins presence for the video the page draws* (`presence.*`, `ops/presence.ts`). */-export const ELECTRON_HOST_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream", "presence.join", "presence.publish", "presence.leave"] as const;+export const ELECTRON_HOST_METHODS = ["onboarding.get", "onboarding.complete", "spaces.openStream", "presence.join", "presence.publish", "presence.leave", "spaces.fixRuntime"] as const;/** `onboarding.get` and `onboarding.complete`'s answer: whether the first run finished, and as what. */export interface WkOnboarding {diff --git a/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsx b/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsxindex a7210f0d3d..6ddd6bc9b2 100644--- a/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsx+++ b/apps/cua-spaces-web/src/components/new-space/new-space-dialog.tsx@@ -16,6 +16,7 @@ import { useCreateFromWizard } from "@/hooks/use-new-space";import { ConnectCloudDialog } from "./connect-cloud-dialog";import { ImageField } from "./image-field";import { MenuSelect } from "./menu-select";+import { RuntimeFixRow } from "./runtime-fix";/*** New Space: System, Resources, Options, Summary, as the native app's sheet.@@ -358,6 +359,7 @@ function SystemRow({ field: f, v }: { field: WizardField; v: WizardView }) {) : (error)}+ {error && !v.runtimeSwitch && v.plan.placement === "local" ? <RuntimeFixRow /> : null}{v.placementHint ? <Note data-placement-hint="">{v.placementHint}</Note> : null}</>}diff --git a/apps/cua-spaces-web/src/components/new-space/runtime-fix.tsx b/apps/cua-spaces-web/src/components/new-space/runtime-fix.tsxnew file mode 100644index 0000000000..bcea008b08--- /dev/null+++ b/apps/cua-spaces-web/src/components/new-space/runtime-fix.tsx@@ -0,0 +1,49 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { LoaderCircleIcon } from "lucide-react";++import { useRuntimeFix, useSession } from "@/bridge";+import { Button } from "@/components/ui/button";+import { toastError } from "@/components/ui/toast";++/**+ * What the host can do about "no local runtime" (Windows: install or start+ * Docker Desktop), under the reason New Space and onboarding show. Nothing+ * when the host offers no fix.+ */+export function RuntimeFixRow({ className }: { className?: string }) {+ const { fix, run, error } = useRuntimeFix();+ const { openExternal } = useSession();+ if (!fix) return null;+ return (+ <div data-runtime-fix={fix.action ?? "busy"} className={className ?? "mt-2 flex flex-col items-start gap-1.5"}>+ <Button size="sm" variant={fix.busy ? "ghost" : "outline"} disabled={fix.busy || !fix.action} onClick={() => void run()}>+ {fix.busy ? <LoaderCircleIcon className="size-3.5 animate-spin" /> : null}+ {fix.label}+ </Button>+ {fix.note ? (+ <p className="text-xs text-muted-foreground">+ {fix.note}+ {fix.termsUrl ? (+ <>+ {" "}+ <button+ type="button"+ className="text-brand-strong hover:underline"+ onClick={() => void openExternal(fix.termsUrl!).catch(toastError("Couldn't open the page"))}+ >+ Docker's terms+ </button>+ </>+ ) : null}+ </p>+ ) : null}+ {error ? (+ <p role="alert" className="text-xs text-destructive">+ {error}+ </p>+ ) : null}+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/routes/onboarding/index.tsx b/apps/cua-spaces-web/src/routes/onboarding/index.tsxindex 7cda2e2a70..4287720c6a 100644--- a/apps/cua-spaces-web/src/routes/onboarding/index.tsx+++ b/apps/cua-spaces-web/src/routes/onboarding/index.tsx@@ -4,7 +4,19 @@import { createFileRoute, useNavigate } from "@tanstack/react-router";import { lazy, Suspense, useEffect, useState, type ReactNode } from "react";-import { useFirstSpaceOffers, useOnboarding, useOnboardingVolume, useSession, useSpaces, useThisMachine, type OnboardingHook, type OnboardingView, type SandboxImage } from "@/bridge";+import {+ useFirstSpaceOffers,+ useMachines,+ useOnboarding,+ useOnboardingVolume,+ useSession,+ useSpaces,+ useThisMachine,+ type OnboardingHook,+ type OnboardingView,+ type SandboxImage,+} from "@/bridge";+import { AddMachineDialog } from "@/components/add-machine-dialog";import { CuaLogo } from "@/components/cua-logo";import { useAgentsStep, type AgentsStep } from "@/components/volume/use-agents-step";import { OsIcon } from "@/components/os-icon";@@ -18,6 +30,7 @@ import { Checkbox } from "@/components/ui/checkbox";import { Switch } from "@/components/ui/switch";import { toast } from "@/components/ui/toast";import { cn } from "@/lib/utils";+import { RuntimeFixRow } from "@/components/new-space/runtime-fix";export const Route = createFileRoute("/onboarding/")({ component: OnboardingPage });@@ -379,10 +392,29 @@ function FirstSpace({ images }: { images: SandboxImage[] }) {);})}</ul>+ {/* Windows without Docker Desktop: install or start it from here, and the cards follow. */}+ {images.some((image) => first.blockedReason(image.ref) !== null) ? <RuntimeFixRow /> : null}+ {/* Nothing runs here (no runtime, virtualization off): another computer can run them. */}+ {first.known && images.length > 0 && images.every((image) => first.blockedReason(image.ref) !== null) ? <AnotherComputer /> : null}</section>);}+/** "Or run Spaces on another computer": Add a machine, from the last page. */+function AnotherComputer() {+ const [adding, setAdding] = useState(false);+ const { setupGuide } = useMachines();+ return (+ <div data-first-space-elsewhere="" className="mt-3 flex items-center gap-3">+ <p className="text-xs text-muted-foreground">Or run Spaces on another computer you use: add it here and create Spaces on it from this one.</p>+ <Button variant="outline" size="sm" onClick={() => setAdding(true)}>+ Add a machine+ </Button>+ <AddMachineDialog open={adding} onOpenChange={setAdding} guide={setupGuide} />+ </div>+ );+}+/* ---- Footer ---------------------------------------------------------------------- */function Footer({ flow, view, agents, onFinish }: { flow: OnboardingHook; view: OnboardingView; agents: AgentsStep; onFinish: () => void }) {