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.

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

/**
 * New Space on the real screen: every distinct wizard state a parity flow
 * reached goes on screen through `window.__cuaParity` (`showWizard`), and
 * what the screen draws must be what the core's view says: the step and its
 * title, Continue or Create and whether it can be pressed, the fields,
 * tiles and errors, the Run on menu entry by entry, the Resources lines,
 * the Summary and the address form. ("Connect a cloud" is the picker and
 * sheets of `cloudSheet`, tested in `connect-cloud.test.tsx`; the parity
 * flow of the older sheet is the native apps'.)
 */

import { expect, type Locator, type Page } from "@playwright/test";

import type { WizardEnv, WizardState, WizardView } from "../src/bridge/contracts/new-space";
import type { ParityCheckpoint } from "../src/bridge/parity";

const texts = (l: Locator) => l.evaluateAll((els) => els.map((el) => (el.textContent ?? "").replace(/\s+/g, " ").trim()));
const attrs = (l: Locator, name: string) => l.evaluateAll((els, n) => els.map((el) => el.getAttribute(n) ?? ""), name);

/** Fields the page does not draw as a row: "Add your cloud account" is the last entry of Run on. */
const LINKS = new Set(["connect-cloud"]);
const ADD_CLOUD = { id: "add:cloud", label: "Add your cloud account\u2026" };

async function expectCheckbox(box: Locator, on: boolean, enabled = true): Promise<void> {
  await expect(box).toHaveAttribute("aria-checked", String(on));
  if (enabled) await expect(box).not.toHaveAttribute("data-disabled", "");
  else await expect(box).toHaveAttribute("data-disabled", "");
}

async function expectTiles(root: Locator, id: string, tiles: WizardView["osTiles"]): Promise<void> {
  const shown = root.locator(`[data-tile^="${id}:"]`);
  await expect(shown).toHaveCount(tiles.length);
  for (const t of tiles) {
    const tile = root.locator(`[data-tile="${id}:${t.id}"]`);
    await expect(tile).toHaveText(t.title);
    await expect(tile).toHaveAttribute("aria-pressed", String(t.pressed));
    if (t.enabled) await expect(tile).toBeEnabled();
    else await expect(tile).toBeDisabled();
  }
  // The chosen tile is filled, as the native segmented control's selection:
  // its background is not the unpressed tiles'.
  const pressed = tiles.find((t) => t.pressed);
  const other = tiles.find((t) => !t.pressed && t.enabled);
  if (pressed && other) {
    const bg = (t: { id: string }) => root.locator(`[data-tile="${id}:${t.id}"]`).evaluate((el) => getComputedStyle(el).backgroundColor);
    expect(await bg(pressed)).not.toBe(await bg(other));
  }
}

/** The Run on menu, opened: each entry's id, label and whether it can be chosen. */
async function expectRunOnMenu(page: Page, v: WizardView): Promise<void> {
  await page.locator("[data-run-on]").click();
  const items = page.locator("[data-run-on-option]:visible");
  // Only with the Your cloud experiment (the core's `connect-cloud` field), last, after a rule.
  const entries = [...v.placements.map((o) => ({ id: o.id, label: o.label, enabled: o.enabled })), ...(v.fields.some((f) => f.id === "connect-cloud") ? [{ ...ADD_CLOUD, enabled: true }] : [])];
  await expect(items).toHaveCount(entries.length);
  expect(await attrs(items, "data-value")).toEqual(entries.map((o) => o.id));
  expect(await items.evaluateAll((els) => els.map((el) => el.hasAttribute("data-disabled")))).toEqual(entries.map((o) => !o.enabled));
  const labels = await items.evaluateAll((els) => els.map((el) => el.querySelector("[data-item-label]")?.textContent ?? ""));
  expect(labels).toEqual(entries.map((o) => o.label));
  await page.keyboard.press("Escape");
  await expect(items).toHaveCount(0);
}

