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): make the Ubuntu .deb removable and close the Linux gaps (CUA-1521, CUA-1524, CUA-1530) (#5104)
ddupontb1ec65127866
diff --git a/apps/cua-spaces-desktop/electron-builder.config.cjs b/apps/cua-spaces-desktop/electron-builder.config.cjsindex cd1fb1d9d1..af3b49aec7 100644--- a/apps/cua-spaces-desktop/electron-builder.config.cjs+++ b/apps/cua-spaces-desktop/electron-builder.config.cjs@@ -178,7 +178,10 @@ module.exports = {for (const f of files) await context.packager.signIf(path.join(resources, "native", f));}},- electronLanguages: ["en"],+ // Chromium's English strings are `en-US.pak`, which "en" alone strips from+ // Linux and Windows builds: the menus then draw their accelerators with no+ // modifier ("+N" for Ctrl+N).+ electronLanguages: ["en", "en-US"],electronFuses: env.CUA_SPACES_NO_FUSES === "1" ? null : electronFuses({ resetAdHocSignature: !macSigning }),mac: {@@ -253,8 +256,14 @@ module.exports = {executableName: linuxId,// 32 to 512 px, symlinks to the Cua Spaces icons so each hicolor size is installed.icon: "packaging/linux-icons",- // 32x32 for the tray; 128x128@2x (256 px) as the window icon (src/icon.ts).- extraResources: [{ from: icons, to: "tray", filter: ["32x32.png", "[email protected]"] }, nativeResources("linux")],+ // The tray glyphs (light for GNOME's dark top bar, dark for a light+ // panel; src/tray.ts), 32x32 as the tray's fallback; 128x128@2x+ // (256 px) as the window icon (src/icon.ts).+ extraResources: [+ { from: icons, to: "tray", filter: ["32x32.png", "[email protected]"] },+ { from: "packaging/linux-tray", to: "tray", filter: ["tray-light.png", "tray-dark.png"] },+ nativeResources("linux"),+ ],category: "Development",// The desktop entry's Comment and the package description (electron-builder// writes the description over an entry's own Comment).@@ -286,7 +295,15 @@ module.exports = {// there the confirmation is unavailable and the Keyvault stays off).deb: {artifactName: "cua-spaces_${version}_${arch}.deb",- fpm: [`${path.join(__dirname, "packaging/ai.cua.spaces.policy")}=/usr/share/polkit-1/actions/ai.cua.spaces.policy`],+ fpm: [+ // Removing the package turns off what the app set up outside /opt+ // (unattended access on the relay, the daemon, launch at login): see+ // the script. An option first: after the first `source=target` fpm reads+ // everything as a path.+ "--before-remove",+ path.join(__dirname, "packaging/linux/prerm.sh"),+ `${path.join(__dirname, "packaging/ai.cua.spaces.policy")}=/usr/share/polkit-1/actions/ai.cua.spaces.policy`,+ ],},// Feed for electron-updater (written to app-update.yml); see the header.diff --git a/apps/cua-spaces-desktop/packaging/linux-tray/tray-dark.png b/apps/cua-spaces-desktop/packaging/linux-tray/tray-dark.pngnew file mode 100644index 0000000000..8dd46c1464Binary files /dev/null and b/apps/cua-spaces-desktop/packaging/linux-tray/tray-dark.png differdiff --git a/apps/cua-spaces-desktop/packaging/linux-tray/tray-light.png b/apps/cua-spaces-desktop/packaging/linux-tray/tray-light.pngnew file mode 100644index 0000000000..0af776a06dBinary files /dev/null and b/apps/cua-spaces-desktop/packaging/linux-tray/tray-light.png differdiff --git a/apps/cua-spaces-desktop/packaging/linux/prerm.sh b/apps/cua-spaces-desktop/packaging/linux/prerm.shnew file mode 100755index 0000000000..d121594d0e--- /dev/null+++ b/apps/cua-spaces-desktop/packaging/linux/prerm.sh@@ -0,0 +1,135 @@+#!/bin/sh+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.+#+# The .deb's pre-removal script (electron-builder deb `fpm`: --before-remove).+#+# Cua Spaces puts things outside /opt that outlive the package: the host+# service ("Set up this machine for unattended access", a systemd user unit+# running a copy of cua-spacesd from ~/.cua) keeps the machine online on the+# Cua relay, the cua daemon keeps the Spaces running, and the app leaves its+# launch-at-login entry and a copy of `cua` in ~/.local/bin. Removing the+# package must turn all of that off, or the machine stays reachable through+# the relay with nobody able to see why (CUA-1521).+#+# Runs for `apt remove` and `apt purge` (both call prerm with "remove"), not+# for an upgrade. Per user that has a cua home (~/.cua and ~/.cua/envs/*),+# it:+# 1. unregisters the machine and the Spaces it provides from the relay,+# deletes the service and the host's tokens (`cua host remove+# --uninstalling`), after turning the provided Spaces off;+# 2. stops the cua daemon;+# 3. removes launch at login and the `cua` copy the app put on PATH.+# The user's data (~/.cua, the Spaces, settings) stays, as with the macOS+# and Windows uninstalls. Every step is best effort and bounded: a failure+# is said on stderr and never blocks the removal.++case "${1:-}" in+remove | purge) ;;+*) exit 0 ;;+esac++APP="/opt/Cua Spaces"+CUA="$APP/resources/native/cua"++say() { echo "cua-spaces: $*" >&2; }++# As user <id> (a name, a uid) with the session variables that reach their+# systemd user manager, for at most <seconds>:+# as_user <seconds> <name> <uid> <home> <command...>+as_user() {+ secs=$1+ u=$2+ id=$3+ h=$4+ shift 4+ rt="/run/user/$id"+ limit=""+ command -v timeout >/dev/null 2>&1 && limit="timeout $secs"+ if [ "$id" = 0 ]; then+ $limit env HOME="$h" XDG_RUNTIME_DIR="$rt" DBUS_SESSION_BUS_ADDRESS="unix:path=$rt/bus" "$@"+ elif command -v runuser >/dev/null 2>&1; then+ $limit runuser -u "$u" -- env HOME="$h" XDG_RUNTIME_DIR="$rt" DBUS_SESSION_BUS_ADDRESS="unix:path=$rt/bus" "$@"+ else+ return 1+ fi+}++# The app first: a running one would start the daemon again.+quit_app() {+ pkill -TERM -f "^$APP/cua-spaces" 2>/dev/null || return 0+ n=0+ while pgrep -f "^$APP/cua-spaces" >/dev/null 2>&1 && [ "$n" -lt 10 ]; do+ sleep 0.5+ n=$((n + 1))+ done+ pkill -KILL -f "^$APP/cua-spaces" 2>/dev/null || true+}++# One cua home of one user: <name> <uid> <home> <cua home>.+turn_off() {+ u=$1+ id=$2+ h=$3+ ch=$4+ if [ -f "$ch/host/config.json" ]; then+ say "turning off unattended access ($ch)"+ if ! as_user 150 "$u" "$id" "$h" env CUA_HOME="$ch" "$CUA" host remove --force --uninstalling; then+ say "could not tell the relay this machine is gone; remove it from Machines in the app or at cua.ai"+ fi+ fi+ if [ -d "$ch" ]; then+ as_user 30 "$u" "$id" "$h" env CUA_HOME="$ch" "$CUA" daemon stop >/dev/null 2>&1 || true+ fi+ # Whatever the removal above could not reach (no session bus for a user+ # who is logged out): the unit file, and a driver still running.+ unit="$h/.config/systemd/user/cua-spacesd-host.service"+ if [ -f "$unit" ] && [ ! -f "$ch/host/config.json" ]; then+ as_user 20 "$u" "$id" "$h" systemctl --user disable --now cua-spacesd-host >/dev/null 2>&1 || true+ fi+ pkill -KILL -u "$id" -f "$ch/host/bin/" 2>/dev/null || true+}++# What the app wrote into one user's home.+clean_home() {+ u=$1+ id=$2+ h=$3+ autostart="$h/.config/autostart/cua-spaces.desktop"+ if [ -f "$autostart" ] && grep -q "cua-spaces" "$autostart" 2>/dev/null; then+ rm -f "$autostart"+ fi+ shim="$h/.local/bin/cua"+ if [ -e "$shim" ] || [ -L "$shim" ]; then+ if [ -L "$shim" ]; then+ case "$(readlink "$shim")" in "$APP"/*) rm -f "$shim" ;; esac+ elif [ -f "$CUA" ] && cmp -s "$shim" "$CUA" 2>/dev/null; then+ rm -f "$shim"+ fi+ fi+ # The copy of cua the daemon runs from when it cannot run from the package.+ data="${XDG_DATA_HOME:-$h/.local/share}/cua-spaces/daemon"+ [ -d "$data" ] && rm -rf "$data"+ pkill -KILL -u "$id" -f "cua-spaces/daemon/.*/cua daemon" 2>/dev/null || true+}++quit_app++getent passwd 2>/dev/null | while IFS=: read -r name _ id _ _ home _; do+ case "$id" in '' | *[!0-9]*) continue ;; esac+ # Real accounts only: root and ordinary users.+ [ "$id" = 0 ] || [ "$id" -ge 1000 ] || continue+ [ -d "$home" ] || continue+ if [ -x "$CUA" ]; then+ for ch in "$home/.cua" "$home"/.cua/envs/*; do+ [ -d "$ch" ] || continue+ turn_off "$name" "$id" "$home" "$ch"+ done+ fi+ clean_home "$name" "$id" "$home"+done++# Anything still running from the package (a daemon that did not answer).+pkill -KILL -f "^$APP/" 2>/dev/null || true++exit 0diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.tsindex b67eece485..09a09ee18b 100644--- a/apps/cua-spaces-desktop/src/bridge/settings.ts+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts@@ -63,7 +63,8 @@ export function settingsPage(model: AppModel, parts: HostParts) {keyvaultProtection: model.keyvault.page.protection,autoConnect: model.settings.autoConnect,lumeSource: model.lumeSource ?? undefined,- linuxSource: model.linuxSource ?? undefined,+ // The built-in Linux runtime is a gVisor VM on a Mac; Docker is the runtime elsewhere, so no row.+ linuxSource: process.platform === "darwin" ? (model.linuxSource ?? undefined) : undefined,};const page = model.native.appSettingsPage(input);return model.native.appSettingsWithStorage(page, parts.storage.section, model.settings.experiments);diff --git a/apps/cua-spaces-desktop/src/passphrase.ts b/apps/cua-spaces-desktop/src/passphrase.tsindex c1314d91c7..94704a9178 100644--- a/apps/cua-spaces-desktop/src/passphrase.ts+++ b/apps/cua-spaces-desktop/src/passphrase.ts@@ -10,6 +10,7 @@// its labels, and `kvPassphraseCheck` for the hint and whether it can be sent.import { randomBytes } from "node:crypto";import * as path from "node:path";+import { showWhenReady } from "./show-when-ready";import type { KvCredentialForm, KvFormMode, KvPassphraseCheck } from "./native/generated/index";import type { CredentialAnswer } from "./model/keyvault";@@ -197,7 +198,7 @@ async function showForm(ipcMain.on(PASSPHRASE_CANCEL, onCancel);win.webContents.on("will-navigate", (e) => e.preventDefault());win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));- win.once("ready-to-show", () => win.show());+ showWhenReady(win, () => win.show());win.on("closed", () => session.cancel());void session.answer.then(() => {ipcMain.removeHandler(PASSPHRASE_CHECK);diff --git a/apps/cua-spaces-desktop/src/pip.ts b/apps/cua-spaces-desktop/src/pip.tsindex c5558a8ca4..fc2410cacd 100644--- a/apps/cua-spaces-desktop/src/pip.ts+++ b/apps/cua-spaces-desktop/src/pip.ts@@ -20,6 +20,7 @@ import { APP_ORIGIN } from "./protocol";import { aspectOf, fitToStream, initialPipBounds, pipPath, PIP_DEFAULT_ASPECT, PIP_MIN_WIDTH, type Rect } from "./pip-layout";import { readSettings, writeSettings } from "./settings";import { appWindow } from "./window";+import { showWhenReady } from "./show-when-ready";export interface PipWindows extends PipPresenter {/** Closes every panel (the app quits). */@@ -98,7 +99,7 @@ export function createPipWindows(): PipWindows {if (open.get(k) === win) open.delete(k);closed();});- win.once("ready-to-show", () => win.show());+ showWhenReady(win, () => win.show());void win.loadURL(`${APP_ORIGIN}${pipPath(spec)}`);},close(spaceId: string, key: string) {diff --git a/apps/cua-spaces-desktop/src/show-when-ready.ts b/apps/cua-spaces-desktop/src/show-when-ready.tsnew file mode 100644index 0000000000..c2ab42e76d--- /dev/null+++ b/apps/cua-spaces-desktop/src/show-when-ready.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Windows start hidden and show once their page has painted (`ready-to-show`),+// so no blank frame flashes. Chromium on Wayland presents nothing for a window+// that was never mapped, so on some compositors (headless GNOME Shell, seen on+// Ubuntu 24.04) the first paint, and with it `ready-to-show`, never comes and+// the window never appears. A window is therefore shown at the latest after+// `READY_TIMEOUT_MS`; its background colour is already the theme's, so showing+// early only means the page paints a moment later. (CUA-1507, Wayland.)+import type { BrowserWindow } from "electron";++export const READY_TIMEOUT_MS = 2500;++/** Calls `show` once, when `win` is ready to show or `READY_TIMEOUT_MS` passed, whichever is first; never for a closed window. */+export function showWhenReady(win: Pick<BrowserWindow, "once" | "isDestroyed">, show: () => void, timeoutMs = READY_TIMEOUT_MS): void {+ let done = false;+ const go = () => {+ if (done || win.isDestroyed()) return;+ done = true;+ clearTimeout(timer);+ show();+ };+ const timer = setTimeout(go, timeoutMs);+ timer.unref?.();+ win.once("ready-to-show", go);+ win.once("closed", () => {+ done = true;+ clearTimeout(timer);+ });+}diff --git a/apps/cua-spaces-desktop/src/tray.ts b/apps/cua-spaces-desktop/src/tray.tsindex be4e250af1..f5e4100e53 100644--- a/apps/cua-spaces-desktop/src/tray.ts+++ b/apps/cua-spaces-desktop/src/tray.ts@@ -10,7 +10,7 @@// instead of quitting; use Quit in the menu (or File > Exit) to stop the// app. Linux keeps quit-on-close, because many desktops (GNOME without the// AppIndicator extension) show no tray at all.-import { app, Menu, nativeImage, Tray, type MenuItemConstructorOptions } from "electron";+import { app, Menu, nativeImage, nativeTheme, Tray, type MenuItemConstructorOptions } from "electron";import { existsSync } from "node:fs";import * as path from "node:path";@@ -20,10 +20,26 @@ let quitting = false;export const isQuitting = () => quitting;export const closesToTray = () => tray !== null && process.platform === "win32";-// Packaged: Resources/tray/. Dev: the Cua Spaces icons, used in place.+/**+ * The Linux tray icon's file: a one-colour glyph (the Mac's template icon)+ * that has to contrast with the panel behind it. GNOME's top bar (and+ * Unity's, Pantheon's and Budgie's) is dark whatever the app theme is, so+ * it gets the light glyph; other desktops draw the panel in the system+ * theme's colour.+ */+export function linuxTrayIconName(desktop: string | undefined, darkTheme: boolean): "tray-light.png" | "tray-dark.png" {+ const darkPanel = /gnome|unity|pantheon|budgie|ubuntu|cosmic/i.test(desktop ?? "");+ return darkPanel || darkTheme ? "tray-light.png" : "tray-dark.png";+}++const linuxTrayName = () => linuxTrayIconName(process.env.XDG_CURRENT_DESKTOP, nativeTheme.shouldUseDarkColors);++// Packaged: Resources/tray/. Dev: the Cua Spaces icons, used in place (the+// Linux glyphs are in the packaging folder).function iconPath(): string | null {- const name = process.platform === "darwin" ? "tray-template.png" : process.platform === "win32" ? "icon.ico" : "32x32.png";- const dirs = app.isPackaged ? [path.join(process.resourcesPath, "tray")] : [path.join(__dirname, "../../cua-spaces/src-tauri/icons")];+ const name = process.platform === "darwin" ? "tray-template.png" : process.platform === "win32" ? "icon.ico" : linuxTrayName();+ const dev = process.platform === "linux" ? path.join(__dirname, "../packaging/linux-tray") : path.join(__dirname, "../../cua-spaces/src-tauri/icons");+ const dirs = app.isPackaged ? [path.join(process.resourcesPath, "tray")] : [dev];for (const dir of dirs) {const file = path.join(dir, name);if (existsSync(file)) return file;@@ -31,6 +47,13 @@ function iconPath(): string | null {return null;}+/** The icon as the tray draws it; Linux shells show 22 to 24 px, so the 36 px glyph is scaled down once, here. */+function trayImage(file: string) {+ const image = nativeImage.createFromPath(file);+ if (process.platform === "darwin") image.setTemplateImage(true);+ return process.platform === "linux" ? image.resize({ width: 24, height: 24, quality: "best" }) : image;+}+/** What the tray lists of a Space. */export interface TraySpace {id: string;@@ -112,9 +135,7 @@ export function installTray(o: {const icon = iconPath();if (!icon) return;- const image = nativeImage.createFromPath(icon);- if (process.platform === "darwin") image.setTemplateImage(true);- tray = new Tray(image);+ tray = new Tray(trayImage(icon));tray.setToolTip("Cua Spaces");const fallback: TrayMenuItem[] = [@@ -129,6 +150,13 @@ export function installTray(o: {// Read again each time the menu could open, and when what it shows changed.tray.on("right-click", rebuild);o.onChange?.(rebuild);+ // A desktop's theme switch can swap the panel's colour under the glyph.+ if (process.platform === "linux") {+ nativeTheme.on("updated", () => {+ const next = iconPath();+ if (next) tray?.setImage(trayImage(next));+ });+ }rebuild();setInterval(rebuild, 60_000).unref();}diff --git a/apps/cua-spaces-desktop/src/viewer.ts b/apps/cua-spaces-desktop/src/viewer.tsindex 0ba0534208..549e4b7f7b 100644--- a/apps/cua-spaces-desktop/src/viewer.ts+++ b/apps/cua-spaces-desktop/src/viewer.ts@@ -17,6 +17,7 @@ import { fitViewerToStream, initialViewerBounds, viewerPath, VIEWER_MIN_HEIGHT,import type { Rect } from "./pip-layout";import { readSettings, writeSettings } from "./settings";import { appWindow } from "./window";+import { showWhenReady } from "./show-when-ready";export interface ViewerWindows {/** The Space's viewer, opened or brought to the front. */@@ -93,7 +94,7 @@ export function createViewerWindows({ remember = true }: { remember?: boolean }win.on("closed", () => {if (open.get(spaceId) === win) open.delete(spaceId);});- win.once("ready-to-show", () => {+ showWhenReady(win, () => {if (!hidden()) win.show();});void win.loadURL(`${APP_ORIGIN}${viewerPath(spaceId, name, os)}`);diff --git a/apps/cua-spaces-desktop/src/window.ts b/apps/cua-spaces-desktop/src/window.tsindex a125fe252a..6ad09d2c57 100644--- a/apps/cua-spaces-desktop/src/window.ts+++ b/apps/cua-spaces-desktop/src/window.ts@@ -11,6 +11,7 @@ import { readSettings, writeSettings, type WindowBounds } from "./settings";import { DIM_CHANNEL, overlayColors, overlaySteps } from "./overlay";import { KEYBOARD_CHANNEL, applyKeyboard } from "./keyboard";import { BACKGROUND, resolvedTheme } from "./theme";+import { showWhenReady } from "./show-when-ready";const TITLEBAR_HEIGHT = 40;// Room for the macOS traffic lights at x=16 plus a gap.@@ -212,12 +213,14 @@ export function createMainWindow({ demo = false, remember = true }: { demo?: booconst bounds = hidden() ? { ...DEFAULT_SIZE, width: 1440, height: 900 } : remember ? restoredBounds() : { ...DEFAULT_SIZE };const win = appWindow({ ...bounds, title: "Cua Spaces" });+ // performance.now() counts from process start.win.once("ready-to-show", () => {- // performance.now() counts from process start.readyToShowMs = performance.now();if (process.env.CUA_SPACES_LOG_STARTUP) {console.log(`[cua-spaces] ready-to-show ${readyToShowMs.toFixed(0)}ms after process start`);}+ });+ showWhenReady(win, () => {if (hidden()) return;if (bounds.maximized) win.maximize();win.show();diff --git a/apps/cua-spaces-desktop/test/packaging.test.ts b/apps/cua-spaces-desktop/test/packaging.test.tsindex cf8e18c939..ee9f172db4 100644--- a/apps/cua-spaces-desktop/test/packaging.test.ts+++ b/apps/cua-spaces-desktop/test/packaging.test.ts@@ -1,10 +1,11 @@// SPDX-License-Identifier: FSL-1.1-MIT// Copyright (c) 2026 Cua AI, Inc.-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";import { tmpdir } from "node:os";import * as path from "node:path";+import { execFileSync } from "node:child_process";import { afterEach, describe, expect, it } from "vitest";import { LINUX_WINDOW_ICON, windowIconPath } from "../src/icon";@@ -35,6 +36,44 @@ describe("packaging", () => {expect(filter).toContain(LINUX_WINDOW_ICON);expect(filter).toContain("32x32.png");});++ it("ships a light and a dark one-colour tray glyph for Linux panels", () => {+ const res = config.linux.extraResources.find((r: { to: string; from: string }) => r.to === "tray" && r.from === "packaging/linux-tray");+ expect(res.filter.sort()).toEqual(["tray-dark.png", "tray-light.png"]);+ for (const f of res.filter) expect(existsSync(path.join(import.meta.dirname, "..", res.from, f))).toBe(true);+ });++ it("keeps Chromium's en-US strings: without them menu accelerators lose their modifier on Linux", () => {+ // en-US.pak holds "Ctrl" and "Alt"; "en" alone matches no pak (CUA-1530).+ expect(config.electronLanguages).toContain("en-US");+ });+});++describe("the .deb's removal script (CUA-1521)", () => {+ const script = path.join(import.meta.dirname, "../packaging/linux/prerm.sh");++ it("runs before the package is removed", () => {+ // An option goes before the first `source=target` path: after it, fpm reads everything as a path.+ const args: string[] = config.deb.fpm;+ expect(args.slice(0, 2)).toEqual(["--before-remove", script]);+ expect(args.findIndex((a) => a.includes("="))).toBeGreaterThan(1);+ });++ it("is valid shell and turns off the host service, the daemon and the relay entry", () => {+ execFileSync("sh", ["-n", script]);+ const text = readFileSync(script, "utf8");+ expect(text).toContain("host remove --force --uninstalling");+ expect(text).toContain("daemon stop");+ expect(text).toContain("autostart/cua-spaces.desktop");+ expect(statSync(script).mode & 0o111).not.toBe(0);+ });++ it("leaves an upgrade alone", () => {+ // Only remove and purge turn anything off; an upgrade replaces the files and keeps the host running.+ for (const action of ["upgrade", "failed-upgrade", "deconfigure"]) {+ expect(execFileSync("sh", [script, action]).toString()).toBe("");+ }+ });});describe("the Linux install tree", () => {diff --git a/apps/cua-spaces-desktop/test/show-when-ready.test.ts b/apps/cua-spaces-desktop/test/show-when-ready.test.tsnew file mode 100644index 0000000000..2b3009c8f1--- /dev/null+++ b/apps/cua-spaces-desktop/test/show-when-ready.test.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// A window is shown when its page painted, or after a timeout when the+// compositor never lets it paint (Chromium on Wayland, headless GNOME Shell).+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { EventEmitter } from "node:events";+import { READY_TIMEOUT_MS, showWhenReady } from "../src/show-when-ready";++class FakeWindow extends EventEmitter {+ destroyed = false;+ isDestroyed() {+ return this.destroyed;+ }+}++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++describe("showWhenReady", () => {+ it("shows at ready-to-show, once", () => {+ const win = new FakeWindow();+ const show = vi.fn();+ showWhenReady(win as never, show);+ win.emit("ready-to-show");+ vi.advanceTimersByTime(READY_TIMEOUT_MS * 2);+ expect(show).toHaveBeenCalledTimes(1);+ });++ it("shows after the timeout when ready-to-show never comes (Wayland)", () => {+ const win = new FakeWindow();+ const show = vi.fn();+ showWhenReady(win as never, show);+ vi.advanceTimersByTime(READY_TIMEOUT_MS - 1);+ expect(show).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(show).toHaveBeenCalledTimes(1);+ win.emit("ready-to-show");+ expect(show).toHaveBeenCalledTimes(1);+ });++ it("does not show a window that was closed or destroyed first", () => {+ const closed = new FakeWindow();+ const show = vi.fn();+ showWhenReady(closed as never, show);+ closed.emit("closed");+ vi.advanceTimersByTime(READY_TIMEOUT_MS * 2);+ const gone = new FakeWindow();+ showWhenReady(gone as never, show);+ gone.destroyed = true;+ vi.advanceTimersByTime(READY_TIMEOUT_MS * 2);+ expect(show).not.toHaveBeenCalled();+ });+});diff --git a/apps/cua-spaces-desktop/test/tray.test.ts b/apps/cua-spaces-desktop/test/tray.test.tsindex 19a329adef..0a595e0f40 100644--- a/apps/cua-spaces-desktop/test/tray.test.ts+++ b/apps/cua-spaces-desktop/test/tray.test.ts@@ -7,8 +7,8 @@import { describe, expect, it, vi } from "vitest";const quit = vi.fn();-vi.mock("electron", () => ({ app: { quit, on: () => {}, isPackaged: false }, Menu: {}, nativeImage: {}, Tray: class {} }));-const { accelerator, trayTemplate } = await import("../src/tray");+vi.mock("electron", () => ({ app: { quit, on: () => {}, isPackaged: false }, Menu: {}, nativeImage: {}, nativeTheme: { on: () => {}, shouldUseDarkColors: false }, Tray: class {} }));+const { accelerator, linuxTrayIconName, trayTemplate } = await import("../src/tray");const items = [{ id: "status", label: "2 Spaces", enabled: false },@@ -60,3 +60,17 @@ describe("the menu bar item and the tray", () => {expect(accelerator(undefined, "darwin")).toBeUndefined();});});++describe("the Linux tray glyph", () => {+ it("is light on GNOME's dark top bar whatever the app theme", () => {+ expect(linuxTrayIconName("ubuntu:GNOME", false)).toBe("tray-light.png");+ expect(linuxTrayIconName("GNOME", false)).toBe("tray-light.png");+ expect(linuxTrayIconName("Budgie:GNOME", true)).toBe("tray-light.png");+ });++ it("follows the system theme on desktops with a themed panel", () => {+ expect(linuxTrayIconName("KDE", false)).toBe("tray-dark.png");+ expect(linuxTrayIconName("XFCE", true)).toBe("tray-light.png");+ expect(linuxTrayIconName(undefined, false)).toBe("tray-dark.png");+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/detail.test.tsindex 4cd27f12d0..a77d57186d 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/detail.test.ts@@ -8,7 +8,7 @@ import type { TelemetryView } from "../contracts/host";import { sanitizeSignals } from "../ops/telemetry";import { TelemetryForwarder, telemetryAllowed } from "../telemetry";import { toMachineRows } from "../adapters/webkit";-import { rowsToSpaces, toMachines } from "../derive";+import { machineIdOf, rowsToSpaces, toMachines } from "../derive";import { agentRunLines, desktopCover, SpaceDetailStore, spaceDetail } from "../space-detail";import type { CoreClient } from "../core";import { parseDropped, sendFiles, splitDrop } from "../space-files";@@ -135,6 +135,36 @@ describe("this device's access to its machines", () => {});});+describe("this computer on the relay (CUA-1527)", () => {+ const HOST = "09c8b17b5a55f89bc1e376eaeabf111f";+ const wkSpace = (id: string, name: string, host?: string) => ({ space: { id, name, provider: "relay", status: "running", os: "linux", host, hostName: host ? "lg-x11" : undefined } });+ const status = { configured: true, mode: "relay", machineId: HOST, name: "lg-x11", sharing: true, serviceInstalled: true, serviceRunning: true, serviceKind: "systemd", clients: [], permissions: [] };++ it("lists the machine that is set up for access once, as This computer, with its Spaces", () => {+ const spaces = { spaces: [wkSpace("relay:space-16dec1e7810d08b6", "remote-from-wl", HOST), wkSpace(`relay:${HOST}`, "lg-x11")] };+ const rows = toMachineRows(spaces as never, { devices: null, signedIn: true, host: status } as never, "linux");+ expect(rows.map((r) => r.name)).toEqual(["This computer"]);+ const machines = toMachines(rows, []);+ expect(machines).toHaveLength(1);+ });++ it("puts the Spaces this machine provides on This computer", () => {+ const rows = toMachineRows({ spaces: [wkSpace("relay:space-16dec1e7810d08b6", "remote-from-wl", HOST)] } as never, { devices: null, signedIn: true, host: status } as never, "linux");+ const here = rows.find((r) => r.current)!;+ expect(machineIdOf({ id: "relay:space-16dec1e7810d08b6", provider: "relay", host: HOST }, rows)).toBe(here.id);+ });++ it("does not list a Space registered on the relay as a machine", () => {+ const rows = toMachineRows({ spaces: [wkSpace("relay:space-32179dffc4bd8902", "lin-local")] } as never, { devices: null, signedIn: true } as never, "linux");+ expect(rows.map((r) => r.name)).toEqual(["This computer"]);+ });++ it("still lists another machine's Spaces under that machine", () => {+ const rows = toMachineRows({ spaces: [wkSpace("relay:space-aaaa", "job", "feedfacefeedfacefeedfacefeedface")] } as never, { devices: null, signedIn: true, host: status } as never, "linux");+ expect(rows.map((r) => r.name)).toEqual(["This computer", "lg-x11"]);+ });+});+describe.skipIf(!wasmBuilt)("a Space's detail as this device sees it (wasm core)", () => {const row = (over: Partial<SpaceRow>): SpaceRow => ({ id: "relay:studio", name: "Studio", provider: "relay", os: "macos", spacesdVersion: "0.6.0", features: ["desktop_stream", "host_spaces"], reachable: true, ...over });diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex 8fa120794a..7bc6ca5616 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -142,6 +142,10 @@ export function toMachineRows(spaces: WkSpaces, machines: WkMachines | null, os:if (machines?.accessNotice) self.accessNotice = machines.accessNotice;const rows: MachineRow[] = [self];const byId = new Map(rows.map((r) => [r.id, r] as const));+ // This computer is also on the relay under its own machine id once it is set+ // up for access: that is the same row, not a second machine.+ const hostMachineId = machines?.host?.machineId || undefined;+ if (hostMachineId) byId.set(hostMachineId, self);const add = (row: MachineRow) => {byId.set(row.id, row);rows.push(row);@@ -149,6 +153,8 @@ export function toMachineRows(spaces: WkSpaces, machines: WkMachines | null, os:for (const { space } of spaces.spaces) {// A machine's own desktop: `relay:<machine>` with no host above it.const own = space.provider === "relay" && !space.host && space.id.startsWith("relay:") ? space.id.slice(6) : undefined;+ // A Space registered on the relay (`space-…`) is a Space, not a machine.+ if (own?.startsWith("space-")) continue;if (own && !own.includes("/")) {// The list's connect probe was refused by a machine that stopped// sharing: it is connected (that is how it refused), not offline.@@ -156,6 +162,8 @@ export function toMachineRows(spaces: WkSpaces, machines: WkMachines | null, os:const online = space.status === "running" || space.status === "local" || stopped;const limits = stopped ? withNotSharing([], stoppedSharingLine(space.name)) : [];const known = byId.get(own);+ // This computer keeps its own name and system ("This computer", Linux).+ if (known === self) continue;if (known) Object.assign(known, { name: space.name, os: space.os, online, limits });else add({ id: own, name: space.name, via: "relay", online, os: space.os, detail: space.detail || undefined, limits });continue;diff --git a/apps/cua-spaces-web/src/bridge/derive.ts b/apps/cua-spaces-web/src/bridge/derive.tsindex 05e86b31b1..cb41cf4674 100644--- a/apps/cua-spaces-web/src/bridge/derive.ts+++ b/apps/cua-spaces-web/src/bridge/derive.ts@@ -273,11 +273,14 @@ export interface Machine {/** Which machine a Space runs on: its relay host, the machine itself for* its own desktop (`relay:<machine>`), or this machine for a local Space;* undefined for cloud Spaces. */-export function machineIdOf(space: Pick<Space, "id" | "host" | "provider">, machines: Pick<MachineRow, "id" | "current">[]): string | undefined {- if (space.host) return space.host;- if (space.provider === "local") return machines.find((m) => m.current)?.id;+export function machineIdOf(space: Pick<Space, "id" | "host" | "provider">, machines: Pick<MachineRow, "id" | "current" | "host">[]): string | undefined {+ const current = machines.find((m) => m.current);+ // This computer's own relay machine id is this computer's row.+ const here = (id: string) => (current?.host?.machineId && id === current.host.machineId ? current.id : id);+ if (space.host) return here(space.host);+ if (space.provider === "local") return current?.id;if (space.provider === "relay" && space.id.startsWith("relay:")) {- const own = space.id.slice("relay:".length);+ const own = here(space.id.slice("relay:".length));if (machines.some((m) => m.id === own)) return own;}return undefined;diff --git a/docs/content/docs/cua-cli/reference/cli/host.mdx b/docs/content/docs/cua-cli/reference/cli/host.mdxindex bee199c66c..c2c0fe6719 100644--- a/docs/content/docs/cua-cli/reference/cli/host.mdx+++ b/docs/content/docs/cua-cli/reference/cli/host.mdx@@ -230,6 +230,7 @@ cua host remove [OPTIONS]| Flag | Short | Type | Default | Description || --- | --- | --- | --- | --- || <span id="cua-host-remove--force"></span>`--force` | `-f` | boolean | `false` | Skip the confirmation prompt. Required when there is no terminal to ask on (scripts, agents): without it nothing is removed. |+| <span id="cua-host-remove--uninstalling"></span>`--uninstalling` | | boolean | `false` | For an uninstall of Cua Spaces: turns off the Spaces this machine provides and takes them off the relay too, instead of refusing while it provides any. The Spaces and their data stay on this machine. |**Examples**diff --git a/docs/content/docs/spaces/guides/unattended-access.mdx b/docs/content/docs/spaces/guides/unattended-access.mdxindex cf2855acc3..77a686fce5 100644--- a/docs/content/docs/spaces/guides/unattended-access.mdx+++ b/docs/content/docs/spaces/guides/unattended-access.mdx@@ -51,6 +51,11 @@ cua host start # share againcua host remove # unregister, uninstall the service, delete ~/.cua/host```+Uninstalling the app turns this off too. On Linux, `sudo apt remove cua-spaces`+(and `purge`) removes the machine, and the Spaces it provides, from the relay,+deletes the `cua-spacesd-host.service` user unit and stops the daemon. Your+Spaces and data under `~/.cua` stay on the machine (the Spaces are turned off).+`cua host stop` turns sharing off locally first, so it holds even when therelay is unreachable. In direct mode `cua host status` prints the URL and theenv token's path; add the machine elsewhere withdiff --git a/docs/content/docs/spaces/quickstart.mdx b/docs/content/docs/spaces/quickstart.mdxindex 339fa2fd4b..043779393a 100644--- a/docs/content/docs/spaces/quickstart.mdx+++ b/docs/content/docs/spaces/quickstart.mdx@@ -14,6 +14,20 @@ locally, and register it as your first Space.later.- Docker, for the local Space.+### Cua Spaces on Linux++The supported Linux package is the **.deb** on Ubuntu 24.04 (x64 and arm64),+installed with `sudo apt install ./cua-spaces_<version>_<arch>.deb`. It is+sandboxed, installs the confirmation prompt the Keyvault needs, and+`sudo apt remove cua-spaces` turns off what the app set up (see+[Unattended access](/spaces/guides/unattended-access#check-pause-remove)).+Other distributions and desktops are untested.++The **AppImage** is a portable build, not a supported one. It cannot use the+browser sandbox (it starts with `--no-sandbox`), and without the system's+confirmation prompt the Keyvault is unavailable. Use it to try Cua Spaces+without installing; install the .deb to keep it.+For CLI-managed local Linux Spaces, use Docker (gVisor `runsc`, when installed, addsisolation) or QEMU. QEMU needs read/write access to `/dev/kvm` for hardwareacceleration of same-architecture guests. The managed runtime is macOS-only.diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 607ece10cf..2ad59d1ae7 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -203,6 +203,12 @@ pub enum HostCmd {/// to ask on (scripts, agents): without it nothing is removed.#[arg(long, short)]force: bool,+ /// For an uninstall of Cua Spaces: turns off the Spaces this machine+ /// provides and takes them off the relay too, instead of refusing+ /// while it provides any. The Spaces and their data stay on this+ /// machine.+ #[arg(long)]+ uninstalling: bool,},}@@ -1472,7 +1478,10 @@ pub async fn run_host(.map_err(host_err)?;print_allow(&allow, json, out);}- HostCmd::Remove { force } => {+ HostCmd::Remove {+ force,+ uninstalling,+ } => {use crate::sandbox::{DeleteConfirmation, confirm_delete};use std::io::IsTerminal as _;match confirm_delete(force, std::io::stdin().is_terminal(), || {@@ -1492,7 +1501,11 @@ pub async fn run_host());}}- host.remove().await.map_err(host_err)?;+ if uninstalling {+ host.remove_for_uninstall().await.map_err(host_err)?;+ } else {+ host.remove().await.map_err(host_err)?;+ }if json {line(out, r#"{"removed":true}"#);} else {@@ -1503,6 +1516,38 @@ pub async fn run_host(Ok(0)}+/// How long an uninstall waits for one Space to turn off.+const UNINSTALL_STOP_WAIT: std::time::Duration = std::time::Duration::from_secs(45);++/// `cua host remove --uninstalling`: turns off (keeping its data) each Space+/// this machine provides, so nothing of this machine stays reachable+/// through the relay. Best effort, each reported on stderr.+pub async fn turn_off_provided_spaces<F, Fut>(home: &Path, open: F)+where+ F: FnOnce() -> Fut,+ Fut: std::future::Future<Output = Result<Arc<cua_sdk::Cua>, CuaError>>,+{+ let provided = Host::new(home).provided_spaces().unwrap_or_default();+ if provided.is_empty() {+ return;+ }+ let cua = match open().await {+ Ok(cua) => cua,+ Err(e) => {+ eprintln!("Could not turn off the Spaces this machine provides: {e}");+ return;+ }+ };+ for space in provided {+ let id = space.local_space;+ match tokio::time::timeout(UNINSTALL_STOP_WAIT, cua.spaces().stop(id.clone())).await {+ Ok(Ok(_)) => eprintln!("Turned off {id}."),+ Ok(Err(e)) => eprintln!("Could not turn off {id}: {e}"),+ Err(_) => eprintln!("Timed out turning off {id}."),+ }+ }+}+fn print_allow(allow: &[String], json: bool, out: &mut dyn Write) {if json {line(out, serde_json::json!({ "allow": allow }).to_string());diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex e493d625b7..ce5d1eab87 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -1679,6 +1679,21 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {match cli.command {Command::Host(cmd) => {let home = util::cua_home();+ // An uninstall turns off the Spaces this machine provides first+ // (each is on the relay as its own machine), best effort.+ if matches!(+ cmd,+ host::HostCmd::Remove {+ uninstalling: true,+ ..+ }+ ) {+ let rest = Cli {+ command: Command::Spaces(host::SpacesCmd::Ls { relay: None }),+ ..cli+ };+ host::turn_off_provided_spaces(&home, || open(&rest, false)).await;+ }let flow = if matches!(&cmd, host::HostCmd::Setup { remote: true, .. }) {cua_auth::Flow::Device} else {diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex 130e6c9fbe..71f1eb430f 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -1614,12 +1614,30 @@ impl Host {/// and deletes `<home>/host`. The machine id is kept so a later setup/// reuses it.pub async fn remove(&self) -> Result<()> {+ self.remove_inner(false).await+ }++ /// [`Self::remove`] for an uninstall of the app: the Spaces this machine+ /// provides do not stop it. Their relay machines (each Space joined the+ /// relay as its own) are unregistered too, so nothing stays reachable+ /// through the relay; the Spaces themselves are left as they are for+ /// the caller to turn off ([`Self::provided_spaces`]).+ pub async fn remove_for_uninstall(&self) -> Result<()> {+ self.remove_inner(true).await+ }++ /// The Spaces this host provides to the owner's other devices.+ pub fn provided_spaces(&self) -> Result<Vec<crate::provided::ProvidedSpace>> {+ crate::provided::load_provided(&self.paths.dir)+ }++ async fn remove_inner(&self, uninstalling: bool) -> Result<()> {let Some(config) = self.config()? else {return Ok(());};// Spaces it provides would keep running with nobody to delete them.let provided = crate::provided::load_provided(&self.paths.dir)?;- if !provided.is_empty() {+ if !provided.is_empty() && !uninstalling {return Err(Error::InvalidArgument(format!("this machine still provides {} Space{} ({}); delete {} first (`cua spaces delete <local:name>`)",provided.len(),@@ -1633,17 +1651,32 @@ impl Host {)));}let mut relay_error = None;+ let mut note = |e: Error| match e {+ // Already gone: nothing to tell the relay.+ Error::NotFound(_) => {}+ // A refused machine token leaves the entry listed under My+ // machines; report it (after the local cleanup) rather than+ // pretending the unregister worked.+ e => relay_error = Some(e),+ };+ if uninstalling {+ for space in &provided {+ if space.machine_token.is_empty() || space.relay_url.is_empty() {+ continue;+ }+ if let Err(e) = RelayClient::new(&space.relay_url)?+ .delete(&space.machine_token, &space.relay_machine)+ .await+ {+ note(e);+ }+ }+ }if let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id)&& let Ok(token) = read_secret(&self.paths.machine_token())+ && let Err(e) = RelayClient::new(url)?.delete(&token, id).await{- match RelayClient::new(url)?.delete(&token, id).await {- // Already gone: nothing to tell the relay.- Ok(()) | Err(Error::NotFound(_)) => {}- // A refused machine token leaves the entry listed under My- // machines; report it (after the local cleanup) rather than- // pretending the unregister worked.- Err(e) => relay_error = Some(e),- }+ note(e);}self.manager_for_config(&config).uninstall()?;std::fs::remove_dir_all(&self.paths.dir)?;diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex 4071234a35..8a2f73d391 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -370,6 +370,64 @@ async fn remove_reports_a_refused_unregister_after_the_local_cleanup() {assert!(relay.machine(&id).is_some());}+/// Uninstalling the app (CUA-1521): a machine that provides Spaces is taken+/// off the relay together with each Space's own relay machine, and nothing+/// is left to run; a plain remove still refuses while it provides Spaces.+#[tokio::test]+async fn remove_for_uninstall_unregisters_the_machine_and_its_spaces_from_the_relay() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct-token", "user-1", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let status = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct-token".into()))+ .await+ .unwrap();+ let id = status.machine_id.clone().unwrap();+ // A Space it provides, attached to the relay as its own machine.+ let reg = RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "acct-token",+ &crate::relay::RegisterRequest {+ id: "space-0001".into(),+ name: "lin-local".into(),+ host: Some(id.clone()),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ crate::provided::save_provided(+ &host.paths().dir,+ &[crate::provided::ProvidedSpace {+ relay_machine: "space-0001".into(),+ local_space: "local:lin-local".into(),+ name: "lin-local".into(),+ machine_token: reg.machine_token,+ relay_url: relay.url.clone(),+ ..Default::default()+ }],+ )+ .unwrap();+ assert!(relay.machine("space-0001").is_some());++ assert!(matches!(+ host.remove().await.unwrap_err(),+ Error::InvalidArgument(_)+ ));+ assert!(+ relay.machine(&id).is_some(),+ "a refused remove changes nothing"+ );++ host.remove_for_uninstall().await.unwrap();+ assert!(relay.machine(&id).is_none(), "the host is off the relay");+ assert!(relay.machine("space-0001").is_none(), "so is its Space");+ assert!(!host.paths().dir.exists());+ assert!(!f.manager.state().installed, "the service is gone");+}+#[tokio::test]async fn status_shows_recent_access_and_who_is_connected_in_direct_mode() {let f = fixture();diff --git a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rsindex 8f97063a63..34094938b1 100644--- a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs+++ b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs@@ -253,9 +253,7 @@ impl DaemonBackend {let Some(home) = self.host.home_dir() else {return;};- let root = home.join(cua_teleport_bundle::layout::firefox::root_for(- self.platform,- ));+ let root = ff::app_data_dir(&home, self.platform);let Some(profile) = ff::default_profile(&root) else {notes.push("no Firefox profile was found".into());return;diff --git a/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs b/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rsindex 3addbbd9df..33f1e4c36a 100644--- a/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/teleport_app.rs@@ -16,18 +16,16 @@ use crate::Teleport;use cua_sdk::{CuaError, Result};pub(crate) fn ux_err(e: UxError) -> CuaError {- {- let m = e.to_string();- match e {- UxError::Unsupported(_) => CuaError::Unsupported(m),- UxError::Invalid(_) => CuaError::InvalidArgument(m),- // Its own words: the error says "teleport refused:" itself.- UxError::NotApproved(why) => CuaError::TeleportRefused(why),- UxError::PermissionDenied(_) | UxError::HostEffectsRefused(_) => {- CuaError::PermissionDenied(m)- }- UxError::Io(_) => CuaError::Internal(m),- }+ // The SDK error adds the same prefix as the UX one ("invalid argument:",+ // "unsupported:", "permission denied:"), so those carry the bare message+ // (it read "invalid argument: invalid argument: ..." before).+ match e {+ UxError::Unsupported(m) => CuaError::Unsupported(m),+ UxError::Invalid(m) => CuaError::InvalidArgument(m),+ UxError::NotApproved(m) => CuaError::TeleportRefused(m),+ UxError::PermissionDenied(m) => CuaError::PermissionDenied(m),+ e @ UxError::HostEffectsRefused(_) => CuaError::PermissionDenied(e.to_string()),+ e @ UxError::Io(_) => CuaError::Internal(e.to_string()),}}diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex af9a1b9b40..2ad1f0171e 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -748,8 +748,21 @@ impl Spaces {Ok(info)}).collect::<Result<_>>()?;+ // A Space this machine provides is in the registry as a local Space,+ // and its relay machine lists it again under the host: once, as the+ // local one (CUA-1527).+ let provided_here: std::collections::HashSet<String> =+ cua_host::provided::load_provided(&cua_host::Host::new(self.home_dir()).paths().dir)+ .unwrap_or_default()+ .into_iter()+ .filter(|p| out.iter().any(|i| i.id == p.local_space))+ .map(|p| p.relay_machine)+ .collect();let cache = self.inner.relay_cache.lock().expect("relay cache");for m in cache.iter() {+ if provided_here.contains(&m.id) {+ continue;+ }let mut info = relay_info(m);self.apply_reported(&mut info, m.online);if !info.host.is_empty() {diff --git a/libs/cua/crates/cua-spaces/tests/host_spaces.rs b/libs/cua/crates/cua-spaces/tests/host_spaces.rsindex 09a53ac0c2..e98a869aff 100644--- a/libs/cua/crates/cua-spaces/tests/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/tests/host_spaces.rs@@ -368,6 +368,36 @@ async fn the_host_creates_attaches_lists_and_deletes_with_an_audit() {assert_eq!(actions[3].1, "<[email protected]> (bob)");}+/// A Space this machine provides is listed once, as its local Space: its+/// relay machine (it joined the relay as its own) is not listed again under+/// the host (CUA-1527). Another device of the account still sees the relay one.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_provided_space_is_listed_once_on_the_host_that_provides_it() {+ let f = fixture(HostProfile::Spare).await;+ let attach = f.register("ada-token", "space-ada00001").await;+ let space = f.create(&ada(), "linux", attach).await.unwrap();+ f.spaces.set_relay(Some(cua_spaces::RelayAccount::new(+ &f.relay.url,+ Arc::new(StaticToken("ada-token".into())),+ )));+ let listed = f.spaces.list_all().await.unwrap();+ let ids: Vec<&str> = listed.iter().map(|s| s.id.as_str()).collect();+ assert!(ids.contains(&space.local_space.as_str()), "{ids:?}");+ assert!(+ !ids.contains(&"relay:space-ada00001"),+ "the same Space is not listed twice: {ids:?}"+ );++ // Another device of the account has no local copy: it lists the relay one.+ let (_host, other, _dir) = client_fixture(&f).await;+ let theirs = other.list_all().await.unwrap();+ assert!(+ theirs.iter().any(|s| s.id == "relay:space-ada00001"),+ "{:?}",+ theirs.iter().map(|s| &s.id).collect::<Vec<_>>()+ );+}+/// An image whose cua-spacesd predates relay_attach: the create fails/// saying the image is too old to be reached from other devices and needs/// republishing, and leaves nothing behind.diff --git a/libs/cua/crates/cua-teleport-bundle/src/layout.rs b/libs/cua/crates/cua-teleport-bundle/src/layout.rsindex ef1280f8c2..c794377c5e 100644--- a/libs/cua/crates/cua-teleport-bundle/src/layout.rs+++ b/libs/cua/crates/cua-teleport-bundle/src/layout.rs@@ -328,6 +328,24 @@ user_pref("network.proxy.socks_remote_dns", true);}}+ /// Where Firefox may keep its profiles on the machine the app is taken+ /// from, relative to the home, most likely first. Linux has several: the+ /// classic `~/.mozilla/firefox`, the XDG location current Firefox uses+ /// (`~/.config/mozilla/firefox`), Ubuntu's snap and the Flatpak. (A+ /// destination always uses [`root_for`].)+ pub fn source_roots_for(platform: Platform) -> &'static [&'static str] {+ match platform {+ Platform::MacOS => &["Library/Application Support/Firefox"],+ Platform::Linux => &[+ ".mozilla/firefox",+ ".config/mozilla/firefox",+ "snap/firefox/common/.mozilla/firefox",+ ".var/app/org.mozilla.firefox/.mozilla/firefox",+ ],+ Platform::Windows => &["AppData/Roaming/Mozilla/Firefox"],+ }+ }+/// The Firefox program on `platform`.pub fn launch_program_for(platform: Platform) -> String {match platform {@@ -897,6 +915,15 @@ mod tests {#[test]fn firefox_layout_per_platform() {assert_eq!(firefox::root_for(Platform::Linux), ".mozilla/firefox");+ assert_eq!(+ firefox::source_roots_for(Platform::Linux)[0],+ ".mozilla/firefox"+ );+ assert!(firefox::source_roots_for(Platform::Linux).contains(&".config/mozilla/firefox"));+ assert!(+ firefox::source_roots_for(Platform::Linux)+ .contains(&"snap/firefox/common/.mozilla/firefox")+ );assert_eq!(firefox::root_for(Platform::MacOS),"Library/Application Support/Firefox"diff --git a/libs/cua/crates/cua-teleport/src/firefox_store.rs b/libs/cua/crates/cua-teleport/src/firefox_store.rsindex 8e8d50a484..f1010c5bb2 100644--- a/libs/cua/crates/cua-teleport/src/firefox_store.rs+++ b/libs/cua/crates/cua-teleport/src/firefox_store.rs@@ -82,6 +82,19 @@ pub fn profiles(app_data: &Path) -> Vec<FirefoxProfile> {.collect()}+/// The Firefox application-data directory under `home` on `platform`: the+/// first location with a `profiles.ini` (Linux has several, see+/// [`cua_teleport_bundle::layout::firefox::source_roots_for`]), else the+/// first one.+pub fn app_data_dir(home: &Path, platform: cua_teleport_bundle::Platform) -> PathBuf {+ let roots = cua_teleport_bundle::layout::firefox::source_roots_for(platform);+ roots+ .iter()+ .map(|r| home.join(r))+ .find(|dir| dir.join("profiles.ini").is_file())+ .unwrap_or_else(|| home.join(roots[0]))+}+/// The profile Firefox opens: the install's `Default=` in `installs.ini`,/// else the one marked `Default=1`, else the only one.pub fn default_profile(app_data: &Path) -> Option<FirefoxProfile> {diff --git a/libs/cua/crates/cua-teleport/src/providers/firefox.rs b/libs/cua/crates/cua-teleport/src/providers/firefox.rsindex 27b129ba22..ada72dc257 100644--- a/libs/cua/crates/cua-teleport/src/providers/firefox.rs+++ b/libs/cua/crates/cua-teleport/src/providers/firefox.rs@@ -19,7 +19,7 @@ use std::sync::Arc;use crate::bundle::{BundleWriter, DEFAULT_MAX_TOTAL_BYTES};use crate::host::{HostEffects, default_host};use crate::layout::firefox::{- APP_IDS as FIREFOX_APP_IDS, BUNDLE_PREFIX, PROFILE_DIRS, PROFILE_FILES, TABS_JSON, root_for,+ APP_IDS as FIREFOX_APP_IDS, BUNDLE_PREFIX, PROFILE_DIRS, PROFILE_FILES, TABS_JSON,};use crate::providers::util::{add_dir_recursive, add_file_best_effort, dir_len, file_len};use crate::{@@ -87,7 +87,7 @@ impl FirefoxProvider {if let Some(dir) = &self.profile_dir_override {return Some(dir.clone());}- let root = self.host.home_dir()?.join(root_for(platform));+ let root = crate::firefox_store::app_data_dir(&self.host.home_dir()?, platform);resolve_active_profile(&root)}}@@ -835,7 +835,11 @@ mod tests {fn resolves_the_active_profile_under_the_host_home() {use crate::host::FakeHost;let home = tempfile::tempdir().unwrap();- let root = home.path().join(root_for(Platform::Linux));+ let root = home+ .path()+ .join(cua_teleport_bundle::layout::firefox::root_for(+ Platform::Linux,+ ));std::fs::create_dir_all(&root).unwrap();let src = fake_profile();// Move the fake tree under the fake home's Linux Firefox root.@@ -850,6 +854,44 @@ mod tests {);}+ /// Current Firefox on Linux keeps its profile under `~/.config/mozilla/firefox`,+ /// Ubuntu's snap under `~/snap/firefox/common/.mozilla/firefox` (CUA-1524):+ /// either is found, and the classic `~/.mozilla/firefox` still wins when it has a profile.+ #[test]+ fn finds_the_profile_in_the_xdg_snap_and_flatpak_locations() {+ use crate::host::FakeHost;+ for rel in [+ ".config/mozilla/firefox",+ "snap/firefox/common/.mozilla/firefox",+ ".var/app/org.mozilla.firefox/.mozilla/firefox",+ ] {+ let home = tempfile::tempdir().unwrap();+ let root = home.path().join(rel);+ std::fs::create_dir_all(&root).unwrap();+ let src = fake_profile();+ for entry in ["profiles.ini", "Profiles"] {+ std::fs::rename(src.path().join(entry), root.join(entry)).unwrap();+ }+ let provider = FirefoxProvider::new()+ .with_host(std::sync::Arc::new(FakeHost::new().with_home(home.path())));+ assert_eq!(+ provider.source_profile_dir(Platform::Linux),+ Some(root.join("Profiles/abc.default-release")),+ "{rel}"+ );+ let manifest = provider+ .manifest(&app(Platform::Linux), None, TransferScope::FullProfile)+ .unwrap();+ assert!(+ manifest+ .items+ .iter()+ .any(|i| i.rel_path.ends_with("cookies.sqlite")),+ "{rel}: the manifest lists the signed-in state"+ );+ }+ }+#[test]fn selected_export_captures_only_checked_items() {let dir = fake_profile();diff --git a/libs/cua/crates/cua-teleport/src/ux/plan.rs b/libs/cua/crates/cua-teleport/src/ux/plan.rsindex 60c63af16c..14ec56f190 100644--- a/libs/cua/crates/cua-teleport/src/ux/plan.rs+++ b/libs/cua/crates/cua-teleport/src/ux/plan.rs@@ -591,7 +591,16 @@ pub fn build(}};if selected.is_empty() {- return Err(UxError::Invalid("select at least one state item".into()));+ // Nothing to pick from: the app has no profile where Cua looks (a+ // sandboxed or relocated install), which is not the user's choice.+ return Err(UxError::Invalid(if m.items.is_empty() {+ format!(+ "no {} sign-in data was found on this computer; move just the app instead",+ m.app_display_name+ )+ } else {+ "select at least one state item".into()+ }));}for i in &selected {let count = match (i.count, &i.count_noun) {diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex b634c0f298..13d70f625f 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -9867,6 +9867,17 @@"repeatable": false,"short_name": "f","takes_value": false+ },+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "For an uninstall of Cua Spaces: turns off the Spaces this machine provides and takes them off the relay too, instead of refusing while it provides any. The Spaces and their data stay on this machine",+ "hidden": false,+ "name": "uninstalling",+ "repeatable": false,+ "short_name": null,+ "takes_value": false}],"hidden": false,