Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver-bench): run the multi-app tasks CDB-G02 to CDB-G04 on Windows (#6633)
Francesco Bonacci98a8ea1fdf92
diff --git a/libs/cua-driver-bench/README.md b/libs/cua-driver-bench/README.mdindex 522068d304..b956816545 100644--- a/libs/cua-driver-bench/README.md+++ b/libs/cua-driver-bench/README.md@@ -100,8 +100,7 @@ background.per platform" in `METHOD.md`). Rerun with the version you wantto measure and record it.* **Rerun on your platform.** macOS: steps 1 to 5 under "Reproduce", one- condition per run. Linux: "Linux (the BenchLab tasks)". Windows: "Windows (the- BenchLab tasks)". Then `tools/analyze_v2.py` on the run directories. The+ condition per run. Linux: "Linux (the BenchLab tasks)". Windows: "Windows". Then `tools/analyze_v2.py` on the run directories. Themanifest decides which tasks run in which condition, so a rerun needs no tasklist.@@ -357,7 +356,7 @@ Codex computer use is not available on Linux yet([compatibility and limitations](https://learn.chatgpt.com/docs/linux/linux-app#compatibility-and-limitations)).`tests/test_linux_session.py` and `tests/test_linux_tools.py` check the session and the tools without a model.-### Windows (the BenchLab tasks)+### WindowsThe Windows port of BenchLab and the sentinel is in[`automated-eval/macos_bench/windows`](automated-eval/macos_bench/windows): Python with wxPython, so@@ -428,6 +427,49 @@ Where Windows differs:shown when BenchLab's own tooltip window is visible.* **Brief.** "on your Mac" reads "on this Windows PC".+#### Multi-app tasks on Windows (CDB-G02 to CDB-G04)++The same launcher runs the pack's multi-app tasks from each task's own+`platform/launch.windows.json` (`windows/cdb.py`): it resets the workspace with the pack's setup and+byte-level verify, starts the apps, gives each window the descriptor's bounds, runs the agent as above, then+runs the pack's evaluator and leaves the final workspace in `DIR\workspace-final.zip`. The workspace is+`%USERPROFILE%\cdb-s0N`; `{workspace}` in the agent command is filled in.++```powershell+python launch\windows_session.py --task CDB-G03 --run-index 0 --condition background --out C:\bench\CDB-G03-bg-r0 -- <agent command>+```++Install before the trials (the network can be off during them):++| Component | Version used | Where the descriptor expects it |+|---|---|---|+| Node.js | 22 or later (24.15.0 used) | `node` on `PATH` (the CDB-G04 archive site and its evaluator) |+| Electron | 43.8.1, from each app's `package-lock.json` | `npm ci` in `taskpack/tasks/shared/cdb-s0N/apps/<app>`; if npm skips Electron's install script, run `node install.js` in `node_modules\electron` |+| LibreOffice | 26.2 (26.2.6.3 used) | `C:\Program Files\LibreOffice\program` |+| GnuCash | 5.17 (`gnucash-5.17.setup.exe`, sha256 `a3e8049755e536f647640762a483ebe1b6c79cc50cc81a746fa64a404e98d271`) | `C:\Program Files (x86)\gnucash\bin\gnucash.exe` |+| Google Chrome | stable (157.0.8103.39 used) | `C:\Program Files\Google\Chrome\Application\chrome.exe` |++Where the multi-app tasks differ on Windows:++* **Electron apps.** Each app runs from a copy of the pack's own `electron.exe` named after its window title+ (`Copperfield Mail.exe`, `Rillwatch Cases.exe`, ...) in the same `dist` folder, as macOS gives each app its+ own bundle (Amendment 4): same binary, code and arguments, but a setup that names apps by process can tell+ them apart.+* **GnuCash preferences.** GnuCash keeps its preferences in the registry on Windows+ (`HKCU\Software\GSettings\org\gnucash`), outside the task workspace, so the reset deletes that key:+ every trial starts GnuCash with default preferences.+* **LibreOffice updates.** LibreOffice's Windows updater can replace the installation when Calc starts. Turn+ it off for the bench user before the trials: `org.openoffice.Office.Update/Update/Enabled` and+ `org.openoffice.Office.Jobs/Jobs/UpdateCheck/Arguments/AutoCheckEnabled` set to `false` (as+ `Software\Policies\LibreOffice` registry policies, which an administrator writes).+* **Leftovers.** Before and after a trial the launcher stops the task's own executables in the desktop+ session by exact name and whatever listens on the task's loopback port (4184 for CDB-G04).+* **Validation.** `windows\cdb_oracle.py` stands in for the agent: by default it applies the scripted+ correct solution of the pack's own test module to the workspace (the checker passes), `--noop` does+ nothing (the checker fails, the user window stays undisturbed) and `--disturb` steals focus once (the+ sentinel sees it). `tests/test_windows_cdb.py` checks the descriptors, the named executables and the+ oracle without a desktop.+### Tests```bashdiff --git a/libs/cua-driver-bench/automated-eval/macos_bench/launch/windows_session.py b/libs/cua-driver-bench/automated-eval/macos_bench/launch/windows_session.pyindex 2def1710cf..4cfca3103c 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/launch/windows_session.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/launch/windows_session.py@@ -5,13 +5,16 @@# Usage: windows_session.py --task ID --run-index N --condition foreground|background --out DIR# [--timeout S] -- COMMAND [ARG...]#-# One BenchLab trial on a Windows desktop, run in the interactive session of the user who owns it:+# One trial on a Windows desktop, run in the interactive session of the user who owns it:# 1. derive the seed (fairness rule), render the brief (+ the background paragraph), write DIR/brief.md;-# 2. start BenchLab (windows/benchlab.py) and the sentinel (windows/sentinel.py): in the background-# condition the "User activity" window partly covers BenchLab, is brought to the front and types;-# 3. arm the sentinel, run COMMAND (the agent; `{brief}`, `{out}`, `{seed}`, `{mode}` in its arguments are filled in)-# with the GUI-only guard watching, stop it at the time limit or on a violation;-# 4. disarm, run the task's checker, summarise the sentinel, write DIR/row.json.+# 2. start the task's apps: BenchLab (windows/benchlab.py) for the BenchLab tasks, or for a pack task+# (CDB-G02 to CDB-G04) reset its workspace and start the apps of its platform/launch.windows.json+# (windows/cdb.py); then the sentinel (windows/sentinel.py): in the background condition the+# "User activity" window partly covers the task's windows, is brought to the front and types;+# 3. arm the sentinel, run COMMAND (the agent; `{brief}`, `{out}`, `{seed}`, `{mode}`, `{workspace}` in its+# arguments are filled in) with the GUI-only guard watching, stop it at the time limit or on a violation;+# 4. disarm, run the task's checker, summarise the sentinel, write DIR/row.json (a pack task also leaves+# DIR/workspace-final.zip), stop the apps.# BenchLab and the sentinel run from copies of pythonw.exe named BenchLab.exe and BenchSentinel.exe, so every# tool sees them under those names.from __future__ import annotations@@ -36,7 +39,9 @@ import bench_v2 as v2 # noqa: E402import cdb_fairness # noqa: E402import summarize_sentinel # noqa: E402-TASKS = ("MB-09", "MB-10", "MB-11", "IR-01", "IR-02", "IR-03", "IR-04")+LAB_TASKS = ("MB-09", "MB-10", "MB-11", "IR-01", "IR-02", "IR-03", "IR-04")+CDB_TASKS = ("CDB-G02", "CDB-G03", "CDB-G04")+TASKS = CDB_TASKS + LAB_TASKSLAB_FRAME = (40, 40, 760, 540)WITNESS_FRAME = (1000, 640, 600, 320)PLATFORM_WORDS = ("on your Mac", "on this Windows PC")@@ -46,7 +51,9 @@ def task_spec(task: str) -> dict:return json.loads((BENCH / "probes" / task / "task.json").read_text(encoding="utf-8"))-def render_brief(task: str, seed: int, condition: str) -> str:+def render_brief(task: str, seed: int, condition: str, cdb=None) -> str:+ if cdb is not None:+ return v2.brief_for(cdb.brief().strip(), condition)spec = importlib.util.spec_from_file_location(f"render_{task}", BENCH / "probes" / task / "render_brief.py")@@ -97,9 +104,16 @@ def run(args: argparse.Namespace, command: list[str]) -> dict:out: Path = args.out.resolve()out.mkdir(parents=True, exist_ok=True)spec = task_spec(args.task)- mode = spec["app_args"][spec["app_args"].index("--mode") + 1]seed = cdb_fairness.trial_seed(args.task, args.run_index)- brief = render_brief(args.task, seed, args.condition)+ cdb = None+ if spec.get("kind") == "cdb":+ import cdb as C++ cdb = C.CdbTask(spec, out, seed=seed)+ mode = spec["pack_task"]+ else:+ mode = spec["app_args"][spec["app_args"].index("--mode") + 1]+ brief = render_brief(args.task, seed, args.condition, cdb)(out / "brief.md").write_text(brief, encoding="utf-8")background = args.condition == "background"row: dict = {@@ -113,16 +127,29 @@ def run(args: argparse.Namespace, command: list[str]) -> dict:for stale in (state, events, log, control):stale.unlink(missing_ok=True)control.write_text("", encoding="utf-8")- lab = subprocess.Popen(- [str(named_python("BenchLab")), str(BENCH / "windows" / "benchlab.py"), "--mode", mode,- "--seed", str(seed), "--state", str(state), "--events", str(events),- "--frame", ",".join(map(str, LAB_FRAME)), *(["--no-activate"] if background else [])],- ) # fmt: skip- procs = [lab]+ procs = []try:- if not wait_for(state.exists, 30):- row["harness_error"] = "BenchLab did not start"- return row+ if cdb is not None:+ row["workspace"] = str(cdb.workspace)+ try:+ cdb.reset()+ cdb.start_apps()+ cdb.place_windows()+ row["health"] = cdb.health_check()+ except Exception as error: # noqa: BLE001 - any setup failure is a harness error, never scored+ row["harness_error"] = f"setup: {type(error).__name__}: {str(error)[:400]}"+ return row+ finally:+ row["setup_log"] = list(cdb.log)+ else:+ procs.append(subprocess.Popen(+ [str(named_python("BenchLab")), str(BENCH / "windows" / "benchlab.py"), "--mode", mode,+ "--seed", str(seed), "--state", str(state), "--events", str(events),+ "--frame", ",".join(map(str, LAB_FRAME)), *(["--no-activate"] if background else [])],+ )) # fmt: skip+ if not wait_for(state.exists, 30):+ row["harness_error"] = "BenchLab did not start"+ return rowframe = v2.USER_WINDOW_FRAME if background else WITNESS_FRAMEsentinel = subprocess.Popen([str(named_python("BenchSentinel")), str(BENCH / "windows" / "sentinel.py"),@@ -152,6 +179,7 @@ def run(args: argparse.Namespace, command: list[str]) -> dict:"{out}": str(out),"{seed}": str(seed),"{mode}": mode,+ "{workspace}": str(cdb.workspace) if cdb is not None else "",}argv = []for a in command:@@ -209,12 +237,19 @@ def run(args: argparse.Namespace, command: list[str]) -> dict:wait_for(lambda: any(ln.get("ev") == "disarmed" for ln in sentinel_lines(log)), 5)time.sleep(0.3)result = out / "result.json"- subprocess.run(- [sys.executable, str(BENCH / "probes" / args.task / "evaluate.py"), "--seed", str(seed),- "--state", str(state), "--events", str(events), "--result", str(result)],- capture_output=True, timeout=60,- ) # fmt: skip- evaluation = json.loads(result.read_text(encoding="utf-8")) if result.exists() else {}+ if cdb is not None:+ evaluation = cdb.evaluate(124 if timed_out else int(agent.returncode or 0))+ result.write_text(json.dumps(evaluation, indent=1), encoding="utf-8")+ cdb.snapshot_workspace(out / "workspace-final.zip")+ if evaluation.get("harness_error"):+ row["harness_error"] = f"evaluate: {evaluation['harness_error']}"+ else:+ subprocess.run(+ [sys.executable, str(BENCH / "probes" / args.task / "evaluate.py"), "--seed", str(seed),+ "--state", str(state), "--events", str(events), "--result", str(result)],+ capture_output=True, timeout=60,+ ) # fmt: skip+ evaluation = json.loads(result.read_text(encoding="utf-8")) if result.exists() else {}transcript = out / "agent-transcript.jsonl"stream = []if transcript.exists():@@ -249,6 +284,9 @@ def run(args: argparse.Namespace, command: list[str]) -> dict:for proc in procs:if proc.poll() is None:kill_tree(proc.pid)+ if cdb is not None:+ cdb.stop_apps()+ cdb.clean_workspace()row["finished"] = time.time()(out / "row.json").write_text(json.dumps(row, indent=1), encoding="utf-8")diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_cdb.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_cdb.pynew file mode 100644index 0000000000..8b2a45cbb9--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_cdb.py@@ -0,0 +1,115 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""The Windows pack-task runner (windows/cdb.py) without a desktop: every multi-app task's Windows descriptor+resolves, Electron apps get their own named executables, leftovers are cleared by exact executable name and+port, the brief matches the macOS adapter's, and the scripted oracle passes each checker while doing nothing+fails it."""++from __future__ import annotations++import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++HERE = Path(__file__).resolve().parent+BENCH = HERE.parent+sys.path.insert(0, str(BENCH))+sys.path.insert(0, str(BENCH / "windows"))+import bench_v2 as v2 # noqa: E402+import cdb as C # noqa: E402+import cdb_oracle as O # noqa: E402++TASKS = ("CDB-G02", "CDB-G03", "CDB-G04")+++def spec(task: str) -> dict:+ return json.loads((BENCH / "probes" / task / "task.json").read_text("utf-8"))+++def descriptor(task: str) -> dict:+ return json.loads(C.descriptor_path(spec(task)["pack_task"]).read_text("utf-8"))+++class DescriptorTest(unittest.TestCase):+ def test_every_multi_app_task_runs_on_windows(self) -> None:+ manifest = {t["id"]: t for t in v2.load_taskset()["tasks"]}+ for task in TASKS:+ self.assertIn("windows", manifest[task]["os"])+ d = descriptor(task)+ self.assertEqual(d["platform"], "windows")+ self.assertTrue(d["workspace_root"].startswith("${USERPROFILE}" + "\\"), task)+ self.assertTrue(C.CdbTask(spec(task), Path(tempfile.gettempdir())).apps(), task)++ def test_electron_apps_get_named_executables(self) -> None:+ argv = C.electron_argv(+ ["npx.cmd", "electron", ".", "--surface=mail"],+ "C:/b/app",+ "Copperfield Mail",+ copy=False,+ )+ self.assertEqual(Path(argv[0]).name, "Copperfield Mail.exe")+ self.assertEqual(Path(argv[0]).parent.as_posix(), "C:/b/app/node_modules/electron/dist")+ self.assertEqual(argv[1:], [".", "--surface=mail"])+ self.assertEqual(+ C.electron_argv(["npx", "electron", "."], "C:/b/a", "X", copy=False)[1:], ["."]+ )+ self.assertEqual(+ C.electron_argv(["node", "server.js"], "C:/b", "X", copy=False), ["node", "server.js"]+ )++ def test_leftovers_are_named_exactly(self) -> None:+ g02, g03, g04 = (descriptor(t) for t in TASKS)+ self.assertTrue({"copperfield mail.exe", "signal quay chat.exe", "daymark calendar.exe", "soffice.bin"}+ <= C.process_names(g02)) # fmt: skip+ self.assertTrue(+ {"ledger lantern mail.exe", "gnucash.exe", "scalc.exe"} <= C.process_names(g03)+ )+ self.assertIn("chrome.exe", C.process_names(g04))+ self.assertNotIn("node.exe", C.process_names(g04)) # the archive service goes by its port+ self.assertEqual(C.ports(g04), [4184])+ self.assertEqual(C.ports(g02), [])++ def test_window_titles(self) -> None:+ self.assertTrue(C.title_matches({"title": "Copperfield Mail"}, "Copperfield Mail"))+ self.assertFalse(C.title_matches({"title": "Copperfield Mail"}, "Copperfield"))+ calc = {"title_contains": "kestrel-wharf-reconciliation"}+ self.assertTrue(+ C.title_matches(calc, "kestrel-wharf-reconciliation.ods - LibreOffice Calc")+ )+ self.assertFalse(C.title_matches(calc, "kestrel-wharf.gnucash - Accounts - GnuCash"))++ def test_brief_names_the_workspace(self) -> None:+ task = C.CdbTask(spec("CDB-G02"), Path(tempfile.gettempdir()))+ brief = task.brief()+ self.assertIn(f"Your workspace directory is `{task.workspace}`.", brief)+ self.assertNotIn("configured `cua` MCP server", brief)+++class OracleTest(unittest.TestCase):+ def test_oracle_passes_and_noop_fails(self) -> None:+ for task in TASKS:+ with self.subTest(task=task), tempfile.TemporaryDirectory() as tmp:+ bundle = C.TASKPACK / "tasks" / spec(task)["pack_task"]+ ws, result = Path(tmp) / "ws", Path(tmp) / "result.json"++ def evaluate() -> bool:+ subprocess.run(+ [sys.executable, "evaluator/evaluate.py", "--workspace", str(ws), "--artifacts", tmp,+ "--result", str(result), "--agent-exit-code", "0"],+ cwd=bundle, capture_output=True, check=False,+ ) # fmt: skip+ return json.loads(result.read_text("utf-8"))["passed"]++ subprocess.run([sys.executable, "reset/setup.py", "--workspace", str(ws)], cwd=bundle,+ capture_output=True, check=True) # fmt: skip+ self.assertFalse(evaluate())+ O.solve(task, ws)+ self.assertTrue(evaluate())+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_tools.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_tools.pyindex 05221dcbcd..03a7c99325 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_tools.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_windows_tools.py@@ -27,6 +27,7 @@ import summarize_sentinel # noqa: E402import windows_session as WS # noqa: E402BENCHLAB_TASKS = ("MB-09", "MB-10", "MB-11", "IR-01", "IR-02", "IR-03", "IR-04")+CDB_TASKS = ("CDB-G02", "CDB-G03", "CDB-G04")def _emitted(path: Path) -> set[str]:@@ -77,7 +78,7 @@ class ParityTest(unittest.TestCase):self.assertEqual(launch["app_args"], spec["app_args"], tid)self.assertEqual(launch["conditions"], manifest[tid]["conditions"], tid)self.assertIn("windows", manifest[tid]["os"])- self.assertEqual(set(WS.TASKS), set(BENCHLAB_TASKS))+ self.assertEqual(set(WS.TASKS), set(BENCHLAB_TASKS) | set(CDB_TASKS))class BriefTest(unittest.TestCase):diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/windows/cdb.py b/libs/cua-driver-bench/automated-eval/macos_bench/windows/cdb.pynew file mode 100644index 0000000000..74b05ff5db--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/windows/cdb.py@@ -0,0 +1,358 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""A task of the CDB task pack (CDB-G02 to CDB-G04) on a Windows desktop.++The Windows counterpart of `cdb_adapter.CdbTask`. It reads the task's own `platform/launch.windows.json` and+does what it says: reset the workspace (setup, then the byte-level verify), start the apps, place their+windows, run the evaluator, stop the apps. No task content lives here.++Mechanical adaptations, the same as on macOS where one applies:+* `terminal` and `editor` apps are not started (every setup gets the same tools; GUI-only on Windows).+* The brief is the pack's `brief.md` with the MCP server name made neutral plus one line giving the+ workspace path (as `cdb_adapter.CdbTask.brief`).+* `electron` apps (macOS Amendment 4): `npx electron .` would make every app a process called+ `electron.exe`, so a setup that names apps by process cannot tell them apart. Each app instead runs from+ a copy of the pack's own `electron.exe` named after its window title (`Copperfield Mail.exe`), in the same+ `dist` folder, so the copy finds the same Electron runtime files. Same binary, code and arguments.+* GnuCash keeps its preferences (GSettings) in the registry on Windows, outside the task workspace, so the+ reset deletes `HKCU\\Software\\GSettings\\org\\gnucash` before each trial: every trial starts GnuCash with+ default preferences, as the descriptor's task-scoped data and config folders intend.+"""++from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import sys+import time+import urllib.request+import zipfile+from pathlib import Path+from typing import Any++HERE = Path(__file__).resolve().parent+TASKPACK = Path(os.environ.get("CDB_TASKPACK") or HERE.parents[2] / "taskpack")+SKIP_KINDS = {"terminal", "editor"}+GNUCASH_PREFS = r"HKCU\Software\GSettings\org\gnucash"+CREATE_NEW_PROCESS_GROUP = 0x00000200+++def descriptor_path(pack_task: str, root: Path | None = None) -> Path:+ return (root or TASKPACK) / "tasks" / pack_task / "platform" / "launch.windows.json"+++def substitute(text: str, values: dict[str, str]) -> str:+ return re.sub(r"\$\{(\w+)\}", lambda m: values.get(m.group(1), m.group(0)), text)+++def app_display_name(app: dict[str, Any]) -> str:+ """The name an Electron app runs under: its window title, else its role, else its id (as on macOS)."""+ win = app.get("window") or {}+ return str(win.get("title") or app.get("role") or app["id"]).strip()+++def exe_name(name: str) -> str:+ return re.sub(r'[<>:"/\\|?*]+', "-", name).strip(" .") + ".exe"+++def electron_argv(argv: list[str], cwd: str, name: str, *, copy: bool = True) -> list[str]:+ """Rewrite `[npx|npx.cmd, electron, <args>]` to `[<cwd>\\node_modules\\electron\\dist\\<Name>.exe, <args>]`.++ `npx electron` resolves `node_modules/electron` of `cwd` and runs its `dist/electron.exe` with the remaining+ arguments; this runs a copy of that executable named NAME (made once, refreshed when the original changes)."""+ try:+ at = next(+ i for i in range(len(argv) - 1)+ if Path(argv[i]).name.lower() in ("npx", "npx.cmd") and argv[i + 1] == "electron"+ ) # fmt: skip+ except StopIteration:+ return argv+ dist = Path(cwd) / "node_modules" / "electron" / "dist"+ source = dist / "electron.exe"+ target = dist / exe_name(name)+ if copy:+ if not source.is_file():+ raise RuntimeError(f"electron.exe missing for {name}: {source} (run `npm ci` in {cwd})")+ if not target.is_file() or target.stat().st_size != source.stat().st_size:+ shutil.copy2(source, target)+ return argv[:at] + [str(target)] + argv[at + 2 :]+++def process_names(descriptor: dict[str, Any]) -> set[str]:+ """Executable names (lower case) the task's apps run as: cleared before and after a trial."""+ names: set[str] = set()+ for app in descriptor["apps"]:+ if app["kind"] in SKIP_KINDS:+ continue+ if app["kind"] == "electron":+ names.update({"electron.exe", exe_name(app_display_name(app)).lower()})+ continue+ exe = Path(app["command"][0].replace("\\", "/")).name.lower()+ if exe in ("soffice.exe", "scalc.exe", "swriter.exe"):+ names.update({"soffice.exe", "soffice.bin", "scalc.exe"})+ elif (+ exe != "node" and exe != "node.exe"+ ): # the archive service: cleared by its port, not by name+ names.add(exe if exe.endswith(".exe") else exe + ".exe")+ if "gnucash.exe" in names:+ names.add("gnucash-cli.exe")+ return names+++def ports(descriptor: dict[str, Any]) -> list[int]:+ text = json.dumps(descriptor)+ found = {int(p) for p in re.findall(r"127\.0\.0\.1:(\d+)", text)}+ for app in descriptor["apps"]:+ port = (app.get("env") or {}).get("CDB_S04_PORT")+ if port:+ found.add(int(port))+ return sorted(found)+++def title_matches(win: dict[str, Any], title: str) -> bool:+ if win.get("title"):+ return title == win["title"] or title.startswith(win["title"] + " ")+ if win.get("title_contains"):+ return win["title_contains"].lower() in title.lower()+ return False+++class CdbTask:+ """One task of the pack, driven by its Windows launch descriptor."""++ def __init__(self, spec: dict[str, Any], artifacts: Path, seed: int | None = None) -> None:+ self.spec = spec+ self.seed = seed+ self.bundle = TASKPACK / "tasks" / spec["pack_task"]+ self.descriptor = json.loads(descriptor_path(spec["pack_task"]).read_text("utf-8"))+ self.artifacts = artifacts+ home = os.environ.get("USERPROFILE") or str(Path.home())+ self.workspace = Path(self.descriptor["workspace_root"].replace("${USERPROFILE}", home))+ self.procs: list[tuple[dict[str, Any], subprocess.Popen]] = []+ self.windows: dict[str, int] = {}+ self.log: list[str] = []++ def values(self, **extra: str) -> dict[str, str]:+ return {+ "python": sys.executable,+ "seed": str(self.seed),+ "workspace": str(self.workspace),+ "workspace_uri": self.workspace.as_uri(),+ "bundle": str(self.bundle),+ "USERPROFILE": os.environ.get("USERPROFILE", str(Path.home())),+ "artifacts": str(self.artifacts),+ **extra,+ }++ def sub(self, text: str, **extra: str) -> str:+ return substitute(text, self.values(**extra))++ def _run(+ self, command: list[str], timeout: int = 300, **extra: str+ ) -> subprocess.CompletedProcess:+ argv = [self.sub(part, **extra) for part in command]+ return subprocess.run(+ argv, cwd=str(self.bundle), capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=timeout,+ ) # fmt: skip++ # ---- lifecycle+ def clear_leftovers(self) -> None:+ """Stop leftovers of an earlier trial in this desktop session only: the task's app executables by name,+ and whatever listens on the task's loopback ports."""+ import winenv as W++ here = W.session_of(os.getpid())+ names = process_names(self.descriptor)+ for pid, _, exe in W.processes():+ if exe.lower() in names and pid != os.getpid() and W.session_of(pid) == here:+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(pid)], capture_output=True)+ for port in ports(self.descriptor):+ out = subprocess.run(+ ["netstat", "-ano", "-p", "TCP"], capture_output=True, text=True+ ).stdout+ for line in out.splitlines():+ parts = line.split()+ if len(parts) >= 5 and parts[1].endswith(f":{port}") and parts[3] == "LISTENING":+ subprocess.run(["taskkill", "/T", "/F", "/PID", parts[4]], capture_output=True)+ time.sleep(0.5)++ def reset(self) -> None:+ """Descriptor setup, then the pack's byte-level reset verification. Raises on failure."""+ self.clear_leftovers()+ if any("gnucash" in json.dumps(a["command"]).lower() for a in self.descriptor["apps"]):+ subprocess.run(["reg", "delete", GNUCASH_PREFS, "/f"], capture_output=True)+ self.log.append("gnucash preferences reset")+ sem = self.descriptor["semantics"]["reset"]+ for step in ("setup", "verify"):+ done = self._run(sem[step])+ self.log.append(f"reset.{step} rc={done.returncode}")+ if done.returncode != 0:+ raise RuntimeError(f"reset {step} failed: {(done.stderr or done.stdout)[-400:]}")++ def health_check(self) -> list[dict[str, Any]]:+ """The evaluator's tools are on PATH (the s04 evaluator starts `node`). A failure is a harness error."""+ checks = []+ for name in (+ ("python", "node") if "node" in json.dumps(self.descriptor["apps"]) else ("python",)+ ):+ path = sys.executable if name == "python" else shutil.which(name)+ checks.append({"name": f"tool:{name}", "ok": bool(path), "path": path})+ bad = [c["name"] for c in checks if not c["ok"]]+ if bad:+ raise RuntimeError("harness health: missing " + ", ".join(bad))+ return checks++ def brief(self) -> str:+ brief = self.sub(self.descriptor["semantics"].get("brief", "brief.md"))+ text = (self.bundle / brief).read_text("utf-8")+ text = text.replace("configured `cua` MCP server", "configured computer-use MCP server")+ return text.strip() + f"\n\nYour workspace directory is `{self.workspace}`.\n"++ def apps(self) -> list[dict[str, Any]]:+ return [a for a in self.descriptor["apps"] if a["kind"] not in SKIP_KINDS]++ def start_apps(self) -> None:+ for app in self.apps():+ env = dict(os.environ)+ env.update({k: self.sub(v) for k, v in (app.get("env") or {}).items()})+ for key in app.get("unset_env", []):+ env.pop(key, None)+ cwd = self.sub(app["cwd"]) if app.get("cwd") else str(self.bundle)+ argv = [self.sub(p) for p in app["command"]]+ if app["kind"] == "electron":+ argv = electron_argv(argv, cwd, app_display_name(app))+ self.log.append(f"electron {app['id']} as {Path(argv[0]).name}")+ elif Path(argv[0]).name.lower() == "node":+ argv[0] = shutil.which("node") or argv[0]+ out = (self.artifacts / f"app-{app['id']}.log").open("ab")+ proc = subprocess.Popen(+ argv, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=out, stderr=out,+ creationflags=CREATE_NEW_PROCESS_GROUP,+ ) # fmt: skip+ self.procs.append((app, proc))+ ready = (app.get("ready") or {}).get("url") or (app.get("ready") or {}).get("http")+ if ready:+ self._wait_http(self.sub(ready), float(app["ready"].get("timeout_seconds", 20)))+ self.log.append(f"started {app['id']} pid={proc.pid}")+ time.sleep(1.0)++ @staticmethod+ def _wait_http(url: str, timeout: float) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ try:+ with urllib.request.urlopen(url, timeout=2) as r:+ if r.status == 200:+ return+ except OSError:+ pass+ time.sleep(0.4)+ raise RuntimeError(f"app not ready: {url}")++ def place_windows(self, limit: float = 90.0) -> None:+ """Wait for each app's window (a shown top-level window of the app's own processes whose title matches+ the descriptor) and give it the descriptor's bounds. Raises when a window does not appear."""+ import guard as G+ import winenv as W++ pending = [(a, p) for a, p in self.procs if (a.get("window") or {}).get("bounds")]+ deadline = time.monotonic() + limit+ while pending and time.monotonic() < deadline:+ rows = W.processes()+ for app, proc in list(pending):+ tree = G.descendants(rows, proc.pid)+ exe = Path(proc.args[0]).name.lower() if isinstance(proc.args, list) else ""+ for hwnd in W.top_level_windows():+ if not W.shown(hwnd) or hwnd in self.windows.values():+ continue+ pid = W.window_pid(hwnd)+ mine = (+ pid in tree+ or Path(W.process_path(pid)).name.lower() == exe+ or (+ exe in ("soffice.exe", "scalc.exe")+ and W.stem(W.process_path(pid)).lower() == "soffice"+ )+ ) # LibreOffice hands the document to its running soffice.bin+ if mine and title_matches(app["window"], W.text(hwnd)):+ b = app["window"]["bounds"]+ if W.user32.IsIconic(hwnd) or W.user32.IsZoomed(hwnd):+ W.user32.ShowWindow(hwnd, W.SW_RESTORE)+ W.move_window(hwnd, b["x"], b["y"], b["width"], b["height"])+ self.windows[app["id"]] = hwnd+ self.log.append(f"window {app['id']} hwnd={hwnd} title={W.text(hwnd)!r}")+ pending.remove((app, proc))+ break+ time.sleep(0.5)+ if pending:+ raise RuntimeError("windows did not appear: " + ", ".join(a["id"] for a, _ in pending))+ time.sleep(1.5)++ def evaluate(self, agent_exit_code: int) -> dict[str, Any]:+ """The pack's evaluator. A result with `harness_error` set means the harness, not the agent, failed."""+ result = self.artifacts / "cdb-result.json"+ result.unlink(missing_ok=True)+ try:+ done = self._run(+ self.descriptor["semantics"]["evaluate"], timeout=300, result=str(result),+ agent_exit_code=str(agent_exit_code),+ ) # fmt: skip+ (self.artifacts / "cdb-evaluator.stderr").write_text(+ (done.stderr or "")[-4000:], "utf-8"+ )+ except subprocess.TimeoutExpired:+ pass+ if not result.is_file():+ return {"passed": False, "score": None, "error": "evaluator wrote no result",+ "harness_error": "evaluator_no_result"} # fmt: skip+ data = json.loads(result.read_text("utf-8"))+ checks_raw = (data.get("detail") or {}).get("checks") or data.get("checks") or {}+ checks = {+ name: bool(c.get("passed")) if isinstance(c, dict) else bool(c)+ for name, c in checks_raw.items()+ }+ return {+ "seed": data.get("seed"),+ "passed": bool(data.get("passed")),+ "score": data.get("score"),+ "checks": checks,+ "diagnostics": {+ "raw_keys": sorted(data)[:12],+ **(data.get("diagnostics") if isinstance(data.get("diagnostics"), dict) else {}),+ },+ }++ def snapshot_workspace(self, target: Path) -> None:+ """The final workspace (without runtime profiles and node_modules) as evidence."""+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as z:+ for path in sorted(self.workspace.rglob("*")):+ rel = path.relative_to(self.workspace)+ if path.is_file() and not ({".runtime", "node_modules"} & set(rel.parts)):+ try:+ z.write(path, str(rel))+ except OSError:+ pass++ def stop_apps(self) -> None:+ for _, proc in reversed(self.procs):+ if proc.poll() is None:+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True)+ try:+ proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ pass+ self.procs.clear()+ self.clear_leftovers()++ def clean_workspace(self) -> None:+ """Leave no workspace behind (the pack's setup recreates it next trial)."""+ for _ in range(5):+ shutil.rmtree(self.workspace, ignore_errors=True)+ if not self.workspace.exists():+ return+ time.sleep(1.0)diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/windows/cdb_oracle.py b/libs/cua-driver-bench/automated-eval/macos_bench/windows/cdb_oracle.pynew file mode 100644index 0000000000..4f393867c2--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/windows/cdb_oracle.py@@ -0,0 +1,85 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""Validation stand-ins for the agent in a Windows pack-task trial (CDB-G02 to CDB-G04). Never a bench setup.++ cdb_oracle.py --task CDB-G02 --workspace {workspace} scripted correct solution: the checker passes+ cdb_oracle.py --task CDB-G02 --workspace {workspace} --noop does nothing: the checker fails, user undisturbed+ cdb_oracle.py --task CDB-G02 --workspace {workspace} --disturb one deliberate disturbance the sentinel must see++The scripted solution is the helper of the pack's own test module (`tests/test_<task>.py`, class `Workspace`,+method `complete`) applied to the trial's workspace, as `tools/validate_cdb.py` does on macOS. It writes the+end state to the workspace files directly; it checks the evaluator and the Windows lifecycle, not the GUI.+"""++from __future__ import annotations++import argparse+import ctypes+import importlib.util+import json+import sys+import tempfile+import time+from pathlib import Path++HERE = Path(__file__).resolve().parent+sys.path.insert(0, str(HERE))+import cdb as C # noqa: E402++PROBES = HERE.parent / "probes"+++def solve(task: str, workspace: Path) -> None:+ pack_task = json.loads((PROBES / task / "task.json").read_text("utf-8"))["pack_task"]+ bundle = C.TASKPACK / "tasks" / pack_task+ name = "test_" + Path(pack_task).name.replace("-", "_")+ spec = importlib.util.spec_from_file_location(name, bundle / "tests" / f"{name}.py")+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module) # type: ignore[union-attr]+ ws = object.__new__(module.Workspace) # pointed at the trial's workspace, no second setup+ ws.root = workspace+ ws.artifacts = Path(tempfile.mkdtemp(prefix="cdb-oracle-"))+ ws.complete()+++def disturb(task: str) -> None:+ """Bring one of the task's windows to the front, move the real pointer and clear the clipboard."""+ import winenv as W++ pack_task = json.loads((PROBES / task / "task.json").read_text("utf-8"))["pack_task"]+ descriptor = json.loads(C.descriptor_path(pack_task).read_text("utf-8"))+ time.sleep(2)+ wins = [a["window"] for a in descriptor["apps"] if a.get("window")]+ for hwnd in W.top_level_windows():+ if W.shown(hwnd) and any(C.title_matches(w, W.text(hwnd)) for w in wins):+ W.force_foreground(hwnd) # focus steal, activation change, raise over the user window+ break+ time.sleep(1)+ W.user32.SetCursorPos(300, 300) # real pointer movement+ ctypes.windll.user32.OpenClipboard(0)+ ctypes.windll.user32.EmptyClipboard() # clipboard change+ ctypes.windll.user32.CloseClipboard()+ time.sleep(2)+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--task", required=True)+ parser.add_argument("--workspace", type=Path, required=True)+ parser.add_argument("--noop", action="store_true")+ parser.add_argument("--disturb", action="store_true")+ args = parser.parse_args()+ if args.disturb:+ disturb(args.task)+ elif args.noop:+ time.sleep(3)+ else:+ solve(args.task, args.workspace)+ time.sleep(2.0) # the sentinel needs 2 s of samples to measure the user window+ time.sleep(1.0)+++if __name__ == "__main__":+ main()