async function checkWizard(page: Page, state: WizardState, v: WizardView, menuChanged: boolean): Promise<void> {
  const root = page.locator("[data-new-space]");
  await expect(root).toHaveAttribute("data-mode", v.mode);
  await expect(root).toHaveAttribute("data-step", String(v.step));
  await expect(root.locator("[data-wizard-title]")).toHaveText(v.title);

  const primary = root.locator("[data-wizard-primary]");
  const back = root.locator("[data-wizard-back]");
  await expect(root.locator("[data-wizard-cancel]")).toHaveText(v.labels.cancel);

  if (v.mode === "address") {
    await expect(primary).toHaveText(v.address.submitLabel);
    if (v.address.canSubmit) await expect(primary).toBeEnabled();
    else await expect(primary).toBeDisabled();
    await expect(back).toHaveText(v.labels.back);
    const address = state.address ?? { url: "", token: "", name: "" };
    await expect(root.locator('[data-address-input="address"]')).toHaveValue(address.url);
    await expect(root.locator('[data-address-input="token"]')).toHaveValue(address.token);
    await expect(root.locator('[data-address-input="address-name"]')).toHaveValue(address.name);
    await expect(root.locator('[data-address-input="address"]')).toHaveAttribute("aria-invalid", String(v.address.showInvalid));
    if (v.address.error) await expect(root.locator("[data-address-error]")).toHaveText(v.address.error);
    else await expect(root.locator("[data-address-error]")).toHaveCount(0);
    return;
  }

  await expect(primary).toHaveText(v.primaryLabel);
  if (v.step >= 3 || v.canContinue) await expect(primary).toBeEnabled();
  else await expect(primary).toBeDisabled();
  await expect(back).toHaveCount(v.showBack ? 1 : 0);
  // The step list: one entry per step, the current one marked.
  expect(await attrs(root.locator("[data-step-state]"), "data-step-state")).toEqual(v.steps.map((s) => s.state));

  const shown = v.fields.filter((f) => !f.advanced || v.advanced);
  const field = (id: string) => shown.find((f) => f.id === id);

  if (v.step === 0) {
    expect((await attrs(root.locator("[data-field]"), "data-field")).sort()).toEqual(shown.filter((f) => !LINKS.has(f.id)).map((f) => f.id).sort());
    const errors: Record<string, string> = {};
    for (const f of shown) {
      if (f.id === "image") {
        if (v.imageField.error) errors.image = v.imageField.error;
      } else if (f.error && !LINKS.has(f.id)) errors[f.id] = f.error;
    }
    const errorEls = root.locator("[data-field-error]");
    const drawn = Object.fromEntries((await attrs(errorEls, "data-field-error")).map((id, i) => [id, i]));
    const errorTexts = await texts(errorEls);
    expect(Object.fromEntries(Object.entries(drawn).map(([id, i]) => [id, errorTexts[i]!]))).toEqual(errors);

    const advanced = v.fields.some((f) => f.advanced);
    await expect(root.locator("[data-advanced-toggle]")).toHaveCount(advanced ? 1 : 0);
    if (advanced) await expect(root.locator("[data-advanced-toggle]")).toHaveAttribute("aria-expanded", String(v.advanced));

    if (field("os")) await expectTiles(root, "os", v.osTiles);
    if (field("kind")) {
      await expectTiles(root, "kind", v.kindTiles);
      // No line under Kind: why MicroVM is greyed out is Settings, Advanced's.
      await expect(root.locator("[data-kind-help]")).toHaveCount(0);
    }
    if (field("image")) {
      const input = root.locator("[data-image-input]");
      await expect(input).toHaveValue(v.imageField.text);
      await expect(input).toHaveAttribute("aria-expanded", String(v.imageField.open));
      const rows = v.imageField.open ? v.imageField.groups.flatMap((g) => g.rows) : [];
      const drawnRows = root.locator("[data-image-row]");
      expect(await attrs(drawnRows, "data-image-row")).toEqual(rows.map((r) => r.ref));
      expect(await attrs(drawnRows, "aria-selected")).toEqual(rows.map((r) => String(r.highlighted)));
    }
    if (field("placement")) {
      const chosen = v.placements.find((o) => o.selected);
      await expect(root.locator("[data-run-on]")).toHaveText(chosen?.label ?? "");
      if (menuChanged) await expectRunOnMenu(page, v);
    }
    if (field("runtime")) {
      const runtime = root.locator("[data-runtime]");
      await expect(runtime).toHaveText(v.runtimes.find((r) => r.value === v.runtime)?.label ?? "");
      if (v.runtimeEnabled) await expect(runtime).not.toHaveAttribute("data-disabled", "");
      else await expect(runtime).toHaveAttribute("data-disabled", "");
    }
    if (v.placementHint) await expect(root.locator("[data-placement-hint]")).toHaveText(v.placementHint);
  } else if (v.step === 1) {
    // A slider's number, or the field it is typed in (with why it can't be used).
    const edit = v.resourceEdit ?? null;
    const value = async (id: "cpus" | "memory" | "disk", text: string) => {
      if (edit?.field === id) {
        await expect(root.locator(`[data-value-input="${id}"]`)).toHaveValue(edit.text);
        await expect(root.locator(`[data-value-text="${id}"]`)).toHaveCount(0);
        if (edit.error) await expect(root.locator(`[data-field-error="${id}"]`)).toHaveText(edit.error);
        else await expect(root.locator(`[data-field-error="${id}"]`)).toHaveCount(0);
      } else await expect(root.locator(`[data-value-text="${id}"]`)).toHaveText(text);
    };
    const none = (id: string) => expect(root.locator(`[data-value-text="${id}"]`)).toHaveCount(0);
    if (field("cpus")) await value("cpus", v.cpusText);
    else await none("cpus");
    if (field("memory")) await value("memory", v.memoryText);
    else await none("memory");
    if (v.diskEditable) {
      await value("disk", v.diskText);
      // A typed disk value's error takes the note's place.
      const typingDisk = edit?.field === "disk" && Boolean(edit.error);
      if (v.diskNote && !typingDisk) await expect(root.locator("[data-disk-note]")).toHaveText(v.diskNote);
      await expect(root.locator("[data-disk-reset]")).toHaveCount(v.diskResetLabel && !typingDisk ? 1 : 0);
    } else await none("disk");
    if (v.gpu) {
      await expect(root.locator("[data-gpu-label]")).toHaveText(v.gpu.label);
      await expectCheckbox(root.locator("[data-gpu]"), v.gpu.on, v.gpu.enabled);
      // The label names the checkbox; why it is off only describes it.
      await expect(root.locator("[data-gpu]")).toHaveAccessibleName(v.gpu.label);
      if (!v.gpu.enabled && v.gpu.reason) {
        await expect(root.locator("[data-gpu-reason]")).toHaveText(v.gpu.reason);
        await expect(root.locator("[data-gpu]")).toHaveAccessibleDescription(v.gpu.reason);
      }
    } else await expect(root.locator("[data-gpu]")).toHaveCount(0);
    if (v.price) await expect(root.locator("[data-price]")).toHaveText(v.price);
    else await expect(root.locator("[data-price]")).toHaveCount(0);
    const facts = root.locator("[data-fact]");
    expect(await attrs(facts, "data-fact")).toEqual(v.resourceFacts.map((f) => f.id));
    expect(await texts(root.locator("[data-fact] [data-fact-value]"))).toEqual(v.resourceFacts.map((f) => f.value));
    if (v.resourcesError) await expect(root.locator("[data-resources-error]")).toHaveText(v.resourcesError);
    else await expect(root.locator("[data-resources-error]")).toHaveCount(0);
  } else if (v.step === 2) {
    await expect(root.locator("[data-name-input]")).toHaveValue(v.name);
    // Left empty, the name it gets is the placeholder.
    const placeholder = v.fields.find((f) => f.id === "name")?.placeholder;
    if (placeholder) await expect(root.locator("[data-name-input]")).toHaveAttribute("placeholder", placeholder);
    await expect(root.locator("[data-name-input]")).toHaveAttribute("aria-invalid", String(v.nameInvalid));
    if (v.nameError) await expect(root.locator('[data-field-error="name"]')).toHaveText(v.nameError);
    else await expect(root.locator('[data-field-error="name"]')).toHaveCount(0);
    await expectCheckbox(root.locator("[data-open-when-ready]"), v.openWhenReady);
    if (v.streamNote) await expect(root.locator("[data-stream-note]")).toHaveText(v.streamNote);
    else await expect(root.locator("[data-stream-note]")).toHaveCount(0);
  } else {
    // The developer-only rows sit under "Advanced" (the page's SUMMARY_ADVANCED), after the plain ones.
    const technical = new Set(["Image", "Kind", "Architecture", "Runtime"]);
    const plain = v.summary.filter((f) => !technical.has(f.label));
    const tech = v.summary.filter((f) => technical.has(f.label));
    await expect(root.locator("[data-advanced-toggle]")).toHaveCount(tech.length ? 1 : 0);
    const rowsOf = () =>
      root.locator("[data-summary-row]").evaluateAll((els) => els.map((el) => [...el.children].map((c) => c.textContent ?? "")));
    expect(await rowsOf()).toEqual((v.advanced ? [...plain, ...tech] : plain).map((f) => [f.label, f.value]));
  }
}

