Skip to content

armgit / cua

Public Imported from GitHub
0

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

20.7 KB
Raw Blame
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.

import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import * as path from "node:path";
import { app, BrowserWindow, dialog, nativeTheme, Notification, screen, shell } from "electron";
import { initCrashReporting } from "./crash-reporting-main";
import { createBridge } from "./bridge";
import { hasBrowser } from "./browser";
import { appBuild } from "./bundle-version";
import { channel, localCuaHome } from "./channel";
import { ELECTRON_EVENT_CHANNEL } from "./channels";
import { applyChromiumKeychainSwitches } from "./chromium-keychain";
import { installGlobalShortcut, type GlobalShortcut } from "./global-shortcut";
import { applyVideoDecodeSwitches } from "./gpu";
import { menuItems, realSpaces, startHost } from "./bridge/host-start";
import { installBridgeIpc } from "./bridge/ipc";
import { installMenu } from "./menu";
import { appCoreStatePaths, migrateFromSwiftApp, SWIFT_BUNDLE_ID } from "./migrate-swift";
import { openedAtLogin } from "./login-item";
import { makeModel, readOnboardingCompleted } from "./model/environment";
import { recordLaunch, refreshAfterUpdate } from "./model/update-refresh";
import { loadNative } from "./native/load";
import { nativeDir } from "./native/location";
import { connectNotch, type NotchCore } from "./notch";
import { dropOnSpace, feedNotch, followDragReadiness, notchTeleport, notchThumbnail, openSpaceFromNotch, teleportFromNotch, type NotchFeedUi } from "./notch-feed";
import { createPipWindows } from "./pip";
import { electronKeyvaultPrompts } from "./prompts";
import { APP_ORIGIN, handleAppProtocol, registerSchemePrivileges, resolveWebRoot } from "./protocol";
import { readSettings, writeSettings } from "./settings";
import { DEEP_LINK_SCHEME, deepLinkInArgv, routeForDeepLink } from "./deep-link";
import { makeSystem } from "./system";
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, handleOverlaySurface, handleViewerKeyboard, setWindowBackground } from "./window";
import { WindowDropTargets, windowNumberOf, type DropWindow } from "./window-drop";

// Must match `appId` (Windows; macOS has the Swift app's bundle id) and the
// Linux desktop entry in electron-builder.config.cjs. Cua Spaces Local has its
// own (src/channel.ts, packaging/electron-builder.local.cjs).
const APP_USER_MODEL_ID = channel.appUserModelId;
const LINUX_ID = "cua-spaces";

/**
 * The parity flows' test switch (apps/cua-spaces-web/e2e/host.ts): no
 * native library, no daemon; the page plays the browser demo host
 * (`?bridge=demo`). A normal launch never shows sample data.
 */
const E2E_DEMO = process.env.CUA_SPACES_E2E_DEMO === "1";

if (channel.isLocal) {
  // Cua Spaces Local (a Windows build from scripts/install-local.ps1) shares nothing with the
  // released app: its own cua home, channel (ports, names, sign-in), user data and URL scheme.
  // Set before anything starts, so the native library and every child process inherit them; a
  // variable that is already set wins.
  process.env.CUA_CHANNEL = "local";
  process.env.CUA_HOME ||= localCuaHome(process.env.USERPROFILE || homedir(), process.env);
}
app.setName(channel.appName);
// Windows groups taskbar buttons and toasts by this id; the NSIS shortcuts carry the same one.
if (process.platform === "win32") app.setAppUserModelId(APP_USER_MODEL_ID);
// Linux: WM_CLASS (X11) and the Wayland app id must match the desktop entry's
// StartupWMClass and file name, or docks show a generic icon. Set before ready.
if (process.platform === "linux") {
  app.commandLine.appendSwitch("class", LINUX_ID);
  app.setDesktopName(`${LINUX_ID}.desktop`);
}
if (process.env.CUA_SPACES_USER_DATA) app.setPath("userData", process.env.CUA_SPACES_USER_DATA);
else if (channel.isLocal) app.setPath("userData", path.join(app.getPath("appData"), channel.userDataDirName));
// Crash reporting as early as the app's name and data folder are settled (Sentry keeps its queue
// and the Crashpad reports there) and before the native library loads, which reads CUA_CRASH_*.
initCrashReporting();
// The page decodes Spaces' video with WebCodecs: on the GPU where it can (gpu.ts).
applyVideoDecodeSwitches(app.commandLine, process.platform, process.env);
// macOS: Chromium's cookie key stays out of the keychain, so its prompt can't freeze the app (chromium-keychain.ts).
applyChromiumKeychainSwitches(app.commandLine, process.platform);
const VIDEO_BENCH = videoBenchEnv(process.env);
// The Spaces' viewer windows ("Open in window"); the bench's own placement is never remembered.
const viewers = createViewerWindows({ remember: !VIDEO_BENCH.bench });

