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.2 KB
Raw Blame
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.

import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { HostError } from "../adapter";
import { createDemoAdapter } from "../adapters/demo";
import type { TelemetryView } from "../contracts/host";
import { sanitizeSignals } from "../ops/telemetry";
import { TelemetryForwarder, telemetryAllowed } from "../telemetry";
import { toMachineRows } from "../adapters/webkit";
import { machineIdOf, machinesView, rowsToSpaces, toMachines } from "../derive";
import { agentRunLines, desktopCover, PIP_CHANGED_EVENT, SpaceDetailStore, spaceDetail } from "../space-detail";
import type { CoreClient } from "../core";
import { parseDropped, sendFiles, splitDrop } from "../space-files";
import type { MachineAccessNotice } from "../contracts/devices";
import type { SpaceRow } from "../contracts/spaces";
import { testCore, wasmBuilt } from "./testCore";

const view = (enabled: boolean, noticeShown = true): TelemetryView => ({
  enabled,
  noticeShown,
  source: "config",
  sourceKind: "config",
  noticeText: "",
  docsUrl: "",
});

describe("usage events", () => {
  it("lets only schema fields and fixed words through", () => {
    expect(
      sanitizeSignals([
        { type: "step", step: "app_launched", ok: true, email: "[email protected]" },
        { type: "feature", feature: "/Users/ada" },
        { type: "space-create-started", location: "local", guestOs: "linux", kind: "container", gpu: false },
        { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "ok", failedPhase: "none", stalled: false, elapsedMs: -1, gpu: false },
        { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "ready", failedPhase: "none", stalled: false, elapsedMs: 10, gpu: false },
        { type: "space-create", location: "yours", guestOs: "windows", kind: "vm", outcome: "error", failedPhase: "booting", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "InsufficientDisk" },
        { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "error", failedPhase: "booting", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "need 52 GB" },
        { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "ok", failedPhase: "none", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "", retryAttempt: 1, errorSubclass: "runtime_start" },
        { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "ok", failedPhase: "none", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "", retryAttempt: 2, errorSubclass: "none" },
        { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "error", failedPhase: "none", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "", retryAttempt: 0, errorSubclass: "/Users/ada" },
        { type: "made-up", word: "x" },
        "step",
      ]),
    ).toEqual([
      { type: "step", step: "app_launched", ok: true },
      { type: "space-create-started", location: "local", guestOs: "linux", kind: "container", gpu: false },
      { type: "space-create", location: "yours", guestOs: "windows", kind: "vm", outcome: "error", failedPhase: "booting", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "InsufficientDisk" },
      { type: "space-create", location: "local", guestOs: "linux", kind: "vm", outcome: "ok", failedPhase: "none", stalled: false, elapsedMs: 10, gpu: false, errorVariant: "", retryAttempt: 1, errorSubclass: "runtime_start" },
    ]);
  });

  it("sends only while the setting is on and the notice was shown", async () => {
    expect(telemetryAllowed(null)).toBe(false);
    expect(telemetryAllowed(view(true, false))).toBe(false);
    const demo = createDemoAdapter({ latencyMs: 0 });
    let current = view(true);
    const f = new TelemetryForwarder(demo, async () => current);
    await f.track([{ type: "step", step: "signed_in", ok: true }]);
    current = view(false);
    await f.track([{ type: "step", step: "first_space", ok: true }]);
    expect(demo.state.telemetry).toEqual([{ type: "step", step: "signed_in", ok: true }]);
    demo.dispose?.();
  });

  it("stops asking a host with no telemetry route", async () => {
    let calls = 0;
    const host = {
      mode: "webkit" as const,
      call: async () => {
        calls++;
        throw new HostError("no route", "unsupported");
      },
      subscribe: () => () => {},
    };
    const f = new TelemetryForwarder(host as never, async () => view(true));
    await f.track([{ type: "step", step: "a", ok: true }]);
    await f.track([{ type: "step", step: "b", ok: true }]);
    expect(calls).toBe(1);
  });
});

