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.

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

from __future__ import annotations

import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

import synth
from synth import C

PROBES = synth.PROBES
SWIFT_DIR = PROBES.parent / "swift"
PROBE_MODES = {
    "PROBE-FORMS": "forms",
    "PROBE-TABLE": "table",
    "PROBE-CANVAS": "canvas",
    "PROBE-CANVASCLICK": "canvasclick",
    "PROBE-HOVER": "hover",
    "PROBE-CLIPBOARD": "clipboard",
}
RUNS = {
    "forms": synth.forms_run,
    "table": synth.table_run,
    "canvas": synth.canvas_run,
    "canvasclick": synth.canvasclick_run,
    "hover": synth.hover_run,
    "clipboard": synth.clipboard_run,
}


class PrngTests(unittest.TestCase):
    def test_splitmix64_reference_vector(self):
        # Published splitmix64 outputs for seed 0.
        r = C.SplitMix64(0)
        self.assertEqual(r.next(), 0xE220A8397B1DCDAF)
        self.assertEqual(r.next(), 0x6E789E6AA1B965F4)
        self.assertEqual(r.next(), 0x06C45D188009454F)

    def test_seed_wraps_to_64_bits(self):
        self.assertEqual(C.SplitMix64(2**64 + 5).next(), C.SplitMix64(5).next())

    def test_derivations_are_deterministic_and_seed_sensitive(self):
        self.assertEqual(C.derive_all(123), C.derive_all(123))
        self.assertNotEqual(C.derive_forms(1), C.derive_forms(2))

    def test_randint_and_shuffle_ranges(self):
        r = C.SplitMix64(9)
        values = [r.randint(3, 6) for _ in range(500)]
        self.assertEqual(set(values), {3, 4, 5, 6})
        self.assertEqual(sorted(r.shuffled([0, 1, 2, 3, 4])), [0, 1, 2, 3, 4])

    def test_forms_derivation_constraints(self):
        for seed in range(500):
            d = C.derive_forms(seed)
            self.assertIn(d["customer_name"], C.NAMES)
            self.assertRegex(d["invoice_amount"], r"^\d{3,4}\.(00|25|50|75)$")
            self.assertTrue(200 <= float(d["invoice_amount"]) < 9801)
            self.assertTrue(1 <= d["category_index"] <= 7)  # never the default selection
            self.assertEqual(d["category_title"], C.CATEGORIES[d["category_index"]])
            self.assertIn(d["priority"], C.PRIORITIES)
            self.assertTrue(2 <= d["quantity"] <= 99)
            self.assertIn(d["notes"], C.NOTES)

    def test_table_sizes(self):
        self.assertEqual(len(C.NAMES), 20)
        self.assertEqual(len(C.CATEGORIES), 8)
        self.assertEqual(len(C.NOTES), 10)
        self.assertEqual(len(set(C.NAMES)), 20)
        self.assertEqual(len(set(C.NOTES)), 10)


class SwiftSourceTests(unittest.TestCase):
    """Cheap drift check between Swift and Python tables; see test_swift_parity for the full one."""

    @classmethod
    def setUpClass(cls):
        cls.source = (SWIFT_DIR / "BenchLab.swift").read_text("utf-8")

    def swift_list(self, name):
        match = re.search(rf"static let {name} = \[(.*?)\]\n", self.source, re.S)
        self.assertIsNotNone(match, name)
        return re.findall(r'"([^"]*)"', match.group(1))

    def test_string_tables_match(self):
        self.assertEqual(self.swift_list("names"), C.NAMES)
        self.assertEqual(self.swift_list("categories"), C.CATEGORIES)
        self.assertEqual(self.swift_list("priorities"), C.PRIORITIES)
        self.assertEqual(self.swift_list("notes"), C.NOTES)
        self.assertEqual(self.swift_list("hoverNames"), C.HOVER_NAMES)
        self.assertEqual(self.swift_list("colors"), C.COLORS)

    def test_constants_match(self):
        def const(name):
            match = re.search(rf"^let {name}(?:: CGFloat)? = (\d+)", self.source, re.M)
            self.assertIsNotNone(match, name)
            return int(match.group(1))

        self.assertEqual(const("tableRows"), C.TABLE_ROWS)
        self.assertEqual(const("canvasW"), C.CANVAS_W)
        self.assertEqual(const("canvasH"), C.CANVAS_H)
        self.assertEqual(const("zoneSize"), C.ZONE_SIZE)
        self.assertEqual(const("tileSize"), C.TILE_SIZE)
        self.assertEqual(const("columnW"), C.COLUMN_W)
        self.assertEqual(const("clickCount"), C.CLICK_COUNT)
        self.assertEqual(const("clickCols"), C.CLICK_COLS)
        self.assertEqual(const("clickCellW"), C.CLICK_CELL_W)
        self.assertEqual(const("clickCellH"), C.CLICK_CELL_H)
        self.assertEqual(const("circleRadius"), C.CIRCLE_RADIUS)

    def test_randint_ranges_match(self):
        """The draw order and ranges are hard to diff textually; pin the literal calls."""
        for snippet in (
            "r.randint(200, 9800)",
            "[0, 25, 50, 75][r.index(4)]",
            "r.randint(1, 7)",
            "r.randint(2, 99)",
            "r.randint(30, 130)",
            "r.randint(131, 260)",
            "r.randint(261, 400)",
            "r.randint(8, 129)",
            "r.randint(16, 150)",
            "r.randint(8, 169)",
            "r.randint(310, 356)",
            "r.randint(-30, 30)",
            "r.randint(-26, 26)",
            "(i / clickCols) * clickCellH + 52 + jy",
            "r.randint(0, 3)",
            "r.randint(120, 989)",
            "r.randint(11, 97)",
            "r.randint(1000, 99999)",
        ):
            self.assertIn(snippet, self.source)


@unittest.skipUnless(
    os.environ.get("BENCHLAB_PARITY") == "1", "set BENCHLAB_PARITY=1 to compile Swift and compare"
)
class SwiftParityTests(unittest.TestCase):
    def test_swift_and_python_derive_identical_parameters(self):
        with tempfile.TemporaryDirectory() as tmp:
            binary = Path(tmp) / "BenchLabDump"
            subprocess.run(
                [
                    "xcrun",
                    "swiftc",
                    "-Onone",
                    "-D",
                    "BENCHLAB_DUMP",
                    "-parse-as-library",
                    "-swift-version",
                    "5",
                    str(SWIFT_DIR / "BenchLab.swift"),
                    "-o",
                    str(binary),
                ],
                check=True,
            )
            for seed in [
                0,
                1,
                2,
                7,
                42,
                999_999,
                2**40 + 5,
                2**63 + 17,
                2**64 - 1,
                *range(100, 140),
            ]:
                out = subprocess.run(
                    [str(binary), "--dump-params", "--seed", str(seed)],
                    capture_output=True,
                    text=True,
                    check=True,
                )
                self.assertEqual(json.loads(out.stdout), C.derive_all(seed), seed)


if __name__ == "__main__":
    unittest.main()