/** macOS, packaged: take over the Swift app's settings once (migrate-swift.ts). */
function migrateSwiftApp() {
  if (process.platform !== "darwin" || !app.isPackaged) return;
  try {
    let defaultsXml: string | null = null;
    try {
      defaultsXml = execFileSync("/usr/bin/defaults", ["export", SWIFT_BUNDLE_ID, "-"], { encoding: "utf8", timeout: 5000 });
    } catch {
      // An empty domain: nothing to read.
    }
    const patch = migrateFromSwiftApp({
      home: process.env.HOME || homedir(),
      userData: app.getPath("userData"),
      settings: readSettings(),
      defaultsXml,
      primaryHeight: screen.getPrimaryDisplay().bounds.height,
      now: new Date(),
    });
    if (patch) writeSettings(patch);
  } catch (error) {
    console.warn("[cua-spaces] could not take over the Swift app's settings:", error);
  }
}

/** One of the app's windows as the window-drop targets see it (one per window). */
const dropWindows = new WeakMap<BrowserWindow, DropWindow>();
function dropWindow(win: BrowserWindow): DropWindow {
  let w = dropWindows.get(win);
  if (!w) {
    w = {
      destroyed: () => win.isDestroyed(),
      visible: () => win.isVisible() && !win.isMinimized(),
      contentBounds: () => win.getContentBounds(),
      zoom: () => win.webContents.getZoomFactor(),
      number: () => windowNumberOf(win.getMediaSourceId()),
      send: (event, payload) => {
        if (!win.isDestroyed()) win.webContents.send(ELECTRON_EVENT_CHANNEL, { event, payload });
      },
    };
    dropWindows.set(win, w);
  }
  return w;
}