describe("demo host: Space detail and This machine", () => {
  it("reads usage and windows for a running Space, and toggles picture in picture", async () => {
    const demo = createDemoAdapter({ latencyMs: 0 });
    const usage = await demo.call("spaces.usage", { spaceId: "local:design-review" });
    expect(usage?.memoryLimited).toBe(true);
    const { windows, display } = await demo.call("spaces.windows", { spaceId: "local:design-review" });
    expect(windows.length).toBeGreaterThan(0);
    expect(display).not.toBeNull();
    expect(await demo.call("stream.pip", { spaceId: "local:design-review", command: { type: "open", row: "desktop" } })).toEqual(["desktop"]);
    expect((await demo.call("spaces.windows", { spaceId: "local:design-review" })).open).toEqual(["desktop"]);
    expect(await demo.call("stream.pip", { spaceId: "local:design-review", command: { type: "close", row: "desktop" } })).toEqual([]);
    await expect(demo.call("spaces.windows", { spaceId: "local:agent-sandbox" })).rejects.toMatchObject({ code: "space_off" });
    demo.dispose?.();
  });

  it("follows the host's open panels on each window read (one closed by its own button, or opened from the viewer)", async () => {
    const demo = createDemoAdapter({ latencyMs: 0 });
    const core = { tryCall: () => null } as unknown as CoreClient;
    const store = new SpaceDetailStore(demo, core);
    const id = "local:design-review";
    await demo.call("stream.pip", { spaceId: id, command: { type: "open", row: "desktop" } });
    const stop = store.watch(id);
    await vi.waitFor(() => expect(store.get(id).open).toEqual(["desktop"]));
    stop();
    store.dispose();
    demo.dispose?.();
  });

  // Regression: a picture-in-picture panel closed by its own button left
  // "Playing in a floating window" on the page until the next windows read
  // (up to WINDOWS_REFRESH_MS), and the inline desktop came back late. The
  // host says so at once (`stream.pipChanged`).
  it("hears a panel the host closed by itself at once, without waiting for a windows read", () => {
    const demo = createDemoAdapter({ latencyMs: 0 });
    const core = { tryCall: () => null } as unknown as CoreClient;
    const store = new SpaceDetailStore(demo, core);
    const id = "local:design-review";
    const say = (payload: unknown) => window.dispatchEvent(new CustomEvent("cua:event", { detail: { event: PIP_CHANGED_EVENT, payload } }));
    say({ spaceId: id, open: ["desktop"] });
    expect(store.get(id).open).toEqual(["desktop"]);
    say({ spaceId: id, open: [] });
    expect(store.get(id).open).toEqual([]);
    // Malformed: ignored.
    say({ spaceId: id, open: "desktop" });
    say({ open: ["desktop"] });
    expect(store.get(id).open).toEqual([]);
    store.dispose();
    say({ spaceId: id, open: ["desktop"] });
    expect(store.get(id).open).toEqual([]);
    demo.dispose?.();
  });

  // Drift guard: the SwiftUI host sends the event the page listens for.
  it("listens for the event the SwiftUI host sends when its panels change", () => {
    const swift = readFileSync(resolve(__dirname, "../../../../cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift"), "utf8");
    expect(swift).toContain(`static let pipChangedEvent = "${PIP_CHANGED_EVENT}"`);
  });

  it("sets this machine up, stops sharing and removes the setup", async () => {
    const demo = createDemoAdapter({ latencyMs: 0, stepMs: 0 });
    expect((await demo.call("host.action", { action: "stop-sharing" })).sharing).toBe(false);
    expect((await demo.call("host.action", { action: "remove" })).configured).toBe(false);
    const set = await demo.call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3300", name: "Studio" } });
    expect(set).toMatchObject({ configured: true, mode: "direct", directUrl: "http://0.0.0.0:3300", name: "Studio" });
    const rows = await demo.call("machines.list", {});
    expect(rows.find((r) => r.current)?.host?.name).toBe("Studio");
    await expect(demo.call("host.openSettings", { url: "https://example.com" })).rejects.toMatchObject({ code: "bad_args" });
    demo.dispose?.();
  });
});

const NOTICE: MachineAccessNotice = {
  kind: "waiting",
  status: "Waiting for approval",
  text: "Waiting for approval. On an enrolled device, approve this Mac with the code K7QX-M2RP.",
  actionLabel: "Enroll This Mac\u2026",
};

describe("this device's access to its machines", () => {
  it("rides on This Mac's machine row from the SwiftUI host's machines.list", () => {
    const rows = toMachineRows({ spaces: [] } as never, { devices: null, signedIn: true, accessNotice: NOTICE });
    expect(rows.find((r) => r.current)?.accessNotice).toEqual(NOTICE);
    const machines = toMachines(rows, []);
    expect(machines.find((m) => m.current)?.accessNotice).toEqual(NOTICE);
    // Enrolled: none.
    expect(toMachineRows({ spaces: [] } as never, { devices: null, signedIn: true, accessNotice: null })[0]!.accessNotice).toBeUndefined();
  });
});