/** Puts each distinct New Space state on screen and checks it. */
export async function checkNewSpace(page: Page, checkpoints: ParityCheckpoint[]): Promise<number> {
  const seen = new Set<string>();
  let lastMenu = "";
  for (const cp of checkpoints) {
    if (cp.kind === "wizard") {
      const key = JSON.stringify(["wizard", cp.view, cp.state.address ?? null]);
      if (seen.has(key)) continue;
      seen.add(key);
      await page.evaluate(([state, env]) => window.__cuaParity!.showWizard(state, env), [cp.state, cp.env] as [WizardState, WizardEnv]);
      // When a typed value's field closes, the dialog (Base UI's
      // restoreFocus: "popup") takes focus back again on the next frame. Let
      // that frame pass, or on a slow one it takes focus from the next
      // state's field, whose blur commits the value.
      await page.evaluate(() => new Promise<void>((r) => requestAnimationFrame(() => r())));
      const menu = JSON.stringify(cp.view.placements);
      // The open image suggestions cover the menu; it is checked on a later state.
      const menuChanged = cp.view.mode === "create" && cp.view.step === 0 && !cp.view.imageField.open && menu !== lastMenu;
      await checkWizard(page, cp.state, cp.view, menuChanged);
      if (menuChanged && cp.view.fields.some((f) => f.id === "placement")) lastMenu = menu;
    }
  }
  return seen.size;
}