/** The native host: the library, the model on it and the bridge. */
async function startNativeHost(showRoute: (route: string) => void, globalShortcut: GlobalShortcut | null) {
  const dir = nativeDir({
    platform: process.platform,
    arch: process.arch,
    packaged: app.isPackaged,
    resourcesPath: process.resourcesPath,
    appRoot: path.join(__dirname, ".."),
    override: process.env.CUA_SPACES_NATIVE_DIR,
  });
  // The browser sign-in's loopback listener lives as long as the app waits
  // for it (SignInRuns.timeoutMs), not the CLI's 5 minutes: a browser slow to
  // start (Edge's first run) must not find the port closed while the app
  // still offers its link.
  process.env.CUA_OIDC_LOGIN_TIMEOUT_SECS ??= "600";
  // The browser's sign-in page says where to go back to.
  process.env.CUA_AUTH_RETURN_TO ??= "Cua Spaces";
  const native = await loadNative(dir);
  // False without a browser here: the sign-in then uses the device flow.
  const openUrl = async (url: string) => {
    if (!/^https:\/\//.test(url) || !hasBrowser()) return false;
    return shell.openExternal(url).then(
      () => true,
      () => false,
    );
  };
  // Before the model loads the settings: a launch after an update refreshes the coding agents' skills.
  const core = appCoreStatePaths(app.getPath("userData"));
  // The version and build as the Swift app records them ("0.7.2 (0.7.2.41)"), so the
  // 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, relaunch: relaunchApp });
  const pip = createPipWindows();
  app.on("will-quit", () => {
    pip.closeAll();
    viewers.closeAll();
    // Closing the last window quits on Windows and Linux: send the usage
    // events still queued (at most 1 s; the rest go with the next launch).
    try {
      native.telemetryFlush(1000);
    } catch {
      // Usage data never holds up quitting.
    }
  });
  const prompts = await electronKeyvaultPrompts(native);
  // macOS: a real window dragged onto a Space tile in the main window (the
  // notch's drag monitor follows it; window-drop.ts). Which Spaces take a drop is the core's rule.
  const windowDrops =
    process.platform === "darwin"
      ? new WindowDropTargets((spaceId) => {
          const space = env.model.spaces.find((s) => s.id === spaceId);
          return !!space && native.appSpaceAcceptsDrop(space as Parameters<typeof native.appSpaceAcceptsDrop>[0]);
        })
      : null;
  const bridge = createBridge({
    model: env.model,
    supervisor: env.supervisor,
    version: app.getVersion(),
    build,
    platform: process.platform,
    env: process.env,
    system: makeSystem({ native, showRoute, webRoot: resolveWebRoot(), globalShortcut }),
    ui: {
      openSpace: (spaceId, name, os) => void viewers.open(spaceId, name, os),
      setBackground: (win, color, appearance) => {
        if (appearance) setThemeSource(appearance);
        if (win instanceof BrowserWindow) setWindowBackground(win, color);
      },
      activate: () => app.focus({ steal: true }),
      setDropTargets: (win, targets) => {
        if (!windowDrops || !(win instanceof BrowserWindow)) return;
        windowDrops.set(dropWindow(win), targets);
        if (process.env.CUA_SPACES_NOTCH_DEBUG) {
          const at = win.getContentBounds();
          console.log(`[cua-spaces] notch drop targets: ${targets.map((t) => t.spaceId).join(", ") || "none"} in window ${win.getMediaSourceId()} at ${at.x},${at.y}`);
        }
      },
      chooseFiles: async (win) => {
        // Files and folders at once where the picker allows it (macOS); Windows and Linux pick files.
        const properties: ("openFile" | "openDirectory" | "multiSelections")[] =
          process.platform === "darwin" ? ["openFile", "openDirectory", "multiSelections"] : ["openFile", "multiSelections"];
        const r = win instanceof BrowserWindow ? await dialog.showOpenDialog(win, { properties }) : await dialog.showOpenDialog({ properties });
        return r.canceled ? null : r.filePaths;
      },
      chooseProgram: async (win) => {
        const options = { properties: ["openFile", "showHiddenFiles", "treatPackageAsDirectory"] as ("openFile" | "showHiddenFiles" | "treatPackageAsDirectory")[], defaultPath: process.platform === "win32" ? undefined : "/usr/local/bin", buttonLabel: "Use" };
        const r = win instanceof BrowserWindow ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options);
        return r.canceled ? null : (r.filePaths[0] ?? null);
      },
      pip,
      ...prompts,
    },
  });
  env.model.startListPoll();
  // A deleted Space's viewer closes (a loaded list only: an empty one is a launch).
  env.model.subscribe((change) => {
    if (change === "spaces" && env.model.loaded) viewers.prune(new Set(env.model.spaces.map((s) => s.id)));
  });
  // Keyvault access is never silent: the notch indicator follows live deliveries even with no window open.
  env.model.keyvault.startPoll();
  if (refresh && env.cua) {
    const cua = env.cua;
    env.model.startup.onReady.push(() => void refreshAfterUpdate(native, cua).then((notice) => notice && env.model.show(notice, false)));
  }
  const model = env.model;
  // Running Spaces' thumbnails stay a minute or two old while the app is in
  // use (not hidden), for the notch's tiles and the page's previews.
  model.thumbnails.keepFresh(
    () => model.streamableSpaceIds,
    () => !(process.platform === "darwin" && app.isHidden()),
  );
  // Devices asking to join, the notifications feed, launch at login, the keychain prompt.
  const background = startHost(bridge.context, { onboarded: () => readOnboardingCompleted(env.onboardingPath) ?? false });

  // macOS: the notch (Cua Spaces Notch.app), fed from the model.
  const notchUi: NotchFeedUi = {
    showSpace: (spaceId, dropped) =>
      showRoute(`/spaces/${encodeURIComponent(spaceId)}${dropped?.length ? `?dropped=${encodeURIComponent(JSON.stringify(dropped))}` : ""}`),
    notify: (title, body) => {
      if (Notification.isSupported()) new Notification({ title, body, silent: true }).show();
    },
  };
  const notch = await connectNotch({
    core: native as unknown as NotchCore,
    thumbnail: notchThumbnail(model),
    actions: {
      openSpace: (spaceId) => openSpaceFromNotch(model, notchUi, spaceId),
      openMain: () => showRoute("/spaces"),
      openSettings: () => showRoute("/settings"),
      openAccess: () => showRoute("/keyvault?view=access"),
      // Hides the indicator and the tiles' key; nothing is revoked or wiped.
      dismissAccess: () => model.keyvault.dismiss(),
      // A window dragged onto a tile: the Teleport review for its app there.
      teleport: (spaceId, app) => void teleportFromNotch(model, notchUi, spaceId, app),
      drop: (spaceId, paths) => void dropOnSpace(model, notchUi, spaceId, paths),
    },
    teleport: notchTeleport(() => model.backend.teleportHandle()),
    windowTargets: windowDrops ?? undefined,
  });
  if (notch) {
    feedNotch(notch, model);
    // Window drags need the SDK: look now and whenever the launch is (again) ready, whichever of the two came first.
    followDragReadiness(notch, model.startup);
  }
  return { 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 {
  registerSchemePrivileges();

  let mainWindow: BrowserWindow | null = null;

  const showMain = () => {
    if (!mainWindow || mainWindow.isDestroyed()) {
      mainWindow = createMainWindow({ demo: E2E_DEMO, remember: !VIDEO_BENCH.bench });
      mainWindow.on("close", (event) => {
        if (closesToTray() && !isQuitting()) {
          event.preventDefault();
          mainWindow?.hide();
        }
      });
      mainWindow.on("closed", () => {
        mainWindow = null;
      });
      return mainWindow;
    }
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.show();
    mainWindow.focus();
    return mainWindow;
  };

  /** The main window on a route of the app (the notch's and the tray's clicks). */
  const showRoute = (route: string) => {
    const win = showMain();
    void win.loadURL(`${APP_ORIGIN}${route}`);
  };

  /** A host event to the main window's page once it is loaded (New Space, Settings… from the menus). */
  const tellMain = (event: string, payload: unknown = null) => {
    const fresh = !mainWindow || mainWindow.isDestroyed();
    const win = showMain();
    const send = () => {
      if (!win.isDestroyed()) win.webContents.send(ELECTRON_EVENT_CHANNEL, { event, payload });
    };
    if (fresh || win.webContents.isLoading()) win.webContents.once("did-finish-load", () => setTimeout(send, 500));
    else send();
  };
  // The page's New Space wizard; Settings (the page's own route, without reloading it).
  const newSpace = () => tellMain("spaces.newRequested", { on: null });
  const openSettings = () => tellMain("settings.openRequested");
  const gettingStarted = () => tellMain("checklist.openRequested");

  // A `cua://add/<code>` link: the app on Machines, Join with a code filled in. Links that
  // arrive before the app is ready wait for it.
  let ready = false;
  const pendingLinks: string[] = [];
  const openLink = (link: string) => {
    if (!ready) {
      pendingLinks.push(link);
      return;
    }
    const route = routeForDeepLink(link);
    if (route) {
      app.focus({ steal: true });
      showRoute(route);
    }
  };
  // Windows and Linux start a second copy with the link as an argument; macOS sends open-url.
  app.on("second-instance", (_event, argv) => {
    const link = deepLinkInArgv(argv);
    if (link) openLink(link);
    else showMain();
  });
  app.on("open-url", (event, url) => {
    event.preventDefault();
    openLink(url);
  });
  const firstLink = deepLinkInArgv(process.argv);
  if (firstLink) pendingLinks.push(firstLink);

  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 });
    handleViewerKeyboard();
    if (process.platform !== "darwin") {
      handleOverlayDim();
      handleOverlaySurface();
    }
    const { webRoot } = handleAppProtocol();
    if (process.env.CUA_SPACES_LOG_STARTUP) console.log(`[cua-spaces] serving ${webRoot}`);

    // ⌘⇧Space from any app: the main window, in front (never under the e2e switch).
    const shortcut = E2E_DEMO
      ? null
      : installGlobalShortcut(
          process.platform,
          () => {
            app.focus({ steal: true });
            showMain();
          },
          { read: () => readSettings().globalShortcut, write: (accelerator) => writeSettings({ globalShortcut: accelerator }) },
        );
    let host: Awaited<ReturnType<typeof startNativeHost>> | null = null;
    if (!E2E_DEMO) {
      try {
        host = await startNativeHost(showRoute, shortcut);
      } catch (error) {
        // A broken install: say so plainly, never show the app without its data.
        const why = error instanceof Error ? error.message : String(error);
        dialog.showErrorBox(
          "Cua Spaces can't start",
          app.isPackaged
            ? `Cua Spaces could not load its native library (${why}). Reinstall Cua Spaces.`
            : `The native layer is missing or broken (${why}). Build it with \`pnpm native\` in apps/cua-spaces-desktop.`,
        );
        app.exit(1);
        return;
      }
    }
    installBridgeIpc({
      registry: host?.bridge.registry ?? null,
      events: host?.bridge.events ?? null,
      // The parity flows' traces are a Mac's: under the e2e switch the page can play another platform.
      platform: (E2E_DEMO ? demoPlatform() : null) ?? process.platform,
      videoStats: countsVideo(VIDEO_BENCH),
    });

    nativeTheme.on("updated", () => {
      for (const win of BrowserWindow.getAllWindows()) applyThemeToWindow(win);
    });

    // Opened at login once the first run is done: the menu bar item (the
    // notch, the tray) only, as after the window is closed.
    const onboarded = host ? (readOnboardingCompleted(host.env.onboardingPath) ?? false) : true;
    const main = openedAtLogin() && onboarded ? null : showMain();
    if (main && host && (VIDEO_BENCH.bench || countsVideo(VIDEO_BENCH))) {
      const model = host.env.model;
      startVideoBench(VIDEO_BENCH, {
        main,
        openSpace: (id) => {
          const s = model.spaces.find((x) => x.id === id);
          return viewers.open(id, s?.name ?? id, s ? String(s.os) : undefined);
        },
      });
    }
    installTray({
      actions: {
        open: () => void showMain(),
        route: showRoute,
        // The page's New Space wizard, once the page listens.
        newSpace,
      },
      items: () => (host ? menuItems(host.bridge.context) : null),
      spaces: () => realSpaces(host?.env.model.spaces ?? []),
      onChange: (listener) => host?.background.onMenuChange(listener) ?? (() => {}),
    });

    app.on("activate", showMain);

    // Make this app the one `cua://` links open (the installer registers it on macOS and in the Linux
    // package; Windows only learns it here). A development run is not an installed app: leave links alone.
    if (app.isPackaged) app.setAsDefaultProtocolClient(DEEP_LINK_SCHEME);
    ready = true;
    for (const link of pendingLinks.splice(0)) openLink(link);
  });

  app.on("window-all-closed", () => {
    if (process.platform !== "darwin") app.quit();
  });
}

/** `CUA_SPACES_DEMO_PLATFORM=<platform>[/<arch>]` under the e2e switch. */
function demoPlatform(): NodeJS.Platform | null {
  const os = (process.env.CUA_SPACES_DEMO_PLATFORM ?? "").split("/")[0];
  return os === "darwin" || os === "win32" || os === "linux" ? os : null;
}