describe("this machine 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 machine, 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 machine"]);
    const machines = toMachines(rows, []);
    expect(machines).toHaveLength(1);
  });

  it("puts the Spaces this machine provides on This machine", () => {
    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 machine"]);
  });

  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 machine", "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 });

  it("greys out a machine's connection actions while this device is not enrolled, and leaves other Spaces alone", async () => {
    const core = await testCore();
    const [studio, local] = rowsToSpaces(core, [row({}), row({ id: "local:dev", name: "dev", provider: "local", os: "linux" })], 0);
    const d = spaceDetail(core, studio!, null, null, NOTICE);
    expect(d.access).toEqual(NOTICE);
    expect(d.canStream).toBe(false);
    expect(d.previewText).toBe(NOTICE.text);
    expect(d.facts.find((f) => f.label === "Status")?.value).toBe("Waiting for approval");
    expect(d.actions.filter((a) => ["teleport", "pip", "share", "open"].includes(a.id)).every((a) => !a.enabled)).toBe(true);
    expect(spaceDetail(core, local!, null, null, NOTICE).access).toBeUndefined();
  });

  it("always offers Share", async () => {
    const core = await testCore();
    const [studio] = rowsToSpaces(core, [row({})], 0);
    expect(spaceDetail(core, studio!, null, null).actions.some((a) => a.id === "share")).toBe(true);
  });

  it("explains a machine that keeps its desktop private, with no button beside the note", async () => {
    const core = await testCore();
    const [studio] = rowsToSpaces(core, [row({ features: ["host_spaces", "files"] })], 0);
    const d = spaceDetail(core, studio!, null, null);
    expect(d.desktopNote).toBe("Studio isn\u2019t sharing its desktop. You can still create Spaces on it.");
    expect(d.newSpace).toEqual({ label: "New Space on Studio\u2026", on: "host:studio" });
    expect(d.sections).toEqual([]);
  });

  it("draws the preview's cover from the core", async () => {
    const core = await testCore();
    const input = { canStream: true, previewText: "", autoConnect: true, connectRequested: false, stream: "nosession" as const };
    expect(desktopCover(core, input)).toMatchObject({ kind: "connecting", text: "Connecting\u2026", openStream: true });
    expect(desktopCover(core, { ...input, autoConnect: false })).toMatchObject({ kind: "connect", button: "Connect", openStream: false });
    expect(desktopCover(core, { ...input, stream: "failed" })).toMatchObject({ kind: "status", text: "Could not connect to the desktop", button: "Try again" });
    expect(desktopCover(core, { ...input, access: NOTICE })).toMatchObject({ kind: "connect", buttonDisabled: true, action: NOTICE.actionLabel, text: NOTICE.text });
  });
});

describe("a Space's drop well", () => {
  it("tells an app dropped on the well from the files beside it", () => {
    expect(splitDrop(["/a/notes.txt", "/Applications/Slack.app", "/a/b.png"])).toEqual({ app: "/Applications/Slack.app", files: ["/a/notes.txt", "/a/b.png"] });
    expect(splitDrop(["/a/notes.txt"])).toEqual({ app: null, files: ["/a/notes.txt"] });
    // The names the notch leaves on a Space's address are a drop, and nothing else is.
    expect(parseDropped(["Slack.app", "notes.txt"])).toEqual(["Slack.app", "notes.txt"]);
    for (const bad of [undefined, null, "Slack.app", [], [""], ["a", 3], Array.from({ length: 201 }, () => "x")]) expect(parseDropped(bad)).toBeUndefined();
  });

  it("says what it sends and what landed, or why it failed", async () => {
    const core = await testCore();
    const demo = createDemoAdapter({ latencyMs: 0 });
    const seen: string[] = [];
    await sendFiles(demo, core, "local:design-review", ["/Users/ada/notes.txt"], (s) => seen.push(`${s?.kind}: ${s?.text}`));
    expect(seen[0]).toMatch(/^working: Sending notes\.txt/);
    // The core words what landed; without it the bridge names the files.
    expect(seen[1]).toMatch(wasmBuilt ? /^done: notes\.txt .* verified in / : /^done: notes\.txt$/);
    seen.length = 0;
    await sendFiles(demo, core, "local:agent-sandbox", ["/Users/ada/notes.txt"], (s) => seen.push(s!.kind));
    expect(seen).toEqual(["working", "failed"]);
    await sendFiles(demo, core, "local:design-review", [], (s) => seen.push(s!.kind));
    expect(seen).toHaveLength(2);
    demo.dispose?.();
  });
});

describe.skipIf(!wasmBuilt)("a Space's Agents rows (wasm core)", () => {
  it("are the agent, what it was asked, and its status word", async () => {
    const core = await testCore();
    const [row] = agentRunLines(core, [{ runId: "r1", agent: "claude-code", status: "idle", reason: "waiting", summary: "Fix the tests", createdAt: null, phase: "", turn: 1 }]);
    expect(row).toMatchObject({ runId: "r1", status: "Idle", reason: "waiting" });
    expect(row!.line).toMatch(/^Claude Code · /);
  });
});

