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(spaces): Linux New Space finds Docker right after install without a reboot (CUA-1763) (#5301)
Francesco Bonacci11e802ad8e5f
diff --git a/apps/cua-spaces-desktop/src/bridge/spaces.ts b/apps/cua-spaces-desktop/src/bridge/spaces.tsindex 1894a5ebe3..e8c824bbd2 100644--- a/apps/cua-spaces-desktop/src/bridge/spaces.ts+++ b/apps/cua-spaces-desktop/src/bridge/spaces.ts@@ -121,8 +121,8 @@ export function spacesMethods(ctx: BridgeContext): Handlers {},"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");+ if (action !== "install-docker" && action !== "start-docker" && action !== "restart-app") throw Failure.badArgs("action: install-docker | start-docker | restart-app");+ if (!model.windowsRuntime && !model.linuxRuntime) throw Failure.unsupported("no runtime fix on this system");model.fixRuntime(action);return null;},diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.tsindex 12dbe438cf..9ffc0d1aa1 100644--- a/apps/cua-spaces-desktop/src/main.ts+++ b/apps/cua-spaces-desktop/src/main.ts@@ -33,6 +33,7 @@ import { initTheme, setThemeSource } from "./theme";import { closesToTray, installTray, isQuitting } from "./tray";import { countsVideo, startVideoBench, videoBenchEnv } from "./video-bench";import { createViewerWindows } from "./viewer";+import { LinuxRuntime, nodeLinuxSystem } from "./model/linux-runtime";import { applyThemeToWindow, createMainWindow, handleOverlayDim, handleViewerKeyboard, setWindowBackground } from "./window";import { WindowDropTargets, windowNumberOf, type DropWindow } from "./window-drop";@@ -140,7 +141,7 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu// first launch after taking over its settings is no update unless the build changed.const build = appBuild({ platform: process.platform, packaged: app.isPackaged, resourcesPath: process.resourcesPath, read: (f) => readFileSync(f, "utf8") });const refresh = recordLaunch(native, core.settings, app.getVersion(), build, readOnboardingCompleted(core.onboarding) ?? false);- const env = makeModel({ native, nativeDir: dir, userData: app.getPath("userData"), version: app.getVersion(), openUrl });+ const env = makeModel({ native, nativeDir: dir, userData: app.getPath("userData"), version: app.getVersion(), openUrl, relaunch: relaunchApp });const pip = createPipWindows();app.on("will-quit", () => {pip.closeAll();@@ -251,6 +252,12 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcureturn { env, bridge, background };}+/** Starts `spec` once this app has exited, and exits (Linux: this app again under `sg docker`, CUA-1763). */+function relaunchApp(spec: { execPath: string; args: string[] }): void {+ app.relaunch(spec);+ app.exit(0);+}+if (!app.requestSingleInstanceLock()) {app.quit();} else {@@ -302,6 +309,8 @@ if (!app.requestSingleInstanceLock()) {app.on("second-instance", showMain);app.whenReady().then(async () => {+ // Docker was installed and the user added to its group after this session began: start again with the group, so no logout or reboot is needed.+ if (process.platform === "linux" && !E2E_DEMO && (await new LinuxRuntime(nodeLinuxSystem(relaunchApp)).relaunchIfNeeded().catch(() => false))) return;migrateSwiftApp();initTheme();installMenu({ newSpace, settings: openSettings, gettingStarted });diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.tsindex d0fb806d42..e363a791bb 100644--- a/apps/cua-spaces-desktop/src/model/app-model.ts+++ b/apps/cua-spaces-desktop/src/model/app-model.ts@@ -47,6 +47,7 @@ import type { StartupModel } from "./startup";import { SignInRuns } from "./sign-in";import { SpaceThumbnails } from "./thumbnails";import { noLocalRuntimeReason } from "./local-runtime";+import type { LinuxRuntime } from "./linux-runtime";import type { RuntimeFix, RuntimeFixAction, WindowsRuntime, WindowsRuntimeAdvice } from "./windows-runtime";import { TimeoutError, sleep, withTimeout } from "./time";@@ -81,6 +82,8 @@ export interface AppModelDeps {hostOs?: AppSpaceOs;/** What New Space offers when Windows has no local runtime (null elsewhere). */windowsRuntime?: WindowsRuntime | null;+ /** Linux: restarts the app under the docker group when a new install needs it (null elsewhere). */+ linuxRuntime?: LinuxRuntime | null;}/** The create the daemon never took. */@@ -156,9 +159,10 @@ 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). */+ /** Windows or Linux without a usable local runtime: why, and the fix New Space offers (null when one is ready). */runtimeAdvice: WindowsRuntimeAdvice | null = null;readonly windowsRuntime: WindowsRuntime | null;+ readonly linuxRuntime: LinuxRuntime | 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). */@@ -220,6 +224,7 @@ export class AppModel {this.checklist.onChange = () => this.changed("checklist");this.settingsPath = d.settingsPath;this.windowsRuntime = d.windowsRuntime ?? null;+ this.linuxRuntime = d.linuxRuntime ?? null;this.servicesInNow = d.servicesIn;this.maxCpus = Math.max(2, Math.min(16, d.cpus));this.settings = d.native.appSettingsLoad(d.settingsPath);@@ -560,14 +565,15 @@ export class AppModel {/** Windows: what is missing for local Spaces and what the app can do about it. */private async readRuntimeAdvice(runtimes: LocalRuntimes | null): Promise<void> {+ if (!runtimes) return;const w = this.windowsRuntime;- if (!w || !runtimes) return;if (runtimes.ready.length > 0) {- w.settled();+ w?.settled();this.runtimeAdvice = null;return;}- this.runtimeAdvice = await w.advice().catch(() => null);+ if (w) this.runtimeAdvice = await w.advice().catch(() => null);+ else if (this.linuxRuntime) this.runtimeAdvice = await this.linuxRuntime.advice(runtimes.details.get("container")).catch(() => null);}/** The fix New Space shows beside the reason (Windows only). */@@ -577,6 +583,11 @@ export class AppModel {/** Runs a New Space fix ("Install Docker Desktop"); the page reads the options again to follow it. */fixRuntime(action: RuntimeFixAction): void {+ if (action === "restart-app") {+ if (!this.linuxRuntime) throw new Error("no runtime fix on this system");+ this.linuxRuntime.run(action);+ return;+ }if (!this.windowsRuntime) throw new Error("no runtime fix on this system");this.windowsRuntime.run(action);}diff --git a/apps/cua-spaces-desktop/src/model/daemon.ts b/apps/cua-spaces-desktop/src/model/daemon.tsindex 89eb648485..fc19b48337 100644--- a/apps/cua-spaces-desktop/src/model/daemon.ts+++ b/apps/cua-spaces-desktop/src/model/daemon.ts@@ -18,6 +18,7 @@ import { execFile, spawn } from "node:child_process";import { readFileSync, readlinkSync, realpathSync } from "node:fs";import * as os from "node:os";import * as path from "node:path";+import { daemonLacksDockerGroup } from "./linux-runtime";import { sleep } from "./time";/** `CUA_KEYCHAIN_NONINTERACTIVE` (cua-auth's `KEYCHAIN_NONINTERACTIVE_ENV`). */@@ -196,6 +197,7 @@ export class DaemonSupervisor {* starts it again (`CUA_DAEMON_KEEP`, here and for the SDK in this process).*/async start(timeoutMs = 60_000): Promise<string | null> {+ await this.replaceDaemonWithoutDockerGroup();const before = await this.stranger();const error = await this.run(["daemon", "start"], timeoutMs);// Replaced: another daemon is named now, or that one is gone.@@ -208,6 +210,24 @@ export class DaemonSupervisor {return error;}+ /**+ * Linux (CUA-1763): a daemon of this bundle that started before the user+ * joined the `docker` group never gets it (a lingering session keeps the+ * old groups), so it cannot reach Docker while this app can. Stops it+ * here; the start that follows runs a new one with the group.+ */+ private async replaceDaemonWithoutDockerGroup(): Promise<void> {+ if (this.platform !== "linux") return;+ for (const pid of daemonPids(this.cuaHome)) {+ if (!(await this.isOwn(pid))) continue;+ if (await daemonLacksDockerGroup(pid)) {+ console.log(`[cua-spaces] the cua daemon (pid ${pid}) started without the docker group this app has; replacing it`);+ await this.run(["daemon", "stop"], 15_000);+ await DaemonSupervisor.stop(pid);+ }+ }+ }+/** Stops this app's daemon (bounded), kills one of this bundle that still starts or no longer answers, then starts it. */async restart(timeoutMs = 30_000): Promise<string | null> {await this.run(["daemon", "stop"], 15_000);diff --git a/apps/cua-spaces-desktop/src/model/environment.ts b/apps/cua-spaces-desktop/src/model/environment.tsindex b311cf0b06..af4d023ee6 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 { LinuxRuntime, nodeLinuxSystem, type RelaunchSpec } from "./linux-runtime";import { WindowsRuntime, nodeWindowsSystem } from "./windows-runtime";/** Whether the first run finished (`onboarding.json`'s `completed`); null when unknown. */@@ -52,6 +53,8 @@ export interface EnvironmentOptions {openUrl: (url: string) => Promise<boolean>;env?: NodeJS.ProcessEnv;platform?: NodeJS.Platform;+ /** Linux: starts this app again as given and quits (Electron's `app.relaunch` and `app.exit`); without it no restart fix is offered. */+ relaunch?: (spec: RelaunchSpec) => void;}export interface Environment {@@ -129,6 +132,7 @@ export function makeModel(o: EnvironmentOptions): Environment {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,+ linuxRuntime: platform === "linux" && o.relaunch ? new LinuxRuntime(nodeLinuxSystem(o.relaunch, env), env) : null,});// Signed out is null (setup signs in first); anything else is the error itself.diff --git a/apps/cua-spaces-desktop/src/model/linux-runtime.test.ts b/apps/cua-spaces-desktop/src/model/linux-runtime.test.tsnew file mode 100644index 0000000000..26deece45b--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/linux-runtime.test.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it, vi } from "vitest";+import {+ LinuxRuntime,+ SG_DOCKER_ENV,+ daemonLacksDockerGroup,+ linuxRuntimeAdvice,+ needsGroupRefresh,+ parseGroupEntry,+ sgRelaunch,+ statusGids,+ type LinuxSystem,+} from "./linux-runtime";++const STATUS_OLD = "Name:\tcua\nGid:\t1000\t1000\t1000\t1000\nGroups:\t4 24 27 1000 \n";+const STATUS_NEW = "Name:\tcua\nGid:\t1000\t1000\t1000\t1000\nGroups:\t4 24 27 118 1000 \n";++function system(over: { entry?: string | null; status?: string; socketExists?: () => boolean; hasSg?: () => boolean } = {}): LinuxSystem & { relaunch: ReturnType<typeof vi.fn> } {+ return {+ user: "azureuser",+ groupEntry: async () => (over.entry === undefined ? "docker:x:118:azureuser" : over.entry),+ status: async () => over.status ?? STATUS_OLD,+ socketExists: over.socketExists ?? (() => true),+ hasSg: over.hasSg ?? (() => true),+ relaunch: vi.fn(),+ } as LinuxSystem & { relaunch: ReturnType<typeof vi.fn> };+}++describe("group facts", () => {+ it("reads the docker group's id and members", () => {+ expect(parseGroupEntry("docker:x:118:alice,azureuser", "azureuser")).toEqual({ gid: 118, member: true });+ expect(parseGroupEntry("docker:x:118:alice", "azureuser")).toEqual({ gid: 118, member: false });+ expect(parseGroupEntry("docker:x:118:", "azureuser").member).toBe(false);+ expect(parseGroupEntry(null, "azureuser")).toEqual({ gid: null, member: false });+ expect(parseGroupEntry("garbage", "azureuser")).toEqual({ gid: null, member: false });+ });++ it("reads every group id a process has", () => {+ expect(statusGids(STATUS_OLD).sort((a, b) => a - b)).toEqual([4, 24, 27, 1000]);+ expect(statusGids(STATUS_NEW)).toContain(118);+ expect(statusGids("")).toEqual([]);+ });++ it("needs a refresh only for a member whose process predates the group", () => {+ expect(needsGroupRefresh({ gid: 118, member: true, sessionHas: false, socket: true })).toBe(true);+ expect(needsGroupRefresh({ gid: 118, member: true, sessionHas: true, socket: true })).toBe(false);+ expect(needsGroupRefresh({ gid: 118, member: false, sessionHas: false, socket: true })).toBe(false);+ expect(needsGroupRefresh({ gid: null, member: false, sessionHas: false, socket: false })).toBe(false);+ });+});++describe("linuxRuntimeAdvice", () => {+ const stale = { gid: 118, member: true, sessionHas: false, socket: true };+ it("offers a restart for a member whose session predates the group (CUA-1763)", () => {+ const a = linuxRuntimeAdvice(stale, "permission denied on unix:///var/run/docker.sock: add yourself", true, false);+ expect(a?.fix).toMatchObject({ action: "restart-app", label: "Restart Cua Spaces", busy: false });+ expect(a?.reason).toMatch(/no logout or reboot/);+ });++ it("offers the restart even when the doctor's words did not say permission denied", () => {+ expect(linuxRuntimeAdvice(stale, "container engine did not answer", true, false)?.fix?.action).toBe("restart-app");+ });++ it("says to log out when the restart already ran, or there is no sg", () => {+ for (const [can, again] of [[true, true], [false, false]] as const) {+ const a = linuxRuntimeAdvice(stale, "permission denied", can, again);+ expect(a?.fix).toBeNull();+ expect(a?.reason).toMatch(/Log out/);+ }+ });++ it("names the one command for a user who is not in the group", () => {+ const a = linuxRuntimeAdvice({ gid: 118, member: false, sessionHas: false, socket: true }, "permission denied on x", true, false);+ expect(a?.fix).toBeNull();+ expect(a?.reason).toContain("sudo usermod -aG docker $USER");+ });++ it("stays out of the way when Docker is simply not installed or not running", () => {+ expect(linuxRuntimeAdvice({ gid: null, member: false, sessionHas: false, socket: false }, "no Docker-API socket found", true, false)).toBeNull();+ expect(linuxRuntimeAdvice({ gid: 118, member: true, sessionHas: true, socket: true }, "container engine at x is not running", true, false)).toBeNull();+ });+});++describe("sgRelaunch", () => {+ it("runs the app under the docker group with the marker set, quoting every part", () => {+ const r = sgRelaunch("/opt/Cua Spaces/cua-spaces", ["--no-sandbox", "it's"], "/usr/bin/sg");+ expect(r.execPath).toBe("/usr/bin/sg");+ expect(r.args.slice(0, 2)).toEqual(["docker", "-c"]);+ expect(r.args[2]).toBe(`${SG_DOCKER_ENV}=1 exec '/opt/Cua Spaces/cua-spaces' '--no-sandbox' 'it'\\''s'`);+ });+});++describe("LinuxRuntime", () => {+ it("starts again under the group at launch for a stale session with Docker installed", async () => {+ const sys = system();+ expect(await new LinuxRuntime(sys, {}).relaunchIfNeeded()).toBe(true);+ expect(sys.relaunch).toHaveBeenCalledTimes(1);+ });++ it("does not relaunch when the session has the group, Docker is absent, the user is not a member, or it already did", async () => {+ for (const sys of [system({ status: STATUS_NEW }), system({ socketExists: () => false }), system({ entry: "docker:x:118:other" }), system({ entry: null }), system({ hasSg: () => false })]) {+ expect(await new LinuxRuntime(sys, {}).relaunchIfNeeded()).toBe(false);+ expect(sys.relaunch).not.toHaveBeenCalled();+ }+ const sys = system();+ expect(await new LinuxRuntime(sys, { [SG_DOCKER_ENV]: "1" }).relaunchIfNeeded()).toBe(false);+ expect(sys.relaunch).not.toHaveBeenCalled();+ });++ it("advises and runs the restart button once", async () => {+ const sys = system();+ const r = new LinuxRuntime(sys, {});+ expect((await r.advice("permission denied"))?.fix?.action).toBe("restart-app");+ r.run("restart-app");+ r.run("restart-app");+ expect(sys.relaunch).toHaveBeenCalledTimes(1);+ });+});++describe("daemonLacksDockerGroup", () => {+ it("is unknown-safe: false when a status file cannot be read", async () => {+ expect(await daemonLacksDockerGroup(999999, async () => Promise.reject(new Error("gone")))).toBe(false);+ });+});diff --git a/apps/cua-spaces-desktop/src/model/linux-runtime.ts b/apps/cua-spaces-desktop/src/model/linux-runtime.tsnew file mode 100644index 0000000000..33e4faf370--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/linux-runtime.ts@@ -0,0 +1,217 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * Local Spaces on Linux run in Docker (or Podman). A new user installs Docker+ * after Cua Spaces and adds themselves to the `docker` group, and the app+ * then kept saying "No local runtime found" until a reboot (CUA-1763): group+ * membership is read once, when a login session starts, and every process+ * started from that session (the app, the cua daemon that outlives it)+ * keeps the groups it started with. A logout does not help while a+ * lingering user manager (`loginctl enable-linger`) or a disconnected xrdp+ * session keeps the old processes alive.+ *+ * The standard answer is `sg docker -c <command>` (the same as `newgrp`):+ * any member of the group can start a process that has the group, without a+ * password. So the app+ *+ * - tells "in the docker group, but this session predates it" from "not in+ * the group at all" (`getent group docker` against the groups the process+ * really has, in `/proc/self/status`);+ * - starts itself again under `sg docker` by itself at launch, and from a+ * "Restart Cua Spaces" button while it runs (Docker was installed while it+ * was open); the relaunched app replaces a cua daemon that started+ * without the group (see `DaemonSupervisor.start`);+ * - for a user who is not in the group, says the one command to run.+ *+ * Everything that touches the system goes through {@link LinuxSystem}, so+ * the decisions are tested without Linux.+ */++import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import { readFile } from "node:fs/promises";+import * as os from "node:os";+import type { RuntimeFix } from "./windows-runtime";++/** What the page's fix button runs on Linux (`spaces.fixRuntime {action}`). */+export type LinuxFixAction = "restart-app";++/** Set in the relaunched app, so it never relaunches itself twice. */+export const SG_DOCKER_ENV = "CUA_SPACES_SG_DOCKER";++export interface DockerGroupFacts {+ /** The `docker` group's id (null: no such group, Docker Engine is not installed). */+ gid: number | null;+ /** The user is listed in the group (the group database, which a new session reads). */+ member: boolean;+ /** This process has the group (it started in a session that already had it, or under `sg`). */+ sessionHas: boolean;+ /** `/var/run/docker.sock` exists (Docker Engine is installed and its service was started). */+ socket: boolean;+}++/** The `docker` group's id and whether `user` is in it, from a `getent group docker` line (`docker:x:999:alice,bob`). */+export function parseGroupEntry(line: string | null, user: string): { gid: number | null; member: boolean } {+ const parts = (line ?? "").trim().split(":");+ const gid = Number.parseInt(parts[2] ?? "", 10);+ if (parts.length < 3 || !Number.isInteger(gid)) return { gid: null, member: false };+ const members = (parts[3] ?? "").split(",").map((m) => m.trim());+ return { gid, member: members.includes(user) };+}++/** Every group id a process has, from its `/proc/<pid>/status` (the Gid line and the supplementary Groups line). */+export function statusGids(status: string): number[] {+ const out = new Set<number>();+ for (const line of status.split("\n")) {+ const m = /^(Gid|Groups):\s*(.*)$/.exec(line);+ if (!m) continue;+ for (const n of m[2]!.trim().split(/\s+/)) {+ const gid = Number.parseInt(n, 10);+ if (Number.isInteger(gid)) out.add(gid);+ }+ }+ return [...out];+}++/** The user is in the group, but this process predates it. */+export function needsGroupRefresh(f: DockerGroupFacts): boolean {+ return f.gid !== null && f.member && !f.sessionHas;+}++/** The doctor's word for the container engine says the socket exists but this user may not use it. */+export function isPermissionDenied(detail: string | undefined): boolean {+ return /permission denied/i.test(detail ?? "");+}++/**+ * The reason and the fix New Space shows on Linux when the container engine+ * is there but this app cannot use it; null for anything else (not+ * installed, not running), which `noLocalRuntimeReason` words.+ */+export function linuxRuntimeAdvice(facts: DockerGroupFacts, containerDetail: string | undefined, canRelaunch: boolean, relaunched: boolean): { reason: string; fix: RuntimeFix | null } | null {+ const denied = isPermissionDenied(containerDetail) || (facts.socket && !facts.sessionHas && facts.gid !== null);+ if (!denied) return null;+ if (needsGroupRefresh(facts) && canRelaunch && !relaunched) {+ return {+ reason: "Docker is ready, and your account is in its group, but Cua Spaces started before that. Restart it to pick the group up (no logout or reboot needed).",+ fix: { action: "restart-app", label: "Restart Cua Spaces", note: "Takes a few seconds. Your Spaces keep running.", busy: false, termsUrl: null },+ };+ }+ if (facts.member) {+ // Already restarted under the group and still denied, or no `sg`: only a new login session has it.+ return {+ reason: "Docker is installed and your account is in its group, but this session doesn't have it yet. Log out of this desktop session completely and back in (or reboot), then open Cua Spaces.",+ fix: null,+ };+ }+ return {+ reason: "Docker is installed, but your account isn't allowed to use it yet. Run `sudo usermod -aG docker $USER` in a terminal, then reopen Cua Spaces.",+ fix: null,+ };+}++/** `sg docker -c 'VAR=1 exec <target> <args>'`: the command that starts this app again with the docker group. */+export function sgRelaunch(target: string, args: string[], sg = "/usr/bin/sg"): { execPath: string; args: string[] } {+ const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;+ const command = `${SG_DOCKER_ENV}=1 exec ${[target, ...args].map(quote).join(" ")}`;+ return { execPath: sg, args: ["docker", "-c", command] };+}++/** The system reads and the relaunch the decisions above use. */+export interface LinuxSystem {+ user: string;+ /** `getent group docker` (null when there is no such group). */+ groupEntry(): Promise<string | null>;+ /** This process's `/proc/self/status`. */+ status(): Promise<string>;+ socketExists(): boolean;+ /** `sg` is installed. */+ hasSg(): boolean;+ /** Starts the app again under `sg docker` and quits this one. */+ relaunch(): void;+}++export class LinuxRuntime {+ private asked = false;++ constructor(+ private readonly sys: LinuxSystem,+ private readonly env: NodeJS.ProcessEnv = process.env,+ ) {}++ async facts(): Promise<DockerGroupFacts> {+ const [entry, status] = await Promise.all([this.sys.groupEntry().catch(() => null), this.sys.status().catch(() => "")]);+ const { gid, member } = parseGroupEntry(entry, this.sys.user);+ return { gid, member, sessionHas: gid !== null && statusGids(status).includes(gid), socket: this.sys.socketExists() };+ }++ /** The advice for a machine whose runtime did not answer, or null. */+ async advice(containerDetail: string | undefined): Promise<{ reason: string; fix: RuntimeFix | null } | null> {+ const facts = await this.facts();+ return linuxRuntimeAdvice(facts, containerDetail, this.sys.hasSg(), this.env[SG_DOCKER_ENV] === "1");+ }++ /** At launch: starts the app again under the group when it is needed. True when it did (this process quits). */+ async relaunchIfNeeded(): Promise<boolean> {+ if (this.env[SG_DOCKER_ENV] === "1" || !this.sys.hasSg()) return false;+ const facts = await this.facts();+ if (!facts.socket || !needsGroupRefresh(facts)) return false;+ this.relaunch();+ return true;+ }++ run(action: LinuxFixAction): void {+ if (action !== "restart-app" || this.asked) return;+ this.relaunch();+ }++ private relaunch(): void {+ this.asked = true;+ this.sys.relaunch();+ }+}++/** What to start in place of this app: `/usr/bin/sg docker -c 'exec <app> <args>'`. */+export interface RelaunchSpec {+ execPath: string;+ args: string[];+}++const SG = "/usr/bin/sg";++/** The real system. `relaunch` starts `spec` after this app exits and quits it (Electron's `app.relaunch` and `app.exit`). */+export function nodeLinuxSystem(relaunch: (spec: RelaunchSpec) => void, env: NodeJS.ProcessEnv = process.env): LinuxSystem {+ return {+ user: os.userInfo().username,+ groupEntry: () =>+ new Promise((resolve) => {+ execFile("getent", ["group", "docker"], { timeout: 5000 }, (error, stdout) => resolve(error ? null : String(stdout).trim() || null));+ }),+ status: () => readFile("/proc/self/status", "utf8"),+ socketExists: () => existsSync("/var/run/docker.sock") || existsSync("/run/docker.sock"),+ hasSg: () => existsSync(SG),+ relaunch: () => relaunch(sgRelaunch(env.APPIMAGE || process.execPath, process.argv.slice(1), SG)),+ };+}++/**+ * Whether the process `pid` lacks the `docker` group that this process has+ * (it started before the user joined the group). False when anything is+ * unknown: only a clear mismatch replaces a daemon.+ */+export async function daemonLacksDockerGroup(pid: number, read: (file: string) => Promise<string> = (f) => readFile(f, "utf8")): Promise<boolean> {+ try {+ const [entry, mine, theirs] = await Promise.all([+ new Promise<string | null>((resolve) => {+ execFile("getent", ["group", "docker"], { timeout: 5000 }, (error, stdout) => resolve(error ? null : String(stdout).trim() || null));+ }),+ read("/proc/self/status"),+ read(`/proc/${pid}/status`),+ ]);+ const { gid } = parseGroupEntry(entry, "");+ return gid !== null && statusGids(mine).includes(gid) && !statusGids(theirs).includes(gid);+ } catch {+ return false;+ }+}diff --git a/apps/cua-spaces-desktop/src/model/local-runtime.test.ts b/apps/cua-spaces-desktop/src/model/local-runtime.test.tsindex 767326523e..199e386d5d 100644--- a/apps/cua-spaces-desktop/src/model/local-runtime.test.ts+++ b/apps/cua-spaces-desktop/src/model/local-runtime.test.ts@@ -25,4 +25,8 @@ describe("noLocalRuntimeReason", () => {it("tells Windows users to start a stopped Docker Desktop", () => {expect(noLocalRuntimeReason("win32", "container engine at npipe://x is not running")).toMatch(/isn't running/);});++ it("names the group command when Docker is there but the account may not use it (CUA-1763)", () => {+ expect(noLocalRuntimeReason("linux", "permission denied on unix:///var/run/docker.sock: add yourself")).toContain("usermod -aG docker");+ });});diff --git a/apps/cua-spaces-desktop/src/model/local-runtime.ts b/apps/cua-spaces-desktop/src/model/local-runtime.tsindex c036c4fdb6..79576820ba 100644--- a/apps/cua-spaces-desktop/src/model/local-runtime.ts+++ b/apps/cua-spaces-desktop/src/model/local-runtime.ts@@ -20,6 +20,9 @@ export function noLocalRuntimeReason(platform: string, containerDetail?: string)}return `Cua runs local Spaces in Docker Desktop (WSL 2 alone isn't enough). Install it from ${DOCKER_DESKTOP_URL}, start it, then try again.`;}+ if (/permission denied/.test(detail)) {+ return "Docker is installed, but your account isn't allowed to use it yet. Run `sudo usermod -aG docker $USER` in a terminal, then reopen Cua Spaces.";+ }if (installedButStopped) return "Docker isn't running. Start it (for example `sudo systemctl start docker`), then try again.";return "No local runtime found. Install Docker Engine or Podman and start it, then try again.";}diff --git a/apps/cua-spaces-desktop/src/model/windows-runtime.ts b/apps/cua-spaces-desktop/src/model/windows-runtime.tsindex 2c08f69e84..12ec52091a 100644--- a/apps/cua-spaces-desktop/src/model/windows-runtime.ts+++ b/apps/cua-spaces-desktop/src/model/windows-runtime.ts@@ -29,7 +29,7 @@ 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";+export type RuntimeFixAction = "install-docker" | "start-docker" | "restart-app";/** A step the page can offer next to the "no local runtime" reason. */export interface RuntimeFix {@@ -260,6 +260,7 @@ export class WindowsRuntime {/** 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 === "restart-app") return;if (action === "start-docker") {this.start();return;diff --git a/apps/cua-spaces-web/src/bridge/contracts/new-space.ts b/apps/cua-spaces-web/src/bridge/contracts/new-space.tsindex 4193ac9a85..186e8ece70 100644--- a/apps/cua-spaces-web/src/bridge/contracts/new-space.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/new-space.ts@@ -56,7 +56,7 @@ export interface LocalStatus {}/** `spaces.fixRuntime`'s actions. */-export type RuntimeFixAction = "install-docker" | "start-docker";+export type RuntimeFixAction = "install-docker" | "start-docker" | "restart-app";/** A step the host offers next to "no local runtime" (`LocalStatus.fix`). */export interface RuntimeFix {