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.

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

// This machine, Devices, Settings, About, launch at login, Storage, Cua
// Volume, Notifications and the first run on the real app core (`pnpm
// native`), over a fixture host, relay, daemon tools and system (the SwiftUI
// app's WebUIHostTests, BridgeContractTests, HostSetupAuthTests,
// HostSignInSharingTests, DevicesTests, LoginItemTests and UpdatesTests,
// ported): every answer in the shapes the page reads (bridge-shapes.json),
// the page's adapter reading them, and what each button does. Skipped when
// this machine's native directory was not built.
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import * as path from "node:path";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { validate, type Schema } from "../../cua-spaces-web/src/bridge/contracts/schema";
import { OP_SHAPES, SHAPE_DEFS } from "../../cua-spaces-web/src/bridge/contracts/shapes";
import { HOST_COVERAGE } from "../../cua-spaces-web/src/bridge/coverage";
import { OPERATIONS, type OpArgs, type OpName } from "../../cua-spaces-web/src/bridge/protocol";
import { createBridge, type Bridge } from "../src/bridge";
import type { BridgeEvent } from "../src/bridge/host";
import { hostParts } from "../src/bridge/host-parts";
import { isMachineDesktop, menuItems, realSpaces, startHost } from "../src/bridge/host-start";
import { AppModel } from "../src/model/app-model";
import { CloudModel } from "../src/model/cloud";
import { DevicesModel } from "../src/model/devices";
import { HostModel } from "../src/model/host";
import { StartupModel } from "../src/model/startup";
import { devDirName, nativeFiles } from "../src/native/location";
import { loadNative, type Native } from "../src/native/load";
import { FixtureAccount, FixtureSpacesBackend, FixtureTelemetry } from "./fixtures";
import { FixtureAgentSetup } from "./agents-fixtures";
import { FakeAccountTokens, FixtureDevices, FixtureHost, FixtureSystem, HOST_METHODS, HOST_OPS, sdkError } from "./host-fixtures";
import { NOT_YET } from "./not-yet";

const dir = path.resolve(__dirname, "../native", devDirName(process.platform, process.arch));
const built = existsSync(nativeFiles(dir, process.platform).library);

const SHAPES = JSON.parse(readFileSync(path.resolve(__dirname, "../../cua-spaces-web/src/bridge/contracts/bridge-shapes.json"), "utf8")) as {
  webkit: Record<string, Schema>;
  $defs: Record<string, Schema>;
};
const json = (v: unknown) => JSON.parse(JSON.stringify({ v })).v as unknown;
const shapeProblems = (method: string, answer: unknown) => validate(SHAPES.webkit[method]!, json(answer), SHAPES.$defs).map((e) => `${method} ${e}`);
const ELECTRON_ADAPTER = path.resolve(__dirname, "../../cua-spaces-web/src/bridge/adapters/electron.ts");
const pageAdapter = async (win: unknown) =>
  ((await import(/* @vite-ignore */ ELECTRON_ADAPTER)) as { createElectronAdapter(win: unknown): { call(op: string, args: unknown): Promise<unknown>; dispose?(): void } }).createElectronAdapter(win);
const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms));

/** The daemon's tools as the fixture daemon answers them. */
class ToolBackend extends FixtureSpacesBackend {
  readonly tools: [string, Record<string, unknown>][] = [];
  notifications: { id: string; at_ms: number; agent: string; kind: string; title: string; body: string; read: boolean; space?: string }[] = [
    { id: "n1", at_ms: 1000, agent: "ada", kind: "answer", title: "Done", body: "The report is ready", read: false },
  ];
  agents: unknown[] = [];
  override async tool(tool: string, args: Record<string, unknown> = {}): Promise<unknown> {
    this.tools.push([tool, args]);
    switch (tool) {
      case "volume_storage":
        return { backend: "fs", fs_path: "~/.cua/volume", s3: null, has_keys: false };
      case "volume_mount_status":
      case "volume_mount":
      case "volume_unmount":
        return { enabled: true, state: "unmounted", method: "nfs", path: "~/Cua Volume", volume_name: "Cua Volume", detail: null, settings_url: null, volume_errors: [] };
      case "volume_cache_stats":
        return { size_bytes: 10, capacity_bytes: 1024 };
      case "volume_requests":
        return { requests: [{ id: "q1", principal: "agent:ada", prefix: "public/", mode: "r", reason: "read" }] };
      case "volume_grants":
        return { grants: [] };
      case "volume_sync_status":
        return null;
      case "volume_storage_set":
        return { ok: true, reachable: true, authorized: true, versioning: true, detail: null, applied: !args.dry_run };
      case "notifications_list":
        return { notifications: this.notifications };
      case "notifications_ack": {
        // As the daemon's feed: no ids is every entry.
        const ids = Array.isArray(args.ids) ? (args.ids as string[]) : [];
        this.notifications = this.notifications.map((n) => (ids.length === 0 || ids.includes(n.id) ? { ...n, read: true } : n));
        return {};
      }
      case "persistent_agent_list":
        return { agents: this.agents };
      case "volume_approve":
      case "volume_deny":
      case "volume_revoke":
      case "volume_sync_resolve":
      case "volume_cache_set":
      case "volume_cache_clear":
        return {};
      default:
        return super.tool(tool);
    }
  }
}