describe("the Machines page's rows from the host (machines.pageRows)", () => {
  it("lists the host's core rows as they are: devices of their own, a machine that stopped sharing", () => {
    const rows = toMachineRows(
      { spaces: [{ space: { id: "relay:b695", detail: "Not reachable" } }] } as never,
      {
        devices: { rows: [{ id: "dev_l1", name: "Laptop", platform: "macOS", current: false, detail: "macOS · Enrolled" }] },
        signedIn: true,
        thisMachine: { status: "local", statusText: "Sharing", detail: "Sharing · Relay" },
        deviceStates: { dev_l1: "enrolled" },
        rows: [
          { id: "this-mac", name: "This Mac", online: true, os: "macos", via: "local", current: true, device: "dev_me", deviceOnly: false, spaceId: "this-mac", stoppedSharing: false, lastSeen: 1799999990, status: "Online", spaces: 1, spacesLabel: "1 Space" },
          { id: "b695", name: "studio-2.local", online: true, os: "macos", via: "relay", current: false, device: "dev_s", deviceOnly: false, spaceId: "relay:b695", stoppedSharing: true, lastSeen: null, status: "Not sharing", spaces: 0, spacesLabel: "No Spaces" },
          { id: "dev_l1", name: "Laptop", online: false, os: "macos", via: "relay", current: false, device: "dev_l1", deviceOnly: true, spaceId: null, stoppedSharing: false, lastSeen: 1797000000, status: "Offline", spaces: 0, spacesLabel: "" },
        ],
      },
    );
    expect(rows.map((r) => [r.id, r.name, r.online, Boolean(r.device), r.detail])).toEqual([
      ["this-mac", "This Mac", true, false, "Sharing · Relay"],
      ["b695", "studio-2.local", true, false, "Not reachable"],
      ["dev_l1", "Laptop", false, true, "macOS · Enrolled"],
    ]);
    expect(rows[1]!.limits).not.toEqual([]);
    expect(rows[2]!.deviceState).toBe("enrolled");
    // Already each computer once: the store lists them as they are.
    const machines = toMachines(rows, []);
    expect(machines.map((m) => m.id)).toEqual(["this-mac", "b695", "dev_l1"]);
    expect(machines[2]!.device).toBe(true);
    // The core's words for each row, as the SwiftUI list shows them.
    expect(machines.map((m) => [m.status, m.spacesLabel])).toEqual([
      ["Online", "1 Space"],
      ["Not sharing", "No Spaces"],
      ["Offline", ""],
    ]);
  });
});

describe("the Machines rows listed here for an older host (machinesView)", () => {
  const desktop = (id: string, over: object = {}) =>
    ({ id: `relay:${id}`, name: id, os: "macos", status: "running", provider: "relay", sdk: { features: ["desktop_stream"], reachable: true }, ...over }) as never;
  const hosted = (id: string, n: number) => ({ id: `relay:${id}/space-${n}`, name: `s${n}`, status: "running", provider: "relay", host: id }) as never;
  const machine = (id: string, over: object = {}) => ({ id, name: id, os: "macos", via: "relay", connection: "relay", online: true, current: false, spaceIds: [], limits: [], ...over }) as never;

  /** The rows the core is asked to draw. */
  function rowsFor(machines: never[], spaces: never[]) {
    let rows: { id: string; spacesLabel: string }[] = [];
    const core = {
      tryCall: (op: string, args: { input: { rows: typeof rows } }) => {
        if (op !== "machines.view") return null;
        rows = args.input.rows;
        return {};
      },
    } as unknown as CoreClient;
    machinesView(core, { hostView: null, machines, spaces, host: null });
    return Object.fromEntries(rows.map((r) => [r.id, r.spacesLabel]));
  }

  it("says a shared desktop, a desktop with Spaces, Spaces only, and a machine that stopped sharing", () => {
    const labels = rowsFor(
      [machine("solo"), machine("both"), machine("box"), machine("stopped", { notSharing: "stopped sharing" })],
      [desktop("solo"), desktop("both"), hosted("both", 1), hosted("box", 1), hosted("box", 2), desktop("stopped", { sdk: { features: [], reachable: false, error: "stopped sharing" } })],
    );
    expect(labels).toEqual({ solo: "Desktop shared", both: "Desktop and 1 Space", box: "2 Spaces", stopped: "No Spaces" });
  });
});