describe.skipIf(!built)("This machine, Devices and Settings on the app core", () => {
  let home: string;
  let native: Native;
  const saved = { ...process.env };
  let backend: ToolBackend;
  let host: FixtureHost;
  let relay: FixtureDevices;
  let system: FixtureSystem;
  let model: AppModel;
  let bridge: Bridge;
  let events: BridgeEvent[];
  let agentSetup: FixtureAgentSetup;

  beforeAll(async () => {
    home = mkdtempSync(path.join(tmpdir(), "cua-host-bridge-"));
    Object.assign(process.env, { HOME: home, USERPROFILE: home, CUA_HOME: path.join(home, ".cua"), CUA_TELEMETRY: "0", DO_NOT_TRACK: "1", CUA_KEYCHAIN_NONINTERACTIVE: "1" });
    native = await loadNative(dir);
  });

  afterAll(() => {
    process.env = saved;
    rmSync(home, { recursive: true, force: true });
  });

  const make = async (o: { system?: FixtureSystem | null; platform?: NodeJS.Platform; servicesIn?: boolean; account?: null; build?: string } = {}) => {
    backend = new ToolBackend(native);
    host = new FixtureHost();
    relay = new FixtureDevices();
    system = new FixtureSystem(home);
    const settingsPath = path.join(mkdtempSync(path.join(home, "app-")), "app-settings.json");
    const servicesIn = o.servicesIn ?? true;
    model = new AppModel({
      native,
      backend,
      startup: new StartupModel({ kind: "ready" }),
      settingsPath,
      host: new HostModel(native, host.like, o.platform ?? "darwin"),
      devices: new DevicesModel(native, () => relay.like),
      cloud: new CloudModel(native, () => backend),
      account: o.account === null ? null : new FixtureAccount("[email protected]"),
      telemetry: new FixtureTelemetry(),
      servicesIn: () => servicesIn,
      cpus: 8,
      agentSetup: (agentSetup = new FixtureAgentSetup()),
    });
    bridge = createBridge({
      model,
      supervisor: null,
      version: "1.2.3",
      build: o.build,
      platform: o.platform ?? "darwin",
      env: { HOME: home },
      ui: { openSpace: () => {}, setBackground: () => {}, activate: () => {} },
      system: o.system === null ? undefined : (o.system ?? system),
    });
    events = [];
    bridge.events.subscribe((e) => events.push(e));
    await model.devices.refresh();
  };

  beforeEach(() => make());

  const call = (method: string, args: Record<string, unknown> = {}) => bridge.registry.handle(method, args);
  const reply = (method: string, args: Record<string, unknown> = {}) => bridge.registry.dispatch({ id: "x", method, args });
  const code = async (method: string, args: Record<string, unknown> = {}) => {
    const r = await reply(method, args);
    return r.ok ? null : r.error.code;
  };

  it("answers in the SwiftUI host's shapes", async () => {
    const cases: [string, Record<string, unknown>][] = [
      ["volume.overview", {}],
      ["volume.storage", {}],
      ["volume.storageSet", { update: { backend: "fs", dry_run: true } }],
      ["volume.mount", {}],
      ["volume.unmount", {}],
      ["volume.approve", { id: "q1" }],
      ["volume.deny", { id: "q1" }],
      ["volume.revoke", { id: "g1" }],
      ["volume.resolve", { path: "public/plan.md" }],
      ["volume.reveal", { path: "~/Cua Volume/public" }],
      ["about.get", {}],
      ["about.set", { channel: "nightly" }],
      ["about.checkNow", {}],
      ["update.get", {}],
      ["update.install", {}],
      ["loginItem.get", {}],
      ["loginItem.set", { on: true }],
      ["loginItem.openSettings", {}],
      ["devices.get", {}],
      ["devices.enroll", {}],
      ["devices.checkEnrolled", {}],
      ["devices.approve", { deviceId: "dev_work" }],
      ["devices.rename", { id: "dev_old", name: "Old box" }],
      ["devices.revoke", { id: "dev_old" }],
      ["devices.confirmMachine", { id: "m2" }],
      ["devices.createPairingCode", { team: null }],
      ["devices.pairingCodes", {}],
      ["devices.revokePairingCode", { id: "pc_fixture1" }],
      ["teams.list", {}],
      ["storage.get", {}],
      ["storage.run", { request: { kind: "clear-cache" } }],
      ["notifications.list", {}],
      ["notifications.markRead", { ids: ["n1"] }],
      ["notifications.markAllRead", {}],
      ["host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } }],
      ["host.action", { action: "provide-spaces" }],
      ["host.limits", { maxSpaces: 2 }],
      ["host.openSettings", { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" }],
      ["settings.get", {}],
      ["settings.choose", { row: "telemetry", option: "off" }],
      ["settings.update", { tips: { off: false, done: ["try-agent"] } }],
    ];
    const problems: string[] = [];
    for (const [method, args] of cases) problems.push(...shapeProblems(method, await call(method, args)));
    expect(problems).toEqual([]);
    // Every method of this area has its case (the first run's are checked below).
    // (host.joinWithCode runs the bundled cua: join-with-code.test.ts.)
    const checkedBelow = new Set(["onboarding.get", "onboarding.complete", "onboarding.reset", "host.joinWithCode"]);
    expect(HOST_METHODS.filter((m) => !checkedBelow.has(m) && !cases.some(([c]) => c === m))).toEqual([]);
    expect(HOST_METHODS.filter((m) => NOT_YET.includes(m))).toEqual([]);
  });

  it("reads into the page's contract through the Electron adapter", async () => {
    const win = { cuaDesktop: { invoke: (_c: string, request: unknown) => bridge.registry.dispatch(request), platform: "darwin" }, open: () => null };
    const adapter = await pageAdapter(win);
    const args: Partial<{ [K in OpName]: OpArgs<K> }> = {
      "volume.storageSet": { update: { backend: "fs", s3: null, access_key_id: null, secret_access_key: null, dry_run: true } } as never,
      "volume.approve": { id: "q1" },
      "volume.deny": { id: "q1" },
      "volume.revoke": { id: "g1" },
      "volume.resolve": { path: "public/plan.md" },
      "volume.reveal": { path: `${home}/Cua Volume/public` },
      "about.set": { autoCheck: true },
      "loginItem.set": { on: true },
      "devices.approve": { code: null, deviceId: "dev_work" },
      "devices.rename": { id: "dev_old", name: "Old box" },
      "devices.revoke": { id: "dev_old" },
      "devices.confirmMachine": { id: "m2" },
      "devices.createPairingCode": { team: null },
      "devices.revokePairingCode": { id: "pc_fixture1" },
      "notifications.markRead": { ids: ["n1"] },
      "storage.run": { request: { kind: "clear-cache" } } as never,
      "host.setUp": { request: { mode: "direct", direct: "0.0.0.0:3211" } } as never,
      "host.action": { action: "provide-spaces" } as never,
      "host.limits": { maxSpaces: 2 },
      "host.openSettings": { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" },
      "settings.set": { key: "telemetry", value: false },
      "settings.choose": { row: "auto-connect", option: "off" },
      "experiments.set": { experiments: { cuaVolume: true } } as never,
      "session.completeOnboarding": { mode: "client" },
    };
    // Every operation over this area's methods is checked here.
    const mine = OPERATIONS.filter((op) => {
      const cov = HOST_COVERAGE[op] as { webkit: { methods: readonly string[] }; electron?: { methods: readonly string[] } };
      return (cov.electron?.methods ?? cov.webkit.methods).some((m) => HOST_METHODS.includes(m) && m !== "onboarding.get");
    });
    expect(mine.filter((op) => !HOST_OPS.includes(op))).toEqual([]);
    const problems: string[] = [];
    for (const op of (HOST_OPS as OpName[]).filter((o) => o !== "host.joinWithCode")) {
      try {
        const result = await adapter.call(op, (args[op] ?? {}) as never);
        problems.push(...validate(OP_SHAPES[op], result, SHAPE_DEFS).map((e) => `${op} ${e}`));
      } catch (e) {
        problems.push(`${op} failed: ${(e as Error).message}`);
      }
    }
    adapter.dispose?.();
    expect(problems).toEqual([]);
  });

  // MARK: This machine

  it("sets this machine up and runs its buttons through the host model", async () => {
    const s = (await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } })) as Record<string, unknown>;
    expect(s).toMatchObject({ configured: true, mode: "direct", progress: null, machineId: "0123abcd4567" });
    const p = (await call("host.action", { action: "provide-spaces" })) as Record<string, unknown>;
    expect(p.provideSpaces).toBe(true);
    expect(host.calls.at(-1)).toBe("configure:-:true");
    expect(await code("host.action", { action: "set-up" })).toBe("bad_args");
    expect(await code("host.setUp", { request: {} })).toBe("bad_args");
  });

  it("changes the limits on the Spaces other machines create, and refuses a bad count", async () => {
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    const r = (await call("host.limits", { maxSpaces: 2 })) as Record<string, unknown>;
    expect(r).toMatchObject({ configured: true });
    expect(host.calls.at(-1)).toBe("configure:-:-");
    expect(await code("host.limits", { maxSpaces: -1 })).toBe("bad_args");
    expect(await code("host.limits", { maxDiskGb: "lots" })).toBe("bad_args");
  });

  it("carries the whole state, the owner and the progress", async () => {
    await call("host.setUp", { request: { mode: "relay", name: "Studio" } });
    const s = (await call("host.status")) as Record<string, unknown>;
    expect(s.maxMacosVms).toBe(2);
    expect(Array.isArray(s.recentAccess) && Array.isArray(s.providedSpaces) && Array.isArray(s.spacesAudit)).toBe(true);
    expect(s).toMatchObject({ pausedSignedOut: false, owner: "user-1", ownerEmail: "[email protected]", progress: null });
    expect("account" in s).toBe(true);
  });

  it("words a failed setup as the native form does", async () => {
    host.script = [sdkError("Http", "error sending request for url (https://relay.cua.ai): connection refused")];
    const r = await reply("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    expect(r.ok).toBe(false);
    if (r.ok) return;
    expect(r.error).toMatchObject({
      code: "failed",
      title: "Couldn’t connect",
      message: "Cua Spaces couldn’t reach the internet. Check your connection and try again.",
      actionLabel: "Retry",
    });
    expect(r.error.details).toContain("connection refused");
  });

  it("words a failed button with the raw error as details, and Retry runs it again", async () => {
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    host.failConfigure = "local runtime: service: launchctl bootstrap failed: 5";
    const r = await reply("host.action", { action: "provide-spaces" });
    expect(r.ok ? null : r.error).toMatchObject({ code: "failed", title: "Couldn’t start the Cua host service", actionLabel: "Retry" });
    expect(r.ok ? "" : r.error.details).toContain("launchctl bootstrap failed");
    expect(model.host.actionFailure?.kind).toBe("service");
    await model.host.retryFailedAction();
    expect(model.host.actionFailure).toBeNull();
    expect(host.calls.filter((c) => c.startsWith("configure:"))).toHaveLength(2);
    // Errors without words of their own keep the plain envelope.
    const plain = await reply("host.action", { action: "nope" });
    expect(plain.ok ? null : plain.error.title).toBeUndefined();
  });

  it("opens only System Settings panes, and only on macOS", async () => {
    await call("host.openSettings", { url: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" });
    expect(system.opened).toEqual(["x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"]);
    expect(await code("host.openSettings", { url: "https://example.com" })).toBe("bad_args");
    await make({ platform: "win32" });
    expect(await code("host.openSettings", { url: "x-apple.systempreferences:x" })).toBe("unsupported");
  });

  it("signs in inline when relay setup has no account, with the progress line", async () => {
    const account = new FakeAccountTokens();
    account.signInGives = "tok-new";
    account.wire(model.host);
    await call("host.setUp", { request: { mode: "relay", name: "Studio" } });
    expect(account.signIns).toBe(1);
    expect(account.progressDuringSignIn).toBe(HostModel.signInProgress);
    expect(host.tokens).toEqual(["tok-new"]);
    expect(model.host.progress).toBeNull();
  });

  it("a cancelled sign-in is a sign-in failure with Sign In as its button", async () => {
    const account = new FakeAccountTokens();
    account.wire(model.host);
    const r = await reply("host.setUp", { request: { mode: "relay", name: "Studio" } });
    expect(host.tokens).toEqual([]);
    expect(r.ok ? null : r.error).toMatchObject({ title: "Sign in to Cua", actionLabel: "Sign In" });
  });

  it("refreshes a token the relay refuses once, then signs in again", async () => {
    const account = new FakeAccountTokens();
    account.token = "tok-stale";
    account.refreshed = "tok-fresh";
    account.wire(model.host);
    host.script = [sdkError("Unauthenticated", "relay: invalid account token: ExpiredSignature")];
    await call("host.setUp", { request: { mode: "relay" } });
    expect(account.reads).toEqual([false, true]);
    expect(host.tokens).toEqual(["tok-stale", "tok-fresh"]);

    await make();
    const again = new FakeAccountTokens();
    again.token = "tok-1";
    again.refreshed = "tok-2";
    again.wire(model.host);
    host.script = [sdkError("Unauthenticated", "relay: invalid account token"), sdkError("Unauthenticated", "relay: invalid account token")];
    const r = await reply("host.setUp", { request: { mode: "relay" } });
    expect(host.tokens).toEqual(["tok-1", "tok-2"]);
    expect(r.ok ? null : r.error.actionLabel).toBe("Sign In");
  });

  it("retries a network error reading the token, and offline is not signed out", async () => {
    const account = new FakeAccountTokens();
    account.token = "tok-1";
    account.failures = [sdkError("Transport", "offline"), sdkError("Timeout", "timed out")];
    account.wire(model.host);
    await call("host.setUp", { request: { mode: "relay" } });
    expect(account.reads).toHaveLength(3);
    expect(account.signIns).toBe(0);

    await make();
    const offline = new FakeAccountTokens();
    offline.failures = [0, 1, 2].map(() => sdkError("Transport", "error sending request: Network is unreachable"));
    offline.wire(model.host);
    const r = await reply("host.setUp", { request: { mode: "relay" } });
    expect(offline.signIns).toBe(0);
    expect(r.ok ? null : r.error).toMatchObject({ title: "Couldn’t connect", actionLabel: "Retry" });
  });

  it("pauses relay sharing while signed out, and Sign In resumes it", async () => {
    const account = new FakeAccountTokens();
    account.token = "tok";
    account.wire(model.host);
    model.host.currentAccount = () => ({ id: "user-1", email: "[email protected]", display: "Ada" });
    await call("host.setUp", { request: { mode: "relay" } });
    account.token = null;
    await model.host.reconcileAccount();
    let s = (await call("host.status")) as Record<string, unknown>;
    expect(s.pausedSignedOut).toBe(true);
    expect(host.calls).toContain("pause");
    account.signInGives = "tok-again";
    s = (await call("host.action", { action: "sign-in" })) as Record<string, unknown>;
    expect(account.signIns).toBe(1);
    expect(host.calls.at(-1)).toBe("resume:user-1");
    expect(s.pausedSignedOut).toBe(false);
  });

  it("moves the host to another account that signs in, with no manual step", async () => {
    const account = new FakeAccountTokens();
    account.token = "tok";
    account.wire(model.host);
    model.host.currentAccount = () => ({ id: "user-1", email: "[email protected]", display: "Ada" });
    await call("host.setUp", { request: { mode: "relay" } });
    account.token = null;
    await model.host.reconcileAccount();
    expect(host.calls).toContain("pause");
    account.signInGives = "tok-bob";
    model.host.currentAccount = () => ({ id: "user-2", email: "[email protected]", display: "Bob" });
    const s = (await call("host.action", { action: "sign-in" })) as Record<string, unknown>;
    expect(host.calls.at(-1)).toBe("resume:user-2");
    expect(s.pausedSignedOut).toBe(false);
    expect(s.owner).toBe("user-2");
  });

  it("a failed switch leaves the host paused, and Retry never starts the old registration", async () => {
    const account = new FakeAccountTokens();
    account.token = "tok";
    account.wire(model.host);
    model.host.currentAccount = () => ({ id: "user-1", email: "[email protected]", display: "Ada" });
    await call("host.setUp", { request: { mode: "relay" } });
    host.failResume = "this computer still runs 1 Space for the account that was signed in before";
    model.host.currentAccount = () => ({ id: "user-2", email: "[email protected]", display: "Bob" });
    await model.host.reconcileAccount();
    const s = (await call("host.status")) as Record<string, unknown>;
    expect(s.pausedSignedOut).toBe(true);
    await model.host.retryFailedAction();
    expect(host.calls).not.toContain("start");
    expect(host.calls.at(-1)).toBe("resume:user-2");
  });

  it("without an account wired, Sign In leaves the status as it is", async () => {
    await make({ account: null });
    await call("host.status");
    const s = (await call("host.action", { action: "sign-in" })) as Record<string, unknown>;
    expect(s.configured).toBe(false);
  });

  it("asks for Local Network access once this machine provides Spaces", async () => {
    let asked = 0;
    model.host.localNetwork = { request: () => asked++ };
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    expect(asked).toBe(0);
    await call("host.action", { action: "provide-spaces" });
    await call("host.action", { action: "stop-providing-spaces" });
    await call("host.action", { action: "provide-spaces" });
    expect(asked).toBe(1);
  });

  // MARK: Devices

  it("shows enrollment when the relay refuses this device, then enrolls", async () => {
    relay.failSnapshot = "relay: this device is not enrolled for your cua.ai account";
    const input = (await call("devices.get")) as Record<string, unknown>;
    expect(String(input.readError)).toContain("not enrolled");
    expect(typeof input.deviceName).toBe("string");
    const r = (await call("devices.enroll")) as Record<string, unknown>;
    expect(r).toEqual({ enrolled: false, code: "K7QX-M2RP" });
    expect(model.devices.pendingCode).toBe("K7QX-M2RP");
    relay.failSnapshot = null;
    expect(((await call("devices.get")) as Record<string, unknown>).readError).toBeNull();
    relay.enrolledNow = true;
    expect(await call("devices.checkEnrolled")).toBe(true);
    expect(model.devices.pendingCode).toBeNull();
  });

  it("asks the person here before approving, naming the device", async () => {
    await call("devices.approve", { deviceId: "dev_work" });
    expect(system.asked).toEqual(["approve “Work laptop” for your Cua account"]);
    expect(relay.calls).toContain("approve:dev_work");
    system.allow = false;
    expect(await code("devices.approve", { deviceId: "dev_old" })).toBe("failed");
    expect(relay.calls.filter((c) => c.startsWith("approve:"))).toHaveLength(1);
    expect(await code("devices.approve", {})).toBe("bad_args");
  });

  it("never says approved unless the relay enrolled the device", async () => {
    relay.approveState = "pending";
    const r = await reply("devices.approve", { code: "K7QX-M2RP" });
    expect(r.ok ? "" : r.error.message).toContain("did not enroll");
  });

  it("renames with the core's clean name, revokes and confirms machines", async () => {
    await call("devices.rename", { id: "dev_old", name: "  Old box  " });
    expect(relay.calls.at(-1)).toBe("rename:dev_old:Old box");
    expect(await code("devices.rename", { id: "dev_old", name: "   " })).toBe("bad_args");
    await call("devices.revoke", { id: "dev_old" });
    await call("devices.confirmMachine", { id: "m2" });
    expect(relay.calls.slice(-2)).toEqual(["revoke:dev_old", "confirm-machine:m2"]);
  });

  it("makes, lists and revokes the codes that add a machine", async () => {
    const made = (await call("devices.createPairingCode", { team: null })) as Record<string, unknown>;
    expect(made).toMatchObject({ id: "pc_fixture1", state: "active", team: null, url: expect.stringContaining("/add/"), installSh: expect.stringContaining("--pair") });
    expect(typeof made.expiresAt).toBe("number");
    const listed = (await call("devices.pairingCodes", {})) as Record<string, unknown>[];
    expect(listed).toEqual([expect.objectContaining({ id: "pc_fixture1", code: null, url: null })]);
    expect(await call("devices.revokePairingCode", { id: "pc_fixture1" })).toBeNull();
    expect(relay.calls.slice(-3)).toEqual(["create-pairing-code:", "pairing-codes", "revoke-pairing-code:pc_fixture1"]);
  });

  it("announces a device asking to join once per launch", async () => {
    const started = startHost(bridge.context, { onboarded: () => true });
    await model.devices.refresh();
    await model.devices.refresh();
    const notes = system.notes.filter((n) => n.id.startsWith("device-"));
    expect(notes.map((n) => n.id)).toEqual(["device-dev_work", "device-dev_old"]);
    expect(notes[0]).toMatchObject({ route: "/machines" });
    expect(notes[0]!.title.length).toBeGreaterThan(0);
    started.stop();
  });

  it("needs a signed-in account", async () => {
    model.devices.devices = () => null;
    expect(await code("devices.get")).toBe("unsupported");
    expect(await code("devices.enroll")).toBe("unsupported");
  });

  // MARK: Settings

  it("lays out General with Teams, Welcome and What is collected, and the runtimes", async () => {
    const s = (await call("settings.get")) as {
      page: { sections: { id: string; rows: { id: string }[] }[] };
      updateChannel: unknown;
      globalShortcut: unknown;
    };
    const rows = s.page.sections.flatMap((x) => x.rows.map((r) => r.id));
    expect(rows).toEqual(expect.arrayContaining(["account", "notch", "auto-connect", "welcome", "teams", "teams-manage", "teams-billing", "telemetry", "telemetry-note", "launch-at-login"]));
    // One runtime row per kind, on every system.
    expect(rows).toEqual(expect.arrayContaining(["runtime:container", "runtime:vm", "runtime:microvm"]));
    expect(s.updateChannel).toBe("stable");
    // Another app holds ⌘⇧Space: the page says so.
    expect(s.globalShortcut).toEqual({ label: "\u2318\u21e7Space", registered: false });
  });

  it("changes the global shortcut from General, and says when another app holds the keys", async () => {
    await call("settings.choose", { row: "global-shortcut", option: "Control+Alt+K" });
    expect(system.shortcutChanges).toEqual(["Control+Alt+K"]);
    expect(((await call("settings.get")) as { globalShortcut: unknown }).globalShortcut).toEqual({ label: "Control+Alt+K", registered: true });
    expect(await code("settings.choose", { row: "global-shortcut", option: "Command+K" })).toBe("failed");
    expect(system.shortcutChanges).toEqual(["Control+Alt+K"]);
  });

  it("chooses each row as the Swift app does", async () => {
    let settingsEvents = 0;
    bridge.events.subscribe((e) => e.event === "settings.changed" && settingsEvents++);
    await call("settings.choose", { row: "notch", option: "hide" });
    expect(model.settings.menuBar).toBe(true);
    await call("settings.choose", { row: "auto-connect", option: "off" });
    expect(model.settings.autoConnect).toBe(false);
    await call("settings.choose", { row: "team-current", option: "org-2" });
    expect(model.settings.currentTeamId).toBe("org-2");
    await call("settings.choose", { row: "telemetry", option: "off" });
    expect(model.telemetry?.status().enabled).toBe(false);
    await call("settings.choose", { row: "launch-at-login", option: "on" });
    expect(system.loginItem.calls).toEqual(["register"]);
    expect(model.settings.launchAtLogin).toBe(true);
    await call("settings.choose", { row: "experiment:cua_volume", option: "on" });
    expect(model.settings.experiments.cuaVolume).toBe(true);
    // Storage follows General while Cua Volume is on.
    const s = (await call("settings.get")) as { page: { sections: { id: string }[] } };
    expect(s.page.sections.map((x) => x.id)).toContain("storage");
    await tick(5);
    expect(settingsEvents).toBeGreaterThan(0);
  });

  it("keeps the notch's pins in the app settings (`settings.update`), in pin order, across a restart", async () => {
    const before = (await call("settings.get")) as { notchPinned: string[] };
    expect(before.notchPinned).toEqual([]);
    const after = (await call("settings.update", { notchPinned: ["relay:wsl", "local:aurora"] })) as typeof before;
    expect(after.notchPinned).toEqual(["relay:wsl", "local:aurora"]);
    // Saved with the rest of the app's settings (a launch reads them back); the tips are untouched.
    expect(native.appSettingsLoad(model.settingsPath).notchPinned).toEqual(["relay:wsl", "local:aurora"]);
    expect(model.settings.tips).toEqual({ off: false, done: [] });
    expect(await code("settings.update", { notchPinned: "relay:wsl" })).toBe("bad_args");
    expect(await code("settings.update", { notchPinned: [1] })).toBe("bad_args");
    // The core's rule for Pin to notch: pinned last, unpinned when pinned, never This machine.
    expect(native.appNotchTogglePin(["a"], "b")).toEqual(["a", "b"]);
    expect(native.appNotchTogglePin(["a", "b"], "a")).toEqual(["b"]);
    expect(native.appNotchTogglePin([], "this-mac")).toEqual([]);
    await call("settings.update", { notchPinned: [] });
    expect(native.appSettingsLoad(model.settingsPath).notchPinned).toEqual([]);
  });

  it("keeps which coding apps the agent menu shows in the app settings (`settings.update`), across a restart", async () => {
    const before = (await call("settings.get")) as { agentMenu: { shown: string[]; hidden: string[]; seen: string[] } };
    expect(before.agentMenu).toEqual({ shown: [], hidden: [], seen: [] });
    const menu = { shown: ["goose"], hidden: ["hermes"], seen: ["claude-code|CLAUDE_CODE_OAUTH_TOKEN|"] };
    const after = (await call("settings.update", { agentMenu: menu })) as typeof before;
    expect(after.agentMenu).toEqual(menu);
    const kept = native.appSettingsLoad(model.settingsPath);
    expect([kept.agentMenuShown, kept.agentMenuHidden, kept.agentMenuSeen]).toEqual([menu.shown, menu.hidden, menu.seen]);
    expect(model.settings.tips).toEqual({ off: false, done: [] });
    expect(await code("settings.update", { agentMenu: { shown: [], hidden: "hermes", seen: [] } })).toBe("bad_args");
    expect(await code("settings.update", { agentMenu: null })).toBe("bad_args");
  });

  it("keeps the page's tips in the app settings (`settings.update`), and Show tips and Reset tips", async () => {
    const before = (await call("settings.get")) as { tips: unknown };
    expect(before.tips).toEqual({ off: false, done: [] });
    const after = (await call("settings.update", { tips: { off: false, done: ["try-agent", "power"] } })) as typeof before;
    expect(after.tips).toEqual({ off: false, done: ["try-agent", "power"] });
    // Saved with the rest of the app's settings (a launch reads them back).
    expect(native.appSettingsLoad(model.settingsPath).tips.done).toEqual(["try-agent", "power"]);
    // Only what is sent changes.
    expect(model.settings.tips.done).toEqual(["try-agent", "power"]);
    expect(await code("settings.update", {})).toBe("bad_args");
    expect(await code("settings.update", { tips: { off: "no", done: [] } })).toBe("bad_args");
    // General's Show tips (the core lays it out) and Reset tips.
    await call("settings.choose", { row: "tips", option: "off" });
    expect(model.settings.tips).toEqual({ off: true, done: ["try-agent", "power"] });
    const page = (await call("settings.get")) as { page: { sections: { rows: { id: string; options: { id: string; active: boolean }[] }[] }[] } };
    const show = page.page.sections.flatMap((s) => s.rows).find((r) => r.id === "tips")!;
    expect(show.options.find((o) => o.active)?.id).toBe("off");
    await call("settings.choose", { row: "reset-tips", option: "press" });
    expect(model.settings.tips).toEqual({ off: false, done: [] });
  });

  it("offers every experiment, and none of the switches that are gone", async () => {
    const s = (await call("settings.get")) as { experiments: { sections: { rows: { id: string }[] }[] } };
    const rows = s.experiments.sections.flatMap((x) => x.rows.map((r) => r.id));
    expect(rows).toEqual(expect.arrayContaining(["experiment:cua_volume", "experiment:secure_spaces", "experiment:warm_pools"]));
    for (const gone of ["your_cloud", "sharing", "web_ui", "classic_ui"]) expect(rows).not.toContain(`experiment:${gone}`);
  });

  it("New Space's \u201cUse built-in Lume\u201d and Settings' kind rows write the per-kind runtime settings", async () => {
    const fixture = backend as unknown as { runtimeSettings: Map<string, string> };
    // The wizard's switch (`RUNTIME_SWITCH_ROW`): the same choice as Settings, Advanced.
    const s = (await call("settings.choose", { row: "runtime:vm", option: "builtin" })) as { page: { sections: { rows: { id: string; label: string; value?: string; options: { id: string; active: boolean }[] }[] }[] } };
    expect(fixture.runtimeSettings.get("runtime.vm")).toBe("builtin");
    const rows = () => s.page.sections.flatMap((x) => x.rows);
    expect(rows().find((r) => r.id === "runtime:vm")!.options.find((o) => o.active)?.id).toBe("builtin");
    // Already installed: what is installed and the path in use.
    const t = (await call("settings.choose", { row: "runtime:container", option: "system" })) as typeof s;
    const path = t.page.sections.flatMap((x) => x.rows).find((r) => r.id === "runtime-path:container")!;
    expect([path.label, path.value]).toEqual(["Detected", "/usr/local/bin/docker"]);
    await call("settings.choose", { row: "runtime-path:container", option: "/opt/homebrew/bin/podman" });
    expect(fixture.runtimeSettings.get("runtime.container_path")).toBe("/opt/homebrew/bin/podman");
    await call("settings.choose", { row: "runtime-path:container", option: "" });
    expect(fixture.runtimeSettings.has("runtime.container_path")).toBe(false);
    // A typed path, checked before it is saved.
    expect(await call("runtimes.check", { kind: "container", path: "/usr/local/bin/docker" })).toMatchObject({ tool: "docker", version: "27.3.1" });
    // "Browse…" is the app's file panel (none in this fixture UI).
    expect(await code("runtimes.browse", { kind: "container" })).toBe("unsupported");
  });

  it("reads, changes and clears the repo cache, and refuses what is not a number of GB", async () => {
    const view = (await call("repoCache.get")) as { enabled: boolean; repos: number; bytes: number; capBytes: number; sizeSetting: string; summary: string; week: string };
    expect(view).toMatchObject({ enabled: true, repos: 3, sizeSetting: "auto", summary: "Repos: 3, 1.2 GB of 5 GB" });
    // The SDK's 64-bit sizes reach the page as numbers.
    expect(typeof view.bytes).toBe("number");
    expect(view.capBytes).toBe(5 * 1024 ** 3);
    expect(await call("repoCache.set", { enabled: false })).toMatchObject({ enabled: false, sizeSetting: "auto" });
    expect(await call("repoCache.set", { enabled: true, sizeGb: 2 })).toMatchObject({ enabled: true, sizeSetting: "2", summary: "Repos: 3, 1.2 GB of 2 GB" });
    expect(await call("repoCache.set", { sizeGb: null })).toMatchObject({ sizeSetting: "auto" });
    expect(await code("repoCache.set", { sizeGb: -1 })).toBe("bad_args");
    expect(await code("repoCache.set", { sizeGb: "lots" })).toBe("bad_args");
    expect(await code("repoCache.set", { enabled: "yes" })).toBe("bad_args");
    expect(await call("repoCache.clear")).toMatchObject({ repos: 0, bytes: 0 });
  });

  it("lists the coding agents under AI agents, and a row's button sets one up", async () => {
    const s = (await call("settings.get")) as { page: { sections: { rows: { id: string }[] }[] } };
    expect(s.page.sections.flatMap((x) => x.rows.map((r) => r.id))).toEqual(expect.arrayContaining(["agent:claude-code", "agent:codex"]));
    await call("settings.choose", { row: "agent:claude-code", option: "press" });
    expect(agentSetup.calls).toContain("setup:claude-code");
    expect(model.agents.coding.rows?.find((r) => r.agent === "claude-code")?.configured).toBe(true);
  });

  it("asks for Local Network access when a Space is created on this machine", async () => {
    let asked = 0;
    model.host.localNetwork = { request: () => asked++ };
    await call("spaces.create", { config: { image: "ghcr.io/trycua/linux:24.04", kind: "container", on: "host:mini" }, pendingId: "pending:c1", os: "linux" });
    expect(asked).toBe(0);
    await call("spaces.create", { config: { image: "ghcr.io/trycua/linux:24.04", kind: "container", on: "local" }, pendingId: "pending:l1", os: "linux" });
    expect(asked).toBe(1);
  });

  it("the notch follows the menu bar setting", async () => {
    // main.ts feeds `notch.setShown(!settings.menuBar)` on each settings change.
    const shown: boolean[] = [];
    model.subscribe((c) => c === "settings" && shown.push(!model.settings.menuBar));
    await call("settings.choose", { row: "notch", option: "hide" });
    await call("settings.choose", { row: "notch", option: "show" });
    expect(shown).toEqual([false, true]);
  });

  it("reads and chooses the update channel by row, unsupported without an updater", async () => {
    await call("settings.choose", { row: "update-channel", option: "nightly" });
    expect(system.updater.channel).toBe("nightly");
    expect(model.settings.updateChannel).toBe(native.AppUpdateChannel.Nightly);
    expect(((await call("settings.get")) as { updateChannel: string }).updateChannel).toBe("nightly");
    // A switch checks the new channel at once.
    expect(system.updater.checks).toBe(1);
    // A page from before Nightly asks for Beta: that is Nightly.
    await call("settings.choose", { row: "update-channel", option: "stable" });
    await call("settings.choose", { row: "update-channel", option: "beta" });
    expect(system.updater.channel).toBe("nightly");
    await make({ system: null });
    expect(((await call("settings.get")) as { updateChannel: unknown }).updateChannel).toBeNull();
    expect(await code("settings.choose", { row: "update-channel", option: "nightly" })).toBe("unsupported");
  });

  it("Welcome's Show again makes the first run due", async () => {
    await call("onboarding.complete", { mode: "client" });
    expect(await call("onboarding.get")).toEqual({ completed: true, mode: "client" });
    events.length = 0;
    await call("settings.choose", { row: "welcome", option: "show" });
    expect(await call("onboarding.get")).toMatchObject({ completed: false });
    expect(events.some((e) => e.event === "session.changed")).toBe(true);
  });

  it("Reset & Show forgets the first run from its first step, and says so", async () => {
    await call("onboarding.complete", { mode: "host" });
    events.length = 0;
    expect(await call("onboarding.reset")).toEqual({ completed: false, mode: "client" });
    expect(await call("onboarding.get")).toEqual({ completed: false, mode: "client" });
    expect(events.some((e) => e.event === "session.changed")).toBe(true);
    // Twice is the same as once.
    expect(await call("onboarding.reset")).toEqual({ completed: false, mode: "client" });
  });

  it("the Keyvault's switches show its state and run through the broker", async () => {
    const { FakeKeyvault, NOW, parityOverview } = await import("./vault-fixtures");
    const { KeyvaultModel } = await import("../src/model/keyvault");
    const fake = new FakeKeyvault(native, parityOverview(native));
    fake.current.status = { ...fake.current.status!, autoWipe: false, skipUnlockPrompt: false };
    (model as { keyvault: InstanceType<typeof KeyvaultModel> }).keyvault = new KeyvaultModel(native, fake, () => NOW);
    await model.keyvault.refresh();
    const s = (await call("settings.get")) as { page: { sections: { rows: { id: string }[] }[] } };
    expect(s.page.sections.flatMap((x) => x.rows.map((r) => r.id))).toEqual(expect.arrayContaining(["keyvault-auto-wipe", "keyvault-unlock-prompt"]));
    await call("settings.choose", { row: "keyvault-auto-wipe", option: "on" });
    await call("settings.choose", { row: "keyvault-unlock-prompt", option: "off" });
    expect(fake.commands.map((c) => (c as unknown as { tag: string }).tag)).toEqual(["SetAutoWipe", "SetSkipUnlockPrompt"]);
    fake.failWith = "CuaError.PermissionDenied: presence was not confirmed";
    expect(await code("settings.choose", { row: "keyvault-auto-wipe", option: "off" })).toBe("failed");
  });

  // MARK: About and launch at login

  it("About is the updater's input, and Check Now answers before the updater's window", async () => {
    const a = (await call("about.set", { autoCheck: true, channel: "nightly" })) as Record<string, unknown>;
    expect(a).toMatchObject({ autoCheck: true, channel: "nightly", updater: true, platform: "macos", version: "1.2.3" });
    expect(String(a.os)).toMatch(/\(/);
    // Switching to Nightly checked it at once.
    expect(system.updater.checks).toBe(1);
    const c = (await call("about.checkNow")) as Record<string, unknown>;
    expect(c.checking).toBe(true);
    expect(system.updater.checks).toBe(1);
    await tick(5);
    expect(system.updater.checks).toBe(2);
    expect(((await call("about.get")) as Record<string, unknown>).lastCheck).toEqual(expect.any(String));
    expect(a.build).toBe("");
    await make({ system: null });
    expect(((await call("about.get")) as Record<string, unknown>).updater).toBe(false);
    expect(await code("about.set", { autoCheck: true })).toBe("unsupported");
    expect(await code("about.checkNow")).toBe("unsupported");
  });

  it("the update indicator reads the updater, installs only when asked, and the page hears of each change", async () => {
    expect(await call("update.get")).toMatchObject({ status: "idle", version: null, percent: null });
    system.updater.report({ type: "available", version: "0.9.3" }, "found");
    system.updater.report({ type: "progress", percent: 40 });
    await tick(5);
    expect(await call("update.get")).toMatchObject({ status: "downloading", version: "0.9.3", percent: 40 });
    // Nothing is installed while it downloads, or when the page asks early.
    await call("update.install");
    await tick(5);
    expect(system.updater.installs).toBe(0);
    system.updater.report({ type: "downloaded", version: "0.9.3" }, "downloaded");
    await tick(5);
    expect(events.some((e) => e.event === "update.changed")).toBe(true);
    expect(await call("update.get")).toMatchObject({ status: "downloaded", version: "0.9.3", percent: 100, notesUrl: "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3" });
    expect(system.updater.installs).toBe(0);
    const answer = await call("update.install");
    expect((answer as { status: string }).status).toBe("downloaded");
    await tick(5);
    expect(system.updater.installs).toBe(1);
  });

  it("records found, downloaded and installed as updater steps", async () => {
    const telemetry = model.telemetry as FixtureTelemetry;
    const before = telemetry.recorded.length;
    system.updater.report({ type: "available", version: "0.9.3" }, "found");
    system.updater.report({ type: "downloaded", version: "0.9.3" }, "downloaded");
    system.updater.installNow();
    const actions = telemetry.recorded.slice(before).map((s) => (s as unknown as { inner: { action: string } }).inner.action);
    expect(actions).toEqual(["checked", "found", "downloaded", "installed"]);
  });

  it("About carries the bundle's build, for \"Version 0.7.2 (0.7.2.41)\" as the SwiftUI app shows it", async () => {
    await make({ build: "1.2.3.41" });
    expect(((await call("about.get")) as Record<string, unknown>).build).toBe("1.2.3.41");
  });

  it("records what each check found", async () => {
    const telemetry = model.telemetry as FixtureTelemetry;
    const before = telemetry.recorded.length;
    await call("about.checkNow");
    await tick(5);
    const tags = telemetry.recorded.slice(before).map((s) => (s as unknown as { inner: { action: string; trigger: string } }).inner);
    expect(tags).toEqual([
      { action: "checked", channel: "stable", trigger: "user" },
      { action: "not_found", channel: "stable", trigger: "user" },
    ]);
  });

  it("launch at login is the system's, with what this machine serves", async () => {
    expect(await call("loginItem.get")).toEqual({ status: "notRegistered", providesSpaces: false, runsAgents: false });
    backend.agents = [{ name: "ada" }];
    expect(await call("loginItem.set", { on: true })).toEqual({ status: "enabled", providesSpaces: false, runsAgents: true });
    await call("loginItem.openSettings");
    expect(system.loginItem.calls).toEqual(["register", "open-settings"]);
    system.loginItem.failure = "not allowed";
    expect(await code("loginItem.set", { on: false })).toBe("failed");
    await make({ system: null });
    expect(await code("loginItem.get")).toBe("unsupported");
  });

  it("turns launch at login on for an install that never chose and serves Spaces; a choice stands", async () => {
    const parts = hostParts(bridge.context);
    await call("host.setUp", { request: { mode: "relay", profile: "spare" } });
    expect(model.host.state?.provideSpaces).toBe(true);
    await parts.loginItem.applyAtLaunch(true);
    expect(system.loginItem.calls).toEqual(["register"]);
    expect(model.settings.launchAtLogin).toBe(true);
    system.loginItem.current = "notRegistered";
    await parts.loginItem.applyAtLaunch(true);
    expect(system.loginItem.calls).toEqual(["register"]);
  });

  // MARK: Storage, Volume, Notifications

  it("Storage answers the three tools and runs the section's commands", async () => {
    const s = (await call("storage.get")) as Record<string, unknown>;
    expect(s).toMatchObject({ os: "macos", home });
    expect(s.storage).toMatchObject({ backend: "fs" });
    await call("storage.run", { request: { kind: "set-cache", capacity_bytes: 2048 } });
    expect(backend.tools.some(([t, a]) => t === "volume_cache_set" && a.capacity_bytes === 2048)).toBe(true);
    expect(await call("storage.run", { request: { kind: "test", update: { backend: "fs", dry_run: true } } })).toMatchObject({ ok: true, applied: false });
    await call("storage.run", { request: { kind: "reveal", path: "~/Cua Volume" } });
    expect(system.revealed).toEqual([path.join(home, "Cua Volume")]);
    expect(await code("storage.run", { request: { kind: "reveal", path: "/etc/hosts" } })).toBe("bad_args");
    expect(await code("storage.run", { request: { kind: "open-url", url: "https://x" } })).toBe("bad_args");
    expect(await code("storage.run", { request: { kind: "nope" } })).toBe("bad_args");
  });

  it("the Volume reads its tools and reveals only paths in the home folder", async () => {
    const o = (await call("volume.overview")) as Record<string, unknown>;
    expect(o).toMatchObject({ os: "macos", home, grants: [], sync: null });
    expect(o.requests).toHaveLength(1);
    await call("volume.approve", { id: "q1" });
    await call("volume.resolve", { path: "public/plan.md" });
    expect(backend.tools.filter(([t]) => t === "volume_approve" || t === "volume_sync_resolve").map(([t, a]) => [t, a])).toEqual([
      ["volume_approve", { request_id: "q1" }],
      ["volume_sync_resolve", { path: "public/plan.md" }],
    ]);
    await call("volume.reveal", { path: "~/Cua Volume/public" });
    expect(system.revealed.at(-1)).toBe(path.join(home, "Cua Volume", "public"));
    expect(await code("volume.reveal", { path: "/etc/hosts" })).toBe("bad_args");
    expect(await code("volume.reveal", { path: "~/../other" })).toBe("bad_args");
  });

  it("pages without the daemon say unsupported (the store reads as none)", async () => {
    await make({ servicesIn: false });
    expect(await code("volume.overview")).toBe("unsupported");
    expect(await code("notifications.list")).toBe("unsupported");
    expect(await code("notifications.markRead", { ids: ["n1"] })).toBe("unsupported");
    expect(await code("storage.run", { request: { kind: "mount" } })).toBe("unsupported");
    expect(await call("volume.storage")).toBeNull();
  });

  it("lists the feed, posts what is new once, and marks it read", async () => {
    const parts = hostParts(bridge.context);
    const list = (await call("notifications.list")) as { id: string; read: boolean; atMs: number }[];
    expect(list).toMatchObject([{ id: "n1", read: false, atMs: 1000 }]);
    // The first read marks the feed seen without posting it (the core's first run).
    expect(system.notes).toEqual([]);
    expect(model.settings.notificationsSeenMs).toBe(1000n);
    backend.notifications = [...backend.notifications, { id: "n2", at_ms: 2000, agent: "ada", kind: "request", title: "Ada asks", body: "May I read public/?\nmore", read: false }];
    await parts.notifications.poll();
    await parts.notifications.poll();
    expect(system.notes).toEqual([{ id: "agent-n2", title: "Ada asks", body: "May I read public/?", route: "/notifications" }]);
    expect(model.settings.notificationsSeenMs).toBe(2000n);
    await call("notifications.markAllRead");
    expect(parts.notifications.feed[0]?.read).toBe(true);
  });

  it("marks one opened entry read, never all, and lists the Space each is about", async () => {
    backend.notifications = [
      { id: "n1", at_ms: 1000, agent: "ada", kind: "answer", title: "Done", body: "The report is ready", read: false, space: "local:dev" },
      { id: "n2", at_ms: 2000, agent: "ada", kind: "message", title: "Ada", body: "Second", read: false },
    ];
    type Row = { id: string; read: boolean; space: string | null; body: string };
    const list = async () => new Map(((await call("notifications.list")) as Row[]).map((r) => [r.id, r]));
    const before = await list();
    expect(before.get("n1")).toMatchObject({ space: "local:dev", read: false, body: "The report is ready" });
    expect(before.get("n2")?.space).toBeNull();

    expect(await call("notifications.markRead", { ids: ["n1"] })).toBeNull();
    expect(backend.tools.filter(([t]) => t === "notifications_ack").at(-1)).toEqual(["notifications_ack", { ids: ["n1"] }]);
    const after = await list();
    expect(after.get("n1")?.read).toBe(true);
    expect(after.get("n2")?.read).toBe(false);

    // No ids marks nothing (the daemon would read it as every entry).
    const acks = backend.tools.filter(([t]) => t === "notifications_ack").length;
    await call("notifications.markRead", { ids: [] });
    expect(backend.tools.filter(([t]) => t === "notifications_ack").length).toBe(acks);
    expect((await list()).get("n2")?.read).toBe(false);
    expect(await code("notifications.markRead", {})).toBe("bad_args");
    expect(await code("notifications.markRead", { ids: [1] })).toBe("bad_args");
  });

  // MARK: The first run

  it("is due until the page finishes it, which applies Launch at login and asks for Local Network", async () => {
    let asked = 0;
    model.host.localNetwork = { request: () => asked++ };
    expect(await call("onboarding.get")).toEqual({ completed: false, mode: "client" });
    events.length = 0;
    expect(await call("onboarding.complete", { mode: "host", launchAtLogin: true })).toEqual({ completed: true, mode: "host" });
    expect(asked).toBe(1);
    // Done is past Welcome's usage notice.
    expect((model.telemetry as FixtureTelemetry).acknowledged).toBe(1);
    expect(system.loginItem.calls).toEqual(["register"]);
    expect(model.settings.launchAtLogin).toBe(true);
    expect(events.some((e) => e.event === "session.changed")).toBe(true);
    expect(await code("onboarding.complete", { mode: "server" })).toBe("bad_args");
  });

  it("posts \"<Space> is ready\" for a create the first run started, and for no other", async () => {
    const config = { image: "ghcr.io/trycua/linux:24.04", kind: "container", on: "local" };
    await call("spaces.create", { pendingId: "pending:n1", config: { ...config, name: "quiet" }, os: "linux" });
    await call("spaces.create", { pendingId: "pending:n2", config: { ...config, name: "no" }, os: "linux", notifyWhenReady: false });
    expect(system.notes).toEqual([]);
    await call("spaces.create", { pendingId: "pending:n3", config: { ...config, name: "dev" }, os: "linux", notifyWhenReady: true });
    expect(system.notes).toEqual([
      {
        id: "space-ready-local:dev",
        title: "dev is ready",
        body: "A fresh Linux computer inside this Mac. Your agent can use it now.",
        route: "/spaces/local%3Adev",
        icon: "cua-key-128.png",
      },
    ]);
    // Without a system side (a build that has none) the create still answers.
    await make({ system: null });
    const made = (await call("spaces.create", { pendingId: "pending:n4", config: { ...config, name: "bare" }, os: "linux", notifyWhenReady: true })) as { id: string };
    expect(made.id).toBe("local:bare");
  });

  it("the page reads the first run from the session (Electron), and finishes it", async () => {
    const win = { cuaDesktop: { invoke: (_c: string, request: unknown) => bridge.registry.dispatch(request), platform: "darwin" }, open: () => null };
    const adapter = await pageAdapter(win);
    expect(await adapter.call("session.get", {})).toMatchObject({ onboarding: { completed: false, mode: "client" } });
    await adapter.call("session.completeOnboarding", { mode: "client", launchAtLogin: false });
    expect(await adapter.call("session.get", {})).toMatchObject({ onboarding: { completed: true } });
    expect(system.loginItem.calls).toEqual(["unregister"]);
    adapter.dispose?.();
  });

  // MARK: The menu bar item and the tray

  it("counts the Spaces the page lists, not the machines' own desktops", async () => {
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    backend.rowsNow = [
      ...backend.rowsNow,
      { ...backend.rowsNow[2]!, id: "relay:m1", name: "studio-mac", provider: "relay", host: undefined },
      { ...backend.rowsNow[2]!, id: "relay:m1/space-1", name: "on-studio", provider: "relay", host: "m1" },
    ];
    await model.refresh();
    const real = realSpaces(model.spaces);
    expect(real.map((s) => s.id)).not.toContain("relay:m1");
    expect(real.map((s) => s.id)).toContain("relay:m1/space-1");
    expect(model.spaces.some((s) => isMachineDesktop(s))).toBe(true);
    const items = menuItems(bridge.context);
    // The count is the Spaces on or starting among them (never a stopped one).
    expect(items[0]!.label).toBe(native.appOnStatusLine(native.appOnCount(model.spaces)));
    expect(items.map((i) => i.id)).toEqual(expect.arrayContaining(["open", "newSpace", "settings", "quit"]));
  });

  it("the home warming for Home's prompt box is in no top bar view until a person writes into it", async () => {
    const { wireView } = await import("../src/notch/core");
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    const base = backend.rowsNow[2]!;
    const home = { ...base, id: "local:home-claude-code", name: "home-claude-code", provider: "local", host: undefined, reachable: true, power: undefined, powerState: undefined };
    backend.rowsNow = [...backend.rowsNow, { ...home, hidden: true }];
    await model.refresh();
    const core = native as unknown as import("../src/notch/core").NotchCore;
    const tiles = () => {
      const shown = core.appNotchReduce(core.appNotchInitial(), { tag: "Visibility", inner: { shown: true } });
      const opened = core.appNotchReduce(shown.state, { tag: "Click" });
      return wireView(core.appNotchView(opened.state, model.spaces));
    };
    // Warming: the list the SDK returns keeps it (marked), the menu, the tray and the notch do not.
    expect(model.spaces.find((s) => s.id === home.id)?.hidden).toBe(true);
    expect(realSpaces(model.spaces).map((s) => s.id)).not.toContain(home.id);
    expect(tiles().tiles.map((t) => t.id)).not.toContain(home.id);
    const before = menuItems(bridge.context)[0]!.label;
    expect(before).toBe(native.appOnStatusLine(native.appOnCount(model.spaces)));
    // The first message: the daemon clears the mark and the next list has it.
    backend.rowsNow = backend.rowsNow.map((r) => (r.id === home.id ? { ...r, hidden: false } : r));
    await model.refresh();
    expect(realSpaces(model.spaces).map((s) => s.id)).toContain(home.id);
    expect(tiles().tiles.map((t) => t.id)).toContain(home.id);
    expect(menuItems(bridge.context)[0]!.label).not.toBe(before);
  });

  it("the notch lists the Spaces, never a machine that only provides them (CUA-1619)", async () => {
    const { wireView } = await import("../src/notch/core");
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    backend.rowsNow = [
      ...backend.rowsNow,
      { ...backend.rowsNow[2]!, id: "relay:m1", name: "studio-mac", provider: "relay", host: undefined },
      { ...backend.rowsNow[2]!, id: "relay:m1/space-1", name: "on-studio", provider: "relay", host: "m1" },
    ];
    await model.refresh();
    // What the notch helper draws (NotchModel.view): the core's view of the
    // app's Spaces (feedNotch hands it model.spaces, machines included).
    const core = native as unknown as import("../src/notch/core").NotchCore;
    const shown = core.appNotchReduce(core.appNotchInitial(), { tag: "Visibility", inner: { shown: true } });
    const opened = core.appNotchReduce(shown.state, { tag: "Click" });
    const view = wireView(core.appNotchView(opened.state, model.spaces));
    const ids = view.tiles.map((t) => t.id);
    expect(ids).toContain("relay:m1/space-1");
    expect(ids).not.toContain("relay:m1");
    expect(ids).not.toContain("this-mac");
    expect(ids.some((id) => isMachineDesktop(model.spaces.find((s) => s.id === id)!))).toBe(false);
    // The list and the menu's count are the same Spaces.
    expect(ids.sort()).toEqual(realSpaces(model.spaces).map((s) => s.id).sort());
    // The tab counts the Spaces on or starting (never a stopped one), though it lists them all.
    expect(view.tab.count).toBe(String(native.appOnCount(model.spaces)));
  });

  it("the notch lists a machine's shared desktop, counts it while it runs, and a pin puts it first and keeps it when it goes offline", async () => {
    const { wireView } = await import("../src/notch/core");
    await call("host.setUp", { request: { mode: "direct", direct: "0.0.0.0:3211" } });
    const wsl = { ...backend.rowsNow[2]!, id: "relay:wsl", name: "WSL", provider: "relay", host: undefined, features: ["desktop_stream", "window_stream", "host_spaces"], reachable: true };
    const studio = { ...backend.rowsNow[2]!, id: "relay:studio", name: "Studio", provider: "relay", host: undefined, features: ["host_spaces"], reachable: true };
    backend.rowsNow = [...backend.rowsNow, wsl, studio];
    await model.refresh();
    const core = native as unknown as import("../src/notch/core").NotchCore;
    const open = (pinned: string[]) => {
      const shown = core.appNotchReduce(core.appNotchInitial(), { tag: "Visibility", inner: { shown: true } });
      const clicked = core.appNotchReduce(shown.state, { tag: "Click" });
      const state = core.appNotchReduce(clicked.state, { tag: "Pinned", inner: { ids: pinned } }).state;
      return wireView(core.appNotchView(state, model.spaces));
    };
    // The shared desktop is a tile of its own kind; the machine that only provides Spaces is not.
    let view = open([]);
    const ids = view.tiles.map((t) => t.id);
    expect(ids).toContain("relay:wsl");
    expect(ids).not.toContain("relay:studio");
    expect(view.tiles.find((t) => t.id === "relay:wsl")).toMatchObject({ desktop: true, location: "Desktop" });
    // It counts as a running Space, as the menu's count does.
    expect(view.tab.count).toBe(String(native.appOnCount(model.spaces)));
    expect(native.appOnCount(model.spaces)).toBeGreaterThan(0);
    // Pinned: first, with the pin.
    view = open(["relay:wsl"]);
    expect(view.tiles[0]).toMatchObject({ id: "relay:wsl", pinned: true });
    // The machine goes offline: the unpinned desktop leaves, the pinned one stays dimmed and says so, and neither counts.
    const on = native.appOnCount(model.spaces);
    backend.rowsNow = backend.rowsNow.map((r) => (r.id === "relay:wsl" ? { ...r, reachable: false } : r));
    await model.refresh();
    expect(open([]).tiles.map((t) => t.id)).not.toContain("relay:wsl");
    const kept = open(["relay:wsl"]).tiles.find((t) => t.id === "relay:wsl");
    expect(kept).toMatchObject({ pinned: true, desktop: true, dim: true, note: "Offline" });
    expect(native.appOnCount(model.spaces)).toBe(on - 1);
  });

  it("says the launch is still waiting first", async () => {
    model.startup.phase = { kind: "starting" };
    const items = menuItems(bridge.context);
    expect(items[0]).toMatchObject({ id: "status", label: "Starting Cua…", enabled: false });
    expect(items[1]!.id).toBe("separator");
  });
});