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
fix(cua-driver): make the jev-use visual action path provable (#4196)
Francesco Bonacci24aaf8d1965b
diff --git a/.github/workflows/ci-jev-use.yml b/.github/workflows/ci-jev-use.ymlindex 87a503fba2..b394eb5cec 100644--- a/.github/workflows/ci-jev-use.yml+++ b/.github/workflows/ci-jev-use.yml@@ -223,6 +223,12 @@ jobs:cd libs/cua-driver/examples/jev-useuv run python verify_mcp_tools.pyuv run --frozen python verify_setup.py --typescript --output-dir "$proof"+ # Visual-path fixture: Submit has no DOM button ref. Without the+ # cua-perception extension, both runners must log not_installed on+ # every step that attempts a visual parse, fall back to the+ # page-structure path, and never submit.+ uv run --frozen python verify_setup.py --typescript --visual-fixture \+ --expect-visual-status not_installed --output-dir "$proof/visual-fixture"SH# This focused recipe E2E reuses the repository's supported X11 stack.xvfb-run -a --server-args="-screen 0 1920x1080x24" \@@ -241,8 +247,30 @@ jobs:("python", "mock", "verified"), ("typescript", "mock", "verified")}assert all(item["observed"] == {"submitted": "jev-guide-mock"} for item in summary["checks"])+ assert all(item["acted_path"] == "page_structure" for item in summary["checks"])+ assert all(item["submit_tool"] == "browser_click" for item in summary["checks"])+ # Page-structure refs exist on every default-fixture step, so the+ # visual parse is skipped rather than paid for and discarded.+ assert all(item["visual_statuses"] and set(item["visual_statuses"]) == {"skipped"}+ for item in summary["checks"])+ visual = json.loads((root / "visual-fixture" / "summary.json").read_text())+ assert visual["complete"] is True+ assert visual["fixture"] == "visual"+ assert visual["expected_visual_status"] == "not_installed"+ assert {(item["language"], item["outcome"]) for item in visual["checks"]} == {+ ("python", "budget_exhausted"), ("typescript", "budget_exhausted")+ }+ for item in visual["checks"]:+ assert item["acted_path"] is None and item["submit_tool"] is None+ assert item["observed"] == {"submitted": None}+ # Typing has a page ref (parse skipped); every Submit decision+ # has none, so each one attempts the parse and logs not_installed.+ statuses = item["visual_statuses"]+ assert statuses[0] == "skipped", statuses+ assert len(statuses) > 1 and set(statuses[1:]) == {"not_installed"}, statuses+ assert item["escalations"] == []forbidden = ("typesafe_api_key", "authorization", "environment", "image_base64", "screenshot")- for path in root.iterdir():+ for path in [*root.iterdir(), *(root / "visual-fixture").iterdir()]:if path.name == "summary.json" or path.suffix == ".jsonl":text = path.read_text().lower()assert not any(value in text for value in forbidden), path@@ -255,5 +283,7 @@ jobs:path: |${{ runner.temp }}/jev-use-mock-proof/summary.json${{ runner.temp }}/jev-use-mock-proof/*.jsonl+ ${{ runner.temp }}/jev-use-mock-proof/visual-fixture/summary.json+ ${{ runner.temp }}/jev-use-mock-proof/visual-fixture/*.jsonlif-no-files-found: errorretention-days: 14diff --git a/.lycheeignore b/.lycheeignoreindex ec77e93e3b..ecf3f86b45 100644--- a/.lycheeignore+++ b/.lycheeignore@@ -10,3 +10,5 @@ https://openai.com/*https://github.com/user-attachments/assets/*# Self-referential install.sh URL: resolves once this PR merges to mainhttps://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.sh+# TypeSafe console returns 403 to automated checkers but resolves fine in-browser+https://console.typesafe.ai/*diff --git a/docs/content/docs/how-to-guides/driver/jev-use.mdx b/docs/content/docs/how-to-guides/driver/jev-use.mdxindex b6b279cd82..c4771239b5 100644--- a/docs/content/docs/how-to-guides/driver/jev-use.mdx+++ b/docs/content/docs/how-to-guides/driver/jev-use.mdx@@ -33,7 +33,14 @@ The example prefers browser DOM evidence. It also recognizes the publictool and the capture-bound `click.capture_id` input. The agent obtains thecapture from `get_window_state` and sends its exact ID with the visual click;it never falls back to unbound coordinates. The optional path is not required-for this form. See+for this form: its Submit button has a DOM reference, so the agent submits+with `browser_click` and skips the visual parse. The agent parses visual+regions only when the page offers no action. If Driver refuses a background+visual click, the next step offers an explicit foreground click instead of+retrying in the background. Each logged step records which tool acted and a+`visual` status (`skipped`, `ok`, `not_installed`, `error`, or `unavailable`). To prove the visual action path with the perception+extension installed, add `--visual-fixture --require-visual-path` to+`verify_setup.py`; that test page has no Submit button reference. See[Capture and delivery modalities](/concepts/capture-and-delivery-modalities) forthe observation modes Cua Driver supports.diff --git a/libs/cua-driver/examples/jev-use/README.md b/libs/cua-driver/examples/jev-use/README.mdindex 7f0b12b566..0b4b16b6ef 100644--- a/libs/cua-driver/examples/jev-use/README.md+++ b/libs/cua-driver/examples/jev-use/README.md@@ -117,6 +117,72 @@ languages. `summary.json` must say `complete: true`; partial results remainfalse. Each runner has four decisions and a 180-second process timeout. Theseare not provider billing caps.+### Prove which path acted++Every `step` event in a runner's JSONL log records the Driver tool that acted+(`browser_type`, `browser_click`, or `click`), its `delivery_mode` for a visual+click, and a redacted `visual` record:++```json+{"status": "skipped", "reason": "page_structure_candidate"}+{"status": "ok", "capture_id": "...", "region_count": 12}+{"status": "not_installed", "error_code": "not_installed"}+{"status": "error", "error_code": "worker_failed"}+{"status": "unavailable", "error_code": "tool_not_advertised"}+```++`skipped` means the runner did not capture or parse the window. By default+(`--visual-observation auto`) it parses visual regions only when the page+structure offers no executable candidate, because only then can a visual+region add one. This avoids several seconds of CPU parsing per step on the+default fixture. `--visual-observation always` restores the per-step parse,+which also sends regions to Jev alongside page refs, and `off` disables it+(reason `disabled`). `ok` means a validated `cua.visual_regions_v1`+observation was available for that decision. `not_installed` is Driver's stable code when the perception+extension is absent. `error` carries Driver's error code or a local+`capture_mismatch`, `invalid_visual_result`, `capture_missing`, or+`driver_error` code. `unavailable` means Driver did not advertise+`parse_visual_regions` or the capture-bound `click.capture_id` input. The+record never contains screenshots, screenshot references, region text, or+credentials. A failed visual observation never stops the run; the runner+continues on the page-structure path, and the log shows that it did.++The visual Submit candidate first uses `delivery_mode: "background"`. If+Driver refuses that click with a structured background refusal (a+`background_*` code such as `background_unavailable`, or+`escalation.recommended: "foreground"`), the runner does not retry background+delivery. The refused step is logged with `action_error` and+`escalation: {"from": "background", "to": "foreground", "reason": ...}`. The+next step takes a fresh capture and offers a distinct `submit-form-foreground`+candidate, which the chooser must select explicitly. Foreground delivery+activates the browser window. Other action errors still end the run as+`unknown`.++`verify_setup.py` copies this into each `summary.json` check as `submit_tool`,+`acted_path` (`page_structure` for DOM `browser_click`, `visual` for the+capture-bound `click`), `submit_delivery_mode`, the per-step+`visual_statuses`, and any `escalations`.++The default fixture always exposes a semantic `button "Submit"` ref, so its+Submit step uses `browser_click` even when visual regions are available. To+prove the capture-bound visual action path, serve the visual fixture, whose+Submit control is a presentational element with no button ref, and require+the visual path:++```bash+uv run --frozen python verify_setup.py --visual-fixture --require-visual-path \+ --output-dir proof-visual+```++This fails unless every runner verified the fixture through `click` with the+exact `capture_id`. It needs a Driver with the cua-perception extension+installed. Without the extension, the visual fixture cannot be submitted.+`--expect-visual-status not_installed` checks that fallback instead: every+step that attempted a visual parse must log `not_installed`, no runner may+submit, and the run must end without claiming success. Skipped steps do not+count as attempts, but at least one attempt is required. Continuous integration runs that form on Linux.+The standalone server also accepts `--visual-fixture`.+## Run the standalone fixtureFor an application or terminal that already owns the server lifecycle, start@@ -239,8 +305,9 @@ installation and diagnostics,for example `cua-driver doctor` and `cua-driver status`, rather than maintaininga third copy of the loop.-This fixture exposes semantic browser refs, so the normal proof does not need-screenshot perception. The optional visual path consumes only the public+The default fixture exposes semantic browser refs, so the normal proof does+not need screenshot perception and never acts visually. The visual fixture+removes the Submit button ref so only the visual candidate can submit. The optional visual path consumes only the public`parse_visual_regions` structured result and never adds a model, extension, orDriver internals to this example. It validates capture identity, PNG geometry,coordinate mapping, region IDs, bounds, content, confidence, and ambiguitydiff --git a/libs/cua-driver/examples/jev-use/fixture_server.py b/libs/cua-driver/examples/jev-use/fixture_server.pyindex c30aea8a26..055500f713 100644--- a/libs/cua-driver/examples/jev-use/fixture_server.py+++ b/libs/cua-driver/examples/jev-use/fixture_server.py@@ -27,6 +27,18 @@ output { display:block; margin-top:20px; font-family:monospace; }<button type="submit">Submit</button></form><output>status=waiting</output></main></html>"""+# Visual-path variant: identical form, but Submit is a presentational element+# with no button role, so the page-structure snapshot exposes no Submit ref and+# only the capture-bound visual candidate can submit the form.+VISUAL_SUBMIT = (+ b'<div role="presentation" style="display:inline-block;box-sizing:border-box;'+ b'font:inherit;margin:8px;padding:16px 28px;background:#e5e5e5;'+ b'border:1px solid #999;cursor:pointer" '+ b'onclick="this.closest(\'form\').requestSubmit()">Submit</div>'+)+VISUAL_PAGE = PAGE.replace(b'<button type="submit">Submit</button>', VISUAL_SUBMIT)+assert VISUAL_PAGE != PAGE+class FixtureState:def __init__(self) -> None:@@ -51,7 +63,8 @@ class FixtureHandler(BaseHTTPRequestHandler):def do_GET(self) -> None: # noqa: N802if self.path == "/":- self._send(HTTPStatus.OK, "text/html; charset=utf-8", PAGE)+ page = VISUAL_PAGE if self.server.visual else PAGE+ self._send(HTTPStatus.OK, "text/html; charset=utf-8", page)elif self.path == "/state":self._send(HTTPStatus.OK,@@ -94,16 +107,22 @@ class FixtureHandler(BaseHTTPRequestHandler):class FixtureServer(ThreadingHTTPServer):- def __init__(self, address: tuple[str, int]) -> None:+ def __init__(self, address: tuple[str, int], *, visual: bool = False) -> None:self.state = FixtureState()+ self.visual = visualsuper().__init__(address, FixtureHandler)def main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--port", type=int, default=8765)+ parser.add_argument(+ "--visual-fixture",+ action="store_true",+ help="serve a Submit control with no DOM button ref so only the visual path can submit",+ )args = parser.parse_args()- server = FixtureServer(("127.0.0.1", args.port))+ server = FixtureServer(("127.0.0.1", args.port), visual=args.visual_fixture)print(f"Fixture ready at http://127.0.0.1:{server.server_port}/", flush=True)try:server.serve_forever()diff --git a/libs/cua-driver/examples/jev-use/python/core.py b/libs/cua-driver/examples/jev-use/python/core.pyindex 2de0abcc05..72b7e62a82 100644--- a/libs/cua-driver/examples/jev-use/python/core.py+++ b/libs/cua-driver/examples/jev-use/python/core.py@@ -6,6 +6,9 @@ from types import MappingProxyTypefrom typing import Any, Literal, MappingOutcome = Literal["verified", "refuted", "unknown", "abstained", "budget_exhausted"]+VisualDelivery = Literal["background", "foreground"]++SUBMIT_IDS = frozenset({"submit-form", "submit-form-foreground"})def _freeze(value: Any) -> Any:@@ -62,7 +65,9 @@ class VisualObservation:class VisualObservationError(ValueError):- pass+ def __init__(self, message: str, code: str = "invalid_visual_result") -> None:+ super().__init__(message)+ self.code = codedef _nonempty(value: Any) -> str:@@ -94,7 +99,9 @@ def parse_visual_regions(raise VisualObservationError("unsupported visual region schema")capture = payload.get("capture")if not isinstance(capture, dict) or capture.get("capture_id") != expected_capture_id:- raise VisualObservationError("visual result is stale or capture-mismatched")+ raise VisualObservationError(+ "visual result is stale or capture-mismatched", code="capture_mismatch"+ )source = capture.get("source")if (not isinstance(source, dict)@@ -102,7 +109,9 @@ def parse_visual_regions(or source.get("pid") != expected_pidor source.get("window_id") != expected_window_id):- raise VisualObservationError("visual result has a mismatched window target")+ raise VisualObservationError(+ "visual result has a mismatched window target", code="capture_mismatch"+ )screenshot = capture.get("screenshot")if not isinstance(screenshot, dict) or screenshot.get("mime_type") != "image/png":raise VisualObservationError("visual result has invalid screenshot provenance")@@ -227,7 +236,15 @@ def build_candidates(visual: VisualObservation | None = None,*,capture_bound_click: bool = False,+ visual_delivery: VisualDelivery = "background",) -> list[Candidate]:+ """Build the closed candidate set for one decision.++ Page-structure refs always win. The capture-bound visual Submit is offered+ only when no Submit ref exists. ``visual_delivery="foreground"`` replaces the+ background visual click with a distinct ``submit-form-foreground`` candidate+ after Driver refused background delivery; the chooser must pick it explicitly.+ """common = {"target_id": snapshot["target_id"],"tab_id": snapshot["tab_id"],@@ -278,10 +295,18 @@ def build_candidates(]if len(matches) == 1:x, y = visual.screenshot_center(matches[0])+ foreground = visual_delivery == "foreground"candidates.append(Candidate(- "submit-form",- "Submit the form using the unique validated visual Submit region.",+ "submit-form-foreground" if foreground else "submit-form",+ (+ "Submit the form by clicking the unique validated visual Submit "+ "region with foreground delivery, which activates the browser "+ "window, because Driver refused background delivery for the "+ "previous visual click."+ if foreground+ else "Submit the form using the unique validated visual Submit region."+ ),"click",{"pid": visual.pid,@@ -289,7 +314,7 @@ def build_candidates("x": x,"y": y,"capture_id": visual.capture_id,- "delivery_mode": "background",+ "delivery_mode": visual_delivery,},capture_id=visual.capture_id,screenshot_reference=visual.screenshot_reference,@@ -298,6 +323,10 @@ def build_candidates(return candidates + _reserved_candidates()+def has_executable_candidate(candidates: list[Candidate]) -> bool:+ return any(candidate.tool is not None for candidate in candidates)++def _ascii_lower(value: str) -> str:return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in value)@@ -307,7 +336,13 @@ def choose_mock(candidates: list[Candidate]) -> tuple[str | None, float, dict[stselected = ("type-verification-value"if "type-verification-value" in ids- else "submit-form" if "submit-form" in ids else "reobserve" if "reobserve" in ids else None+ else "submit-form"+ if "submit-form" in ids+ else "submit-form-foreground"+ if "submit-form-foreground" in ids+ else "reobserve"+ if "reobserve" in ids+ else None)probabilities = {candidate.id: float(candidate.id == selected) for candidate in candidates}return selected, 1.0 if selected else 0.0, probabilitiesdiff --git a/libs/cua-driver/examples/jev-use/python/run.py b/libs/cua-driver/examples/jev-use/python/run.pyindex a969d967e4..a6e2538484 100644--- a/libs/cua-driver/examples/jev-use/python/run.py+++ b/libs/cua-driver/examples/jev-use/python/run.py@@ -16,10 +16,14 @@ from mcp.client.stdio import stdio_clientfrom driver_env import driver_environmentfrom core import (+ SUBMIT_IDS,+ Candidate,+ VisualDelivery,VisualObservation,VisualObservationError,build_candidates,classify,+ has_executable_candidate,parse_visual_regions,validate_choice,)@@ -62,6 +66,20 @@ def reset_fixture(fixture_url: str) -> None:raise RuntimeError(f"fixture reset failed: HTTP {response.status}")+class DriverToolError(RuntimeError):+ """A Driver tool returned an error result, optionally with a stable error code."""++ def __init__(+ self,+ message: str,+ code: str | None = None,+ recommended_delivery: str | None = None,+ ) -> None:+ super().__init__(message)+ self.code = code+ self.recommended_delivery = recommended_delivery++class Driver:def __init__(self, session: ClientSession, label: str) -> None:self.session = session@@ -70,7 +88,16 @@ class Driver:async def call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:result = await self.session.call_tool(name, {**arguments, "session": self.label})if result.isError:- raise RuntimeError(f"{name} failed: {result.content}")+ structured = getattr(result, "structuredContent", None)+ structured = structured if isinstance(structured, dict) else {}+ code = structured.get("code")+ escalation = structured.get("escalation")+ recommended = escalation.get("recommended") if isinstance(escalation, dict) else None+ raise DriverToolError(+ f"{name} failed: {getattr(result, 'content', None)}",+ code if isinstance(code, str) and code else None,+ recommended if isinstance(recommended, str) and recommended else None,+ )data = result.structuredContentif not isinstance(data, dict):raise RuntimeError(f"{name} returned no structured result")@@ -91,17 +118,61 @@ def supports_capture_bound_click(tools: list[Any]) -> bool:return False-async def optional_visual_observation(+def background_refusal_code(candidate: Candidate, error: BaseException) -> str | None:+ """Return Driver's code when it refused a background visual click.++ Only a structured refusal counts: a ``background_*`` error code or an explicit+ ``escalation.recommended == "foreground"``. Anything else stays a failure.+ """+ if candidate.tool != "click" or candidate.arguments.get("delivery_mode") != "background":+ return None+ if not isinstance(error, DriverToolError):+ return None+ if error.code and error.code.startswith("background_"):+ return error.code+ if error.recommended_delivery == "foreground":+ return error.code or "foreground_recommended"+ return None+++def visual_status(+ status: str,+ *,+ error_code: str | None = None,+ visual: VisualObservation | None = None,+ reason: str | None = None,+) -> dict[str, Any]:+ """Build the redacted per-step visual record written to the JSONL log.++ It never contains screenshots, screenshot references, region text, or secrets.+ """+ record: dict[str, Any] = {"status": status}+ if reason:+ record["reason"] = reason+ if error_code:+ record["error_code"] = error_code+ if visual is not None:+ record["capture_id"] = visual.capture_id+ record["region_count"] = len(visual.regions)+ return record+++async def observe_visual(driver: Driver,pid: int,window_id: int,available_tools: set[str],capture_bound_click: bool,-) -> VisualObservation | None:- if not capture_bound_click or not {"get_window_state", "parse_visual_regions"}.issubset(- available_tools- ):- return None+) -> tuple[VisualObservation | None, dict[str, Any]]:+ """Take an optional visual observation and report what happened.++ Failures never stop the run: the caller continues on the page-structure path,+ but the returned status makes the fallback observable.+ """+ if not capture_bound_click:+ return None, visual_status("unavailable", error_code="capture_bound_click_unsupported")+ if not {"get_window_state", "parse_visual_regions"}.issubset(available_tools):+ return None, visual_status("unavailable", error_code="tool_not_advertised")try:capture = await driver.call("get_window_state",@@ -113,7 +184,7 @@ async def optional_visual_observation()capture_id = capture.get("capture_id")if not isinstance(capture_id, str):- return None+ return None, visual_status("error", error_code="capture_missing")result = await driver.call("parse_visual_regions",{@@ -121,14 +192,77 @@ async def optional_visual_observation("options": {"kinds": ["text", "icon"], "min_confidence": 0.8, "max_regions": 100},},)- return parse_visual_regions(+ visual = parse_visual_regions(result,expected_capture_id=capture_id,expected_pid=pid,expected_window_id=window_id,)- except (RuntimeError, VisualObservationError, KeyError, TypeError):- return None+ except DriverToolError as error:+ if error.code == "not_installed":+ return None, visual_status("not_installed", error_code="not_installed")+ return None, visual_status("error", error_code=error.code or "driver_error")+ except VisualObservationError as error:+ return None, visual_status("error", error_code=error.code)+ except (RuntimeError, KeyError, TypeError):+ return None, visual_status("error", error_code="driver_error")+ return visual, visual_status("ok", visual=visual)+++async def optional_visual_observation(+ driver: Driver,+ pid: int,+ window_id: int,+ available_tools: set[str],+ capture_bound_click: bool,+) -> VisualObservation | None:+ visual, _ = await observe_visual(+ driver, pid, window_id, available_tools, capture_bound_click+ )+ return visual+++async def candidates_for_step(+ driver: Driver,+ snapshot: dict[str, Any],+ token: str,+ pid: int,+ window_id: int,+ available_tools: set[str],+ capture_bound_click: bool,+ *,+ visual_mode: str = "auto",+ visual_delivery: VisualDelivery = "background",+) -> tuple[list[Candidate], VisualObservation | None, dict[str, Any]]:+ """Build one step's candidates, parsing visual regions only when useful.++ In ``auto`` mode the capture and parse run only when the page structure+ offers no executable candidate, because only then can a visual region add+ one. ``always`` restores the per-step parse; ``off`` never parses.+ """+ candidates = build_candidates(+ snapshot,+ token,+ None,+ capture_bound_click=capture_bound_click,+ visual_delivery=visual_delivery,+ )+ if visual_mode == "off":+ return candidates, None, visual_status("skipped", reason="disabled")+ if visual_mode == "auto" and has_executable_candidate(candidates):+ return candidates, None, visual_status("skipped", reason="page_structure_candidate")+ visual, record = await observe_visual(+ driver, pid, window_id, available_tools, capture_bound_click+ )+ if visual is not None:+ candidates = build_candidates(+ snapshot,+ token,+ visual,+ capture_bound_click=capture_bound_click,+ visual_delivery=visual_delivery,+ )+ return candidates, visual, recordasync def wait_for_window(driver: Driver, pid: int) -> dict[str, Any]:@@ -156,6 +290,7 @@ async def run(args: argparse.Namespace) -> str:token = args.token or f"jev-{uuid.uuid4().hex[:10]}"label = f"jev-python-{uuid.uuid4().hex[:8]}"history: list[dict[str, Any]] = []+ visual_delivery: VisualDelivery = "background"log_path = Path(args.log) if args.log else Noneif log_path:log_path.write_text("", encoding="utf-8")@@ -203,21 +338,22 @@ async def run(args: argparse.Namespace) -> str:"snapshot_format": "semantic_v2",},)- visual = await optional_visual_observation(+ candidates, visual, visual_record = await candidates_for_step(driver,+ snapshot,+ token,pid,int(window["window_id"]),available_tools,capture_bound_click,- )- candidates = build_candidates(- snapshot,- token,- visual,- capture_bound_click=capture_bound_click,+ visual_mode=args.visual_observation,+ visual_delivery=visual_delivery,)if not candidates:- write_event(log_path, {"event": "outcome", "outcome": "abstained", "step": step})+ write_event(+ log_path,+ {"event": "outcome", "outcome": "abstained", "step": step, "visual": visual_record},+ )return "abstained"if args.provider == "mock":@@ -247,6 +383,8 @@ async def run(args: argparse.Namespace) -> str:"decision_ms": decision_ms,"action_ms": 0.0,"dry_run": args.dry_run,+ "tool": None,+ "visual": visual_record,}history.append(event)write_event(log_path, event)@@ -261,6 +399,7 @@ async def run(args: argparse.Namespace) -> str:"step": step,"confidence": confidence,"probabilities": probabilities,+ "visual": visual_record,},)return "abstained"@@ -271,6 +410,33 @@ async def run(args: argparse.Namespace) -> str:assert candidate.tool is not Noneawait driver.call(candidate.tool, candidate.arguments)except Exception as error:+ refusal = background_refusal_code(candidate, error)+ if refusal is not None:+ # Do not retry background. The next step takes a fresh+ # capture and offers a distinct foreground candidate.+ visual_delivery = "foreground"+ event = {+ "event": "step",+ "step": step,+ "candidate": candidate.id,+ "confidence": confidence,+ "probabilities": probabilities,+ "decision_ms": decision_ms,+ "action_ms": round((time.perf_counter() - action_started) * 1000, 2),+ "dry_run": args.dry_run,+ "tool": candidate.tool,+ "delivery_mode": "background",+ "action_error": refusal,+ "escalation": {+ "from": "background",+ "to": "foreground",+ "reason": refusal,+ },+ "visual": visual_record,+ }+ history.append(event)+ write_event(log_path, event)+ continuewrite_event(log_path,{@@ -279,6 +445,8 @@ async def run(args: argparse.Namespace) -> str:"step": step,"phase": "action","error": type(error).__name__,+ "tool": candidate.tool,+ "visual": visual_record,},)return "unknown"@@ -294,12 +462,15 @@ async def run(args: argparse.Namespace) -> str:"decision_ms": decision_ms,"action_ms": action_ms,"dry_run": args.dry_run,+ "tool": candidate.tool,+ "delivery_mode": candidate.arguments.get("delivery_mode"),+ "visual": visual_record,}history.append(event)write_event(log_path, event)if args.dry_run:return "unknown"- if candidate.id == "submit-form":+ if candidate.id in SUBMIT_IDS:for _ in range(20):oracle = fixture_state(args.fixture_url)outcome = classify(@@ -330,6 +501,15 @@ def parse_args() -> argparse.Namespace:parser.add_argument("--max-steps", type=int, default=4)parser.add_argument("--dry-run", action="store_true")parser.add_argument("--log", help="optional JSONL output path")+ parser.add_argument(+ "--visual-observation",+ choices=("auto", "always", "off"),+ default="auto",+ help=(+ "auto parses visual regions only when the page structure offers no "+ "executable candidate; always parses every step; off never parses"+ ),+ )return parser.parse_args()diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_core.py b/libs/cua-driver/examples/jev-use/python/tests/test_core.pyindex 4ca0dd89ac..6581402189 100644--- a/libs/cua-driver/examples/jev-use/python/tests/test_core.py+++ b/libs/cua-driver/examples/jev-use/python/tests/test_core.py@@ -8,7 +8,15 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from core import Candidate, build_candidates, choose_mock, classify, parse_visual_regions, validate_choice+from core import (+ Candidate,+ build_candidates,+ choose_mock,+ classify,+ has_executable_candidate,+ parse_visual_regions,+ validate_choice,+)FIXTURES = Path(__file__).resolve().parents[2] / "fixtures"@@ -89,6 +97,82 @@ class CoreTest(unittest.TestCase):},)+ def test_submit_path_depends_on_the_dom_button_ref(self) -> None:+ payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())+ visual = parse_visual_regions(+ payload,+ expected_capture_id="capture-submit",+ expected_pid=7,+ expected_window_id=9,+ )+ with_ref = build_candidates(+ self.snapshot("expected"), "expected", visual, capture_bound_click=True+ )+ self.assertEqual(with_ref[0].id, "submit-form")+ self.assertEqual(with_ref[0].tool, "browser_click")+ self.assertIsNone(with_ref[0].capture_id)++ page = self.snapshot("expected")+ page["refs"] = page["refs"][:1]+ without_ref = build_candidates(page, "expected", visual, capture_bound_click=True)+ self.assertEqual(without_ref[0].id, "submit-form")+ self.assertEqual(without_ref[0].tool, "click")+ self.assertEqual(without_ref[0].capture_id, "capture-submit")+ self.assertEqual(+ [candidate.id for candidate in build_candidates(page, "expected", None, capture_bound_click=True)],+ ["reobserve", "abstain"],+ )++ def test_visual_input_does_not_change_semantic_candidate_set(self) -> None:+ # Salvaged from #4165: when the page structure already offers an+ # executable action, a visual observation cannot change the candidates,+ # so the runner may skip the parse without changing behavior.+ payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())+ visual = parse_visual_regions(+ payload,+ expected_capture_id="capture-submit",+ expected_pid=7,+ expected_window_id=9,+ )+ for value in [None, "expected"]:+ without_visual = build_candidates(+ self.snapshot(value), "expected", None, capture_bound_click=True+ )+ with_visual = build_candidates(+ self.snapshot(value), "expected", visual, capture_bound_click=True+ )+ self.assertEqual(with_visual, without_visual)+ self.assertTrue(has_executable_candidate(without_visual))++ def test_foreground_escalation_is_a_distinct_visual_candidate(self) -> None:+ payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())+ visual = parse_visual_regions(+ payload,+ expected_capture_id="capture-submit",+ expected_pid=7,+ expected_window_id=9,+ )+ page = self.snapshot("expected")+ page["refs"] = page["refs"][:1]+ candidates = build_candidates(+ page, "expected", visual, capture_bound_click=True, visual_delivery="foreground"+ )+ ids = [candidate.id for candidate in candidates]+ self.assertEqual(ids, ["submit-form-foreground", "reobserve", "abstain"])+ self.assertEqual(candidates[0].tool, "click")+ self.assertEqual(candidates[0].arguments["delivery_mode"], "foreground")+ self.assertEqual(candidates[0].arguments["capture_id"], "capture-submit")+ self.assertIn("foreground", candidates[0].description)+ self.assertEqual(choose_mock(candidates)[0], "submit-form-foreground")+ # Page-structure refs still win after escalation.+ self.assertEqual(+ build_candidates(+ self.snapshot("expected"), "expected", visual,+ capture_bound_click=True, visual_delivery="foreground",+ )[0].tool,+ "browser_click",+ )+def test_visual_ambiguity_offers_only_reserved_candidates(self) -> None:payload = json.loads((FIXTURES / "parse-visual-regions-ambiguous-v1.json").read_text())for region in payload["regions"]:diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_driver_adapter.py b/libs/cua-driver/examples/jev-use/python/tests/test_driver_adapter.pyindex 6e509d4f16..abc26338cc 100644--- a/libs/cua-driver/examples/jev-use/python/tests/test_driver_adapter.py+++ b/libs/cua-driver/examples/jev-use/python/tests/test_driver_adapter.py@@ -10,9 +10,13 @@ from types import SimpleNamespacesys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from core import build_candidates, validate_choice+from core import Candidate, build_candidates, validate_choicefrom run import (Driver,+ DriverToolError,+ background_refusal_code,+ candidates_for_step,+ observe_visual,optional_visual_observation,select_tab_id,supports_capture_bound_click,@@ -93,6 +97,202 @@ class DriverAdapterTest(unittest.IsolatedAsyncioTestCase):],)+ async def test_visual_status_is_logged_for_ok_not_installed_and_error(self) -> None:+ tools = {"get_window_state", "parse_visual_regions", "click"}+ payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())++ class ScriptedSession(FakeSession):+ def __init__(self, parse_result) -> None:+ super().__init__()+ self.parse_result = parse_result++ async def call_tool(self, name, arguments):+ self.calls.append((name, arguments))+ if name == "get_window_state":+ return SimpleNamespace(+ isError=False, structuredContent={"capture_id": "capture-submit"}+ )+ return self.parse_result++ ok = SimpleNamespace(isError=False, structuredContent=payload)+ visual, status = await observe_visual(+ Driver(ScriptedSession(ok), "jev-test"), 7, 9, tools, True+ )+ self.assertEqual(visual.capture_id, "capture-submit")+ self.assertEqual(+ status,+ {"status": "ok", "capture_id": "capture-submit", "region_count": len(visual.regions)},+ )++ not_installed = SimpleNamespace(+ isError=True,+ structuredContent={"code": "not_installed", "message": "extension missing"},+ content=[{"text": "not installed"}],+ )+ visual, status = await observe_visual(+ Driver(ScriptedSession(not_installed), "jev-test"), 7, 9, tools, True+ )+ self.assertIsNone(visual)+ self.assertEqual(status, {"status": "not_installed", "error_code": "not_installed"})++ worker_failed = SimpleNamespace(+ isError=True,+ structuredContent={"code": "worker_failed"},+ content=[{"text": "worker crashed"}],+ )+ visual, status = await observe_visual(+ Driver(ScriptedSession(worker_failed), "jev-test"), 7, 9, tools, True+ )+ self.assertIsNone(visual)+ self.assertEqual(status, {"status": "error", "error_code": "worker_failed"})++ stale = json.loads(json.dumps(payload))+ stale["capture"]["capture_id"] = "older-capture"+ visual, status = await observe_visual(+ Driver(+ ScriptedSession(SimpleNamespace(isError=False, structuredContent=stale)),+ "jev-test",+ ),+ 7,+ 9,+ tools,+ True,+ )+ self.assertIsNone(visual)+ self.assertEqual(status, {"status": "error", "error_code": "capture_mismatch"})++ uncoded = SimpleNamespace(isError=True, structuredContent=None, content=[])+ _, status = await observe_visual(+ Driver(ScriptedSession(uncoded), "jev-test"), 7, 9, tools, True+ )+ self.assertEqual(status, {"status": "error", "error_code": "driver_error"})++ session = FakeSession()+ _, status = await observe_visual(Driver(session, "jev-test"), 7, 9, {"click"}, True)+ self.assertEqual(status, {"status": "unavailable", "error_code": "tool_not_advertised"})+ _, status = await observe_visual(Driver(session, "jev-test"), 7, 9, tools, False)+ self.assertEqual(+ status,+ {"status": "unavailable", "error_code": "capture_bound_click_unsupported"},+ )+ self.assertEqual(session.calls, [])++ async def test_driver_error_carries_the_structured_error_code(self) -> None:+ class FailingSession(FakeSession):+ async def call_tool(self, name, arguments):+ return SimpleNamespace(+ isError=True, structuredContent={"code": "not_installed"}, content=[]+ )++ with self.assertRaises(DriverToolError) as raised:+ await Driver(FailingSession(), "jev-test").call("parse_visual_regions", {})+ self.assertEqual(raised.exception.code, "not_installed")++ def page(self, *, submit_ref: bool):+ refs = [{"role": "textbox", "name": "verification value", "ref": "p1:0", "value": "expected"}]+ if submit_ref:+ refs.append({"role": "button", "name": "Submit", "ref": "p1:1"})+ return {"target_id": "target", "tab_id": "tab", "refs": refs}++ async def test_visual_parse_runs_only_when_it_can_contribute_a_candidate(self) -> None:+ tools = {"get_window_state", "parse_visual_regions", "click"}+ payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())++ session = FakeSession()+ candidates, visual, status = await candidates_for_step(+ Driver(session, "jev-test"), self.page(submit_ref=True), "expected", 7, 9, tools, True+ )+ self.assertEqual(candidates[0].tool, "browser_click")+ self.assertIsNone(visual)+ self.assertEqual(status, {"status": "skipped", "reason": "page_structure_candidate"})+ self.assertEqual(session.calls, [])++ _, _, status = await candidates_for_step(+ Driver(session, "jev-test"), self.page(submit_ref=False), "expected", 7, 9, tools, True,+ visual_mode="off",+ )+ self.assertEqual(status, {"status": "skipped", "reason": "disabled"})+ self.assertEqual(session.calls, [])++ session = FakeSession(responses=[{"capture_id": "capture-submit"}, payload])+ candidates, visual, status = await candidates_for_step(+ Driver(session, "jev-test"), self.page(submit_ref=False), "expected", 7, 9, tools, True+ )+ self.assertEqual([name for name, _ in session.calls], ["get_window_state", "parse_visual_regions"])+ self.assertEqual(status["status"], "ok")+ self.assertEqual(candidates[0].tool, "click")+ self.assertEqual(candidates[0].arguments["delivery_mode"], "background")++ session = FakeSession(responses=[{"capture_id": "capture-submit"}, payload])+ candidates, visual, status = await candidates_for_step(+ Driver(session, "jev-test"), self.page(submit_ref=True), "expected", 7, 9, tools, True,+ visual_mode="always",+ )+ self.assertEqual(status["status"], "ok")+ self.assertEqual(visual.capture_id, "capture-submit")+ self.assertEqual(candidates[0].tool, "browser_click")++ session = FakeSession(responses=[{"capture_id": "capture-submit"}, payload])+ candidates, _, _ = await candidates_for_step(+ Driver(session, "jev-test"), self.page(submit_ref=False), "expected", 7, 9, tools, True,+ visual_delivery="foreground",+ )+ self.assertEqual(candidates[0].id, "submit-form-foreground")+ self.assertEqual(candidates[0].arguments["delivery_mode"], "foreground")++ async def test_structured_background_refusal_escalates_but_other_errors_do_not(self) -> None:+ background = Candidate(+ "submit-form", "visual", "click",+ {"pid": 7, "window_id": 9, "x": 1, "y": 1, "capture_id": "c", "delivery_mode": "background"},+ capture_id="c",+ )+ foreground = Candidate(+ "submit-form-foreground", "visual", "click",+ {"pid": 7, "window_id": 9, "x": 1, "y": 1, "capture_id": "c", "delivery_mode": "foreground"},+ capture_id="c",+ )+ dom = Candidate("submit-form", "dom", "browser_click", {"ref": "p1:1"})+ self.assertEqual(+ background_refusal_code(background, DriverToolError("refused", "background_unavailable")),+ "background_unavailable",+ )+ self.assertEqual(+ background_refusal_code(background, DriverToolError("refused", "background_occluded")),+ "background_occluded",+ )+ self.assertEqual(+ background_refusal_code(+ background, DriverToolError("refused", "some_new_code", "foreground")+ ),+ "some_new_code",+ )+ self.assertIsNone(+ background_refusal_code(background, DriverToolError("stale", "capture_generation_mismatch"))+ )+ self.assertIsNone(background_refusal_code(background, RuntimeError("background_unavailable")))+ self.assertIsNone(+ background_refusal_code(foreground, DriverToolError("refused", "background_unavailable"))+ )+ self.assertIsNone(+ background_refusal_code(dom, DriverToolError("refused", "background_unavailable"))+ )++ class RefusingSession(FakeSession):+ async def call_tool(self, name, arguments):+ return SimpleNamespace(+ isError=True,+ structuredContent={+ "code": "background_unavailable",+ "escalation": {"recommended": "foreground", "reason": "chromium"},+ },+ content=[],+ )++ with self.assertRaises(DriverToolError) as raised:+ await Driver(RefusingSession(), "jev-test").call("click", dict(background.arguments))+ self.assertEqual(raised.exception.recommended_delivery, "foreground")+ self.assertEqual(background_refusal_code(background, raised.exception), "background_unavailable")+def test_capture_bound_click_requires_advertised_capture_id_schema(self) -> None:self.assertFalse(supports_capture_bound_click(diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_fixture_server.py b/libs/cua-driver/examples/jev-use/python/tests/test_fixture_server.pyindex 271ef6c27a..093fb60d4b 100644--- a/libs/cua-driver/examples/jev-use/python/tests/test_fixture_server.py+++ b/libs/cua-driver/examples/jev-use/python/tests/test_fixture_server.py@@ -39,5 +39,35 @@ class FixtureServerTest(unittest.TestCase):self.assertEqual(json.loads(response.read()), {"submitted": None})+ def test_default_page_keeps_the_dom_submit_button(self) -> None:+ with self.request("/") as response:+ page = response.read().decode()+ self.assertIn('<button type="submit">Submit</button>', page)+++class VisualFixtureServerTest(unittest.TestCase):+ def test_visual_page_has_no_submit_button_and_still_submits(self) -> None:+ server = FixtureServer(("127.0.0.1", 0), visual=True)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ url = f"http://127.0.0.1:{server.server_port}"+ with urlopen(f"{url}/", timeout=2) as response:+ page = response.read().decode()+ self.assertNotIn("<button", page)+ self.assertIn('role="presentation"', page)+ self.assertIn("requestSubmit()", page)+ self.assertIn('aria-label="verification value"', page)+ data = urlencode({"value": "proof"}).encode()+ with urlopen(Request(f"{url}/submit", method="POST", data=data), timeout=2):+ pass+ with urlopen(f"{url}/state", timeout=2) as response:+ self.assertEqual(json.loads(response.read()), {"submitted": "proof"})+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)++if __name__ == "__main__":unittest.main()diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_verify_setup.py b/libs/cua-driver/examples/jev-use/python/tests/test_verify_setup.pyindex 3825bff0b8..2588ab4e18 100644--- a/libs/cua-driver/examples/jev-use/python/tests/test_verify_setup.py+++ b/libs/cua-driver/examples/jev-use/python/tests/test_verify_setup.py@@ -12,7 +12,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[2]))-from verify_setup import BASE, fixture, runner_command, verify+from verify_setup import BASE, acted_path, fixture, runner_command, verifyCHILD = """@@ -101,5 +101,120 @@ class VerifySetupTests(unittest.TestCase):self.assertFalse(output.exists())+ def write_log(self, directory, events):+ log = Path(directory) / 'run.jsonl'+ log.write_text(''.join(json.dumps(event) + '\n' for event in events))+ return log++ def submit_step(self, tool, status):+ visual = {'status': status}+ if status == 'ok':+ visual.update(capture_id='capture-1', region_count=3)+ return {'event': 'step', 'step': 2, 'candidate': 'submit-form', 'tool': tool, 'visual': visual}++ def test_acted_path_reports_dom_and_visual_submissions(self):+ type_step = {'event': 'step', 'step': 1, 'candidate': 'type-verification-value',+ 'tool': 'browser_type', 'visual': {'status': 'not_installed', 'error_code': 'not_installed'}}+ self.assertEqual(+ acted_path([type_step, self.submit_step('browser_click', 'not_installed')]),+ {'submit_tool': 'browser_click', 'acted_path': 'page_structure',+ 'submit_delivery_mode': None,+ 'visual_statuses': ['not_installed', 'not_installed'], 'escalations': []},+ )+ self.assertEqual(+ acted_path([type_step, self.submit_step('click', 'ok')])['acted_path'], 'visual'+ )+ self.assertEqual(acted_path([type_step])['acted_path'], None)++ def replay(self, events, *, submit=True, code='0', **options):+ """Run a child that replays a JSONL log and optionally submits the token."""+ child = (+ "import sys\n"+ "from pathlib import Path\n"+ "from urllib.parse import urlencode\n"+ "from urllib.request import Request, urlopen\n"+ "url, source, log, submit, code = sys.argv[1:]\n"+ "if submit == '1':\n"+ " urlopen(Request(url + 'submit', data=urlencode({'value': 'proof'}).encode()), timeout=2).close()\n"+ "Path(log).write_text(Path(source).read_text())\n"+ "raise SystemExit(int(code))\n"+ )+ with tempfile.TemporaryDirectory() as directory, \+ fixture(visual=options.get('visual_fixture', False)) as url:+ source = self.write_log(directory, events)+ log = Path(directory) / 'out.jsonl'+ command = [sys.executable, '-c', child, url, str(source), str(log), '1' if submit else '0', code]+ return verify(command, url, 'proof', log, **options)++ def verified(self, tool, status):+ return [self.submit_step(tool, status), {'event': 'outcome', 'outcome': 'verified', 'token': 'proof'}]++ def test_reports_page_structure_path(self):+ result = self.replay(self.verified('browser_click', 'not_installed'))+ self.assertEqual(result['acted_path'], 'page_structure')+ self.assertEqual(result['submit_tool'], 'browser_click')++ def test_required_visual_path_fails_when_dom_click_acted(self):+ with self.assertRaisesRegex(RuntimeError, 'Visual path was required.*browser_click'):+ self.replay(self.verified('browser_click', 'ok'), require_visual=True)++ def test_required_visual_path_accepts_capture_bound_click(self):+ result = self.replay(self.verified('click', 'ok'), require_visual=True, visual_fixture=True)+ self.assertEqual(result['acted_path'], 'visual')+ self.assertEqual(result['visual_statuses'], ['ok'])++ def test_expected_visual_status_must_be_logged_on_every_step(self):+ with self.assertRaisesRegex(RuntimeError, "visual status 'not_installed'"):+ self.replay(self.verified('browser_click', 'error'), expect_visual_status='not_installed')++ def test_visual_fixture_fallback_is_observable_and_never_claims_success(self):+ events = [+ {'event': 'step', 'step': 1, 'candidate': 'type-verification-value', 'tool': 'browser_type',+ 'visual': {'status': 'not_installed', 'error_code': 'not_installed'}},+ {'event': 'step', 'step': 2, 'candidate': 'reobserve', 'tool': None,+ 'visual': {'status': 'not_installed', 'error_code': 'not_installed'}},+ {'event': 'outcome', 'outcome': 'budget_exhausted', 'token': 'proof'},+ ]+ result = self.replay(events, submit=False, code='1', visual_fixture=True,+ expect_visual_status='not_installed')+ self.assertEqual(result['outcome'], 'budget_exhausted')+ self.assertIsNone(result['acted_path'])+ self.assertEqual(result['observed'], {'submitted': None})+ with self.assertRaisesRegex(RuntimeError, 'unexpected submission'):+ self.replay(events, submit=True, code='1', visual_fixture=True,+ expect_visual_status='not_installed')+++ def test_skipped_steps_are_not_visual_attempts(self):+ skipped = {'status': 'skipped', 'reason': 'page_structure_candidate'}+ type_step = {'event': 'step', 'step': 1, 'candidate': 'type-verification-value',+ 'tool': 'browser_type', 'visual': skipped}+ events = [type_step, self.submit_step('click', 'ok'),+ {'event': 'outcome', 'outcome': 'verified', 'token': 'proof'}]+ result = self.replay(events, expect_visual_status='ok', require_visual=True, visual_fixture=True)+ self.assertEqual(result['visual_statuses'], ['skipped', 'ok'])+ only_skipped = [+ {**type_step, 'step': 1},+ {'event': 'step', 'step': 2, 'candidate': 'submit-form', 'tool': 'browser_click', 'visual': skipped},+ {'event': 'outcome', 'outcome': 'verified', 'token': 'proof'},+ ]+ with self.assertRaisesRegex(RuntimeError, "visual status 'not_installed'"):+ self.replay(only_skipped, expect_visual_status='not_installed')++ def test_reports_foreground_escalation_after_background_refusal(self):+ refused = {**self.submit_step('click', 'ok'), 'delivery_mode': 'background',+ 'action_error': 'background_unavailable',+ 'escalation': {'from': 'background', 'to': 'foreground', 'reason': 'background_unavailable'}}+ foreground = {**self.submit_step('click', 'ok'), 'step': 3,+ 'candidate': 'submit-form-foreground', 'delivery_mode': 'foreground'}+ events = [refused, foreground, {'event': 'outcome', 'outcome': 'verified', 'token': 'proof'}]+ result = self.replay(events, require_visual=True, visual_fixture=True)+ self.assertEqual(result['acted_path'], 'visual')+ self.assertEqual(result['submit_delivery_mode'], 'foreground')+ self.assertEqual(result['escalations'],+ [{'from': 'background', 'to': 'foreground', 'reason': 'background_unavailable'}])+ self.assertEqual(acted_path([refused])['submit_tool'], None)++if __name__ == '__main__':unittest.main()diff --git a/libs/cua-driver/examples/jev-use/typescript/core.test.ts b/libs/cua-driver/examples/jev-use/typescript/core.test.tsindex 832750f43d..30622a141e 100644--- a/libs/cua-driver/examples/jev-use/typescript/core.test.ts+++ b/libs/cua-driver/examples/jev-use/typescript/core.test.ts@@ -7,12 +7,17 @@ import {buildCandidates,chooseMock,classify,+ hasExecutableCandidate,parseVisualRegions,validateChoice,type Candidate,} from './core.js';import {+ backgroundRefusalCode,+ candidatesForStep,Driver,+ DriverToolError,+ observeVisual,optionalVisualObservation,selectTabId,supportsCaptureBoundClick,@@ -103,6 +108,72 @@ test('visual fixture builds a candidate without claiming interactivity', () => {});});+test('submit path depends on the DOM button ref', () => {+ const visual = parseVisualRegions(+ fixture('parse-visual-regions-submit-v1.json'),+ 'capture-submit',+ 7,+ 9+ );+ const withRef = buildCandidates(snapshot('expected'), 'expected', visual, true);+ assert.equal(withRef[0].id, 'submit-form');+ assert.equal(withRef[0].tool, 'browser_click');+ assert.equal(withRef[0].captureId, undefined);++ const page = snapshot('expected');+ page.refs = page.refs.slice(0, 1);+ const withoutRef = buildCandidates(page, 'expected', visual, true);+ assert.equal(withoutRef[0].id, 'submit-form');+ assert.equal(withoutRef[0].tool, 'click');+ assert.equal(withoutRef[0].captureId, 'capture-submit');+ assert.deepEqual(+ buildCandidates(page, 'expected', undefined, true).map((candidate) => candidate.id),+ ['reobserve', 'abstain']+ );+});++test('visual input does not change a semantic executable candidate set', () => {+ // Salvaged from #4165: when the page structure already offers an executable+ // action, a visual observation cannot change the candidates.+ const visual = parseVisualRegions(+ fixture('parse-visual-regions-submit-v1.json'),+ 'capture-submit',+ 7,+ 9+ );+ for (const value of [null, 'expected']) {+ const withoutVisual = buildCandidates(snapshot(value), 'expected', undefined, true);+ const withVisual = buildCandidates(snapshot(value), 'expected', visual, true);+ assert.deepEqual(withVisual, withoutVisual);+ assert.ok(hasExecutableCandidate(withoutVisual));+ }+});++test('foreground escalation is a distinct visual candidate', () => {+ const visual = parseVisualRegions(+ fixture('parse-visual-regions-submit-v1.json'),+ 'capture-submit',+ 7,+ 9+ );+ const page = snapshot('expected');+ page.refs = page.refs.slice(0, 1);+ const candidates = buildCandidates(page, 'expected', visual, true, 'foreground');+ assert.deepEqual(+ candidates.map((candidate) => candidate.id),+ ['submit-form-foreground', 'reobserve', 'abstain']+ );+ assert.equal(candidates[0].tool, 'click');+ assert.equal(candidates[0].arguments.delivery_mode, 'foreground');+ assert.equal(candidates[0].arguments.capture_id, 'capture-submit');+ assert.match(candidates[0].description, /foreground/);+ assert.equal(chooseMock(candidates).choice, 'submit-form-foreground');+ assert.equal(+ buildCandidates(snapshot('expected'), 'expected', visual, true, 'foreground')[0].tool,+ 'browser_click'+ );+});+test('ambiguous visual regions offer only reobserve and abstain', () => {const payload = fixture('parse-visual-regions-ambiguous-v1.json');for (const region of payload.regions) region.interactive = false;@@ -343,6 +414,229 @@ test('visual tool is optional and uses the public contract when advertised', asy]);});+test('visual status is logged for ok, not_installed, and error', async () => {+ const tools = new Set(['get_window_state', 'parse_visual_regions', 'click']);+ const payload = fixture('parse-visual-regions-submit-v1.json');+ function scripted(parseResult: unknown) {+ const calls: string[] = [];+ const client = {+ callTool: async (request: { name: string }) => {+ calls.push(request.name);+ if (request.name === 'get_window_state') {+ return { isError: false, structuredContent: { capture_id: 'capture-submit' } };+ }+ return parseResult;+ },+ };+ return { driver: new Driver(client as never, 'jev-test'), calls };+ }++ const ok = await observeVisual(+ scripted({ isError: false, structuredContent: payload }).driver,+ 7,+ 9,+ tools,+ true+ );+ assert.equal(ok.visual?.captureId, 'capture-submit');+ assert.deepEqual(ok.status, {+ status: 'ok',+ capture_id: 'capture-submit',+ region_count: ok.visual?.regions.length,+ });++ const notInstalled = await observeVisual(+ scripted({ isError: true, structuredContent: { code: 'not_installed' }, content: [] }).driver,+ 7,+ 9,+ tools,+ true+ );+ assert.equal(notInstalled.visual, undefined);+ assert.deepEqual(notInstalled.status, { status: 'not_installed', error_code: 'not_installed' });++ const workerFailed = await observeVisual(+ scripted({ isError: true, structuredContent: { code: 'worker_failed' }, content: [] }).driver,+ 7,+ 9,+ tools,+ true+ );+ assert.deepEqual(workerFailed.status, { status: 'error', error_code: 'worker_failed' });++ const stalePayload = structuredClone(payload);+ stalePayload.capture.capture_id = 'older-capture';+ const stale = await observeVisual(+ scripted({ isError: false, structuredContent: stalePayload }).driver,+ 7,+ 9,+ tools,+ true+ );+ assert.equal(stale.visual, undefined);+ assert.deepEqual(stale.status, { status: 'error', error_code: 'capture_mismatch' });++ const malformed = await observeVisual(+ scripted({ isError: false, structuredContent: { ...payload, regions: 'bad' } }).driver,+ 7,+ 9,+ tools,+ true+ );+ assert.deepEqual(malformed.status, { status: 'error', error_code: 'invalid_visual_result' });++ const uncoded = await observeVisual(+ scripted({ isError: true, content: [] }).driver,+ 7,+ 9,+ tools,+ true+ );+ assert.deepEqual(uncoded.status, { status: 'error', error_code: 'driver_error' });++ const idle = scripted({ isError: false, structuredContent: payload });+ assert.deepEqual((await observeVisual(idle.driver, 7, 9, new Set(['click']), true)).status, {+ status: 'unavailable',+ error_code: 'tool_not_advertised',+ });+ assert.deepEqual((await observeVisual(idle.driver, 7, 9, tools, false)).status, {+ status: 'unavailable',+ error_code: 'capture_bound_click_unsupported',+ });+ assert.deepEqual(idle.calls, []);+});++test('driver errors carry the structured error code', async () => {+ const client = {+ callTool: async () => ({ isError: true, structuredContent: { code: 'not_installed' }, content: [] }),+ };+ await assert.rejects(+ () => new Driver(client as never, 'jev-test').call('parse_visual_regions', {}),+ (error: unknown) => error instanceof DriverToolError && error.code === 'not_installed'+ );+});++function pageWith(submitRef: boolean) {+ const refs: { role: string; name: string; ref: string; value?: string }[] = [+ { role: 'textbox', name: 'verification value', ref: 'p1:0', value: 'expected' },+ ];+ if (submitRef) refs.push({ role: 'button', name: 'Submit', ref: 'p1:1' });+ return { target_id: 'target', tab_id: 'tab', refs };+}++function recordingDriver(responses: unknown[] = []) {+ const calls: string[] = [];+ const client = {+ callTool: async (request: { name: string }) => {+ calls.push(request.name);+ return { isError: false, structuredContent: responses.shift() ?? { status: 'ok' } };+ },+ };+ return { driver: new Driver(client as never, 'jev-test'), calls };+}++test('visual parse runs only when it can contribute a candidate', async () => {+ const tools = new Set(['get_window_state', 'parse_visual_regions', 'click']);+ const payload = () => fixture('parse-visual-regions-submit-v1.json');++ let rec = recordingDriver();+ let step = await candidatesForStep(rec.driver, pageWith(true), 'expected', 7, 9, tools, true);+ assert.equal(step.candidates[0].tool, 'browser_click');+ assert.equal(step.visual, undefined);+ assert.deepEqual(step.status, { status: 'skipped', reason: 'page_structure_candidate' });+ step = await candidatesForStep(rec.driver, pageWith(false), 'expected', 7, 9, tools, true, 'off');+ assert.deepEqual(step.status, { status: 'skipped', reason: 'disabled' });+ assert.deepEqual(rec.calls, []);++ rec = recordingDriver([{ capture_id: 'capture-submit' }, payload()]);+ step = await candidatesForStep(rec.driver, pageWith(false), 'expected', 7, 9, tools, true);+ assert.deepEqual(rec.calls, ['get_window_state', 'parse_visual_regions']);+ assert.equal(step.status.status, 'ok');+ assert.equal(step.candidates[0].tool, 'click');+ assert.equal(step.candidates[0].arguments.delivery_mode, 'background');++ rec = recordingDriver([{ capture_id: 'capture-submit' }, payload()]);+ step = await candidatesForStep(rec.driver, pageWith(true), 'expected', 7, 9, tools, true, 'always');+ assert.equal(step.status.status, 'ok');+ assert.equal(step.visual?.captureId, 'capture-submit');+ assert.equal(step.candidates[0].tool, 'browser_click');++ rec = recordingDriver([{ capture_id: 'capture-submit' }, payload()]);+ step = await candidatesForStep(+ rec.driver,+ pageWith(false),+ 'expected',+ 7,+ 9,+ tools,+ true,+ 'auto',+ 'foreground'+ );+ assert.equal(step.candidates[0].id, 'submit-form-foreground');+ assert.equal(step.candidates[0].arguments.delivery_mode, 'foreground');+});++test('structured background refusal escalates but other errors do not', async () => {+ const args = { pid: 7, window_id: 9, x: 1, y: 1, capture_id: 'c' };+ const background = {+ id: 'submit-form',+ description: 'visual',+ tool: 'click',+ arguments: { ...args, delivery_mode: 'background' },+ captureId: 'c',+ };+ const foreground = {+ ...background,+ id: 'submit-form-foreground',+ arguments: { ...args, delivery_mode: 'foreground' },+ };+ const dom = { id: 'submit-form', description: 'dom', tool: 'browser_click', arguments: { ref: 'p1:1' } };+ assert.equal(+ backgroundRefusalCode(background, new DriverToolError('refused', 'background_unavailable')),+ 'background_unavailable'+ );+ assert.equal(+ backgroundRefusalCode(background, new DriverToolError('refused', 'background_occluded')),+ 'background_occluded'+ );+ assert.equal(+ backgroundRefusalCode(background, new DriverToolError('refused', 'some_new_code', 'foreground')),+ 'some_new_code'+ );+ assert.equal(+ backgroundRefusalCode(background, new DriverToolError('stale', 'capture_generation_mismatch')),+ undefined+ );+ assert.equal(backgroundRefusalCode(background, new Error('background_unavailable')), undefined);+ assert.equal(+ backgroundRefusalCode(foreground, new DriverToolError('refused', 'background_unavailable')),+ undefined+ );+ assert.equal(+ backgroundRefusalCode(dom, new DriverToolError('refused', 'background_unavailable')),+ undefined+ );++ const client = {+ callTool: async () => ({+ isError: true,+ structuredContent: {+ code: 'background_unavailable',+ escalation: { recommended: 'foreground', reason: 'chromium' },+ },+ content: [],+ }),+ };+ await assert.rejects(+ () => new Driver(client as never, 'jev-test').call('click', background.arguments),+ (error: unknown) =>+ error instanceof DriverToolError &&+ error.recommendedDelivery === 'foreground' &&+ backgroundRefusalCode(background, error) === 'background_unavailable'+ );+});+test('capture-bound click requires capture_id in the advertised schema', () => {assert.equal(supportsCaptureBoundClick([{ name: 'click', inputSchema: { properties: { x: {} } } }]),diff --git a/libs/cua-driver/examples/jev-use/typescript/core.ts b/libs/cua-driver/examples/jev-use/typescript/core.tsindex fc7145fdd3..4dd6756467 100644--- a/libs/cua-driver/examples/jev-use/typescript/core.ts+++ b/libs/cua-driver/examples/jev-use/typescript/core.ts@@ -1,4 +1,7 @@export type Outcome = 'verified' | 'refuted' | 'unknown' | 'abstained' | 'budget_exhausted';+export type VisualDelivery = 'background' | 'foreground';++export const SUBMIT_IDS: ReadonlySet<string> = new Set(['submit-form', 'submit-form-foreground']);export type Candidate = Readonly<{id: string;@@ -52,6 +55,16 @@ export type VisualObservation = Readonly<{regions: readonly VisualRegion[];}>;+export class VisualObservationError extends Error {+ constructor(+ message: string,+ readonly code: string = 'invalid_visual_result'+ ) {+ super(message);+ this.name = 'VisualObservationError';+ }+}+function record(value: unknown, message: string): Record<string, unknown> {if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(message);return value as Record<string, unknown>;@@ -92,7 +105,10 @@ export function parseVisualRegions(if (root.schema !== 'cua.visual_regions_v1') throw new Error('unsupported visual region schema');const capture = record(root.capture, 'visual result has no capture provenance');if (capture.capture_id !== expectedCaptureId) {- throw new Error('visual result is stale or capture-mismatched');+ throw new VisualObservationError(+ 'visual result is stale or capture-mismatched',+ 'capture_mismatch'+ );}const source = record(capture.source, 'visual result has no capture source');if (@@ -100,7 +116,10 @@ export function parseVisualRegions(source.pid !== expectedPid ||source.window_id !== expectedWindowId) {- throw new Error('visual result has a mismatched window target');+ throw new VisualObservationError(+ 'visual result has a mismatched window target',+ 'capture_mismatch'+ );}const screenshot = record(capture.screenshot, 'visual result has no screenshot provenance');if (screenshot.mime_type !== 'image/png') {@@ -208,11 +227,19 @@ function reservedCandidates(): Candidate[] {];}+/**+ * Build the closed candidate set for one decision. Page-structure refs always+ * win. The capture-bound visual Submit is offered only when no Submit ref+ * exists. visualDelivery 'foreground' replaces the background visual click with+ * a distinct submit-form-foreground candidate after Driver refused background+ * delivery; the chooser must pick it explicitly.+ */export function buildCandidates(snapshot: BrowserSnapshot,token: string,visual?: VisualObservation,- captureBoundClick = false+ captureBoundClick = false,+ visualDelivery: VisualDelivery = 'background'): Candidate[] {const common = { target_id: snapshot.target_id, tab_id: snapshot.tab_id };const refs = snapshot.refs ?? [];@@ -253,10 +280,15 @@ export function buildCandidates(const region = matches[0];const x = region.x + region.width / 2;const y = region.y + region.height / 2;+ const foreground = visualDelivery === 'foreground';candidates.push(immutableCandidate({- id: 'submit-form',- description: 'Submit the form using the unique validated visual Submit region.',+ id: foreground ? 'submit-form-foreground' : 'submit-form',+ description: foreground+ ? 'Submit the form by clicking the unique validated visual Submit region with ' ++ 'foreground delivery, which activates the browser window, because Driver ' ++ 'refused background delivery for the previous visual click.'+ : 'Submit the form using the unique validated visual Submit region.',tool: 'click',arguments: {pid: visual.pid,@@ -264,7 +296,7 @@ export function buildCandidates(x,y,capture_id: visual.captureId,- delivery_mode: 'background',+ delivery_mode: visualDelivery,},captureId: visual.captureId,screenshotReference: visual.screenshotReference,@@ -275,6 +307,10 @@ export function buildCandidates(return [...candidates, ...reservedCandidates()];}+export function hasExecutableCandidate(candidates: readonly Candidate[]): boolean {+ return candidates.some((candidate) => candidate.tool !== null);+}+function asciiLower(value: string): string {return value.replace(/[A-Z]/g, (character) =>String.fromCharCode(character.charCodeAt(0) + 32)@@ -287,9 +323,11 @@ export function chooseMock(candidates: Candidate[]) {? 'type-verification-value': ids.has('submit-form')? 'submit-form'- : ids.has('reobserve')- ? 'reobserve'- : null;+ : ids.has('submit-form-foreground')+ ? 'submit-form-foreground'+ : ids.has('reobserve')+ ? 'reobserve'+ : null;return {choice: selected,confidence: selected ? 1 : 0,diff --git a/libs/cua-driver/examples/jev-use/typescript/run.ts b/libs/cua-driver/examples/jev-use/typescript/run.tsindex da94af26d3..8ad2b1bfb9 100644--- a/libs/cua-driver/examples/jev-use/typescript/run.ts+++ b/libs/cua-driver/examples/jev-use/typescript/run.ts@@ -8,17 +8,25 @@ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'import {buildCandidates,classify,+ hasExecutableCandidate,parseVisualRegions,+ SUBMIT_IDS,validateChoice,+ VisualObservationError,type BrowserSnapshot,+ type Candidate,+ type VisualDelivery,type Outcome,type VisualObservation,} from './core.js';import { driverEnvironment } from './driver_env.js';import { chooseLive, chooseMockAdapter } from './jev_adapter.js';+type VisualMode = 'auto' | 'always' | 'off';+type Arguments = {provider: 'mock' | 'live';+ visualObservation: VisualMode;fixtureUrl: string;token?: string;maxSteps: number;@@ -29,6 +37,7 @@ type Arguments = {function parseArgs(argv: string[]): Arguments {const result: Arguments = {provider: 'mock',+ visualObservation: 'auto',fixtureUrl: 'http://127.0.0.1:8765/',maxSteps: 4,dryRun: false,@@ -41,6 +50,13 @@ function parseArgs(argv: string[]): Arguments {else if (value === '--max-steps') result.maxSteps = Number(argv[++index]);else if (value === '--dry-run') result.dryRun = true;else if (value === '--log') result.log = argv[++index];+ else if (value === '--visual-observation') {+ const mode = argv[++index];+ if (mode !== 'auto' && mode !== 'always' && mode !== 'off') {+ throw new Error('--visual-observation must be auto, always, or off');+ }+ result.visualObservation = mode;+ }else throw new Error(`unknown argument: ${value}`);}if (!Number.isInteger(result.maxSteps) || result.maxSteps < 1) {@@ -73,6 +89,17 @@ export function selectTabId(tabs: Record<string, any>[]): string {return String(tabs.find((tab) => tab.active)?.tab_id ?? tabs[0].tab_id);}+export class DriverToolError extends Error {+ constructor(+ message: string,+ readonly code?: string,+ readonly recommendedDelivery?: string+ ) {+ super(message);+ this.name = 'DriverToolError';+ }+}+export class Driver {constructor(private readonly client: Client,@@ -84,7 +111,20 @@ export class Driver {name,arguments: { ...args, session: this.session },});- if (result.isError) throw new Error(`${name} failed: ${JSON.stringify(result.content)}`);+ if (result.isError) {+ const structured = result.structuredContent as Record<string, unknown> | undefined;+ const code = typeof structured?.code === 'string' && structured.code ? structured.code : undefined;+ const escalation = structured?.escalation as Record<string, unknown> | undefined;+ const recommended =+ typeof escalation?.recommended === 'string' && escalation.recommended+ ? escalation.recommended+ : undefined;+ throw new DriverToolError(+ `${name} failed: ${JSON.stringify(result.content)}`,+ code,+ recommended+ );+ }const data = result.structuredContent as Record<string, any> | undefined;if (!data) throw new Error(`${name} returned no structured result`);if (data.status === 'refused' || data.refusal) {@@ -101,19 +141,66 @@ export function supportsCaptureBoundClick(return Boolean(click?.inputSchema?.properties?.capture_id);}-export async function optionalVisualObservation(+/**+ * Return Driver's code when it refused a background visual click. Only a+ * structured refusal counts: a background_* error code or an explicit+ * escalation.recommended === 'foreground'. Anything else stays a failure.+ */+export function backgroundRefusalCode(candidate: Candidate, error: unknown): string | undefined {+ if (candidate.tool !== 'click' || candidate.arguments.delivery_mode !== 'background') {+ return undefined;+ }+ if (!(error instanceof DriverToolError)) return undefined;+ if (error.code?.startsWith('background_')) return error.code;+ if (error.recommendedDelivery === 'foreground') return error.code ?? 'foreground_recommended';+ return undefined;+}++export type VisualStatus = {+ status: 'ok' | 'not_installed' | 'error' | 'unavailable' | 'skipped';+ reason?: string;+ error_code?: string;+ capture_id?: string;+ region_count?: number;+};++/**+ * Build the redacted per-step visual record written to the JSONL log. It never+ * contains screenshots, screenshot references, region text, or secrets.+ */+export function visualStatus(+ status: VisualStatus['status'],+ errorCode?: string,+ visual?: VisualObservation,+ reason?: string+): VisualStatus {+ const result: VisualStatus = { status };+ if (reason) result.reason = reason;+ if (errorCode) result.error_code = errorCode;+ if (visual) {+ result.capture_id = visual.captureId;+ result.region_count = visual.regions.length;+ }+ return result;+}++/**+ * Take an optional visual observation and report what happened. Failures never+ * stop the run: the caller continues on the page-structure path, but the+ * returned status makes the fallback observable.+ */+export async function observeVisual(driver: Driver,pid: number,windowId: number,availableTools: ReadonlySet<string>,captureBoundClick: boolean-): Promise<VisualObservation | undefined> {- if (- !captureBoundClick ||- !availableTools.has('get_window_state') ||- !availableTools.has('parse_visual_regions')- ) {- return undefined;+): Promise<{ visual?: VisualObservation; status: VisualStatus }> {+ if (!captureBoundClick) {+ return { status: visualStatus('unavailable', 'capture_bound_click_unsupported') };+ }+ if (!availableTools.has('get_window_state') || !availableTools.has('parse_visual_regions')) {+ return { status: visualStatus('unavailable', 'tool_not_advertised') };}try {const capture = await driver.call('get_window_state', {@@ -121,15 +208,81 @@ export async function optionalVisualObservation(window_id: windowId,include_accessibility_tree: false,});- if (typeof capture.capture_id !== 'string') return undefined;+ if (typeof capture.capture_id !== 'string') {+ return { status: visualStatus('error', 'capture_missing') };+ }const result = await driver.call('parse_visual_regions', {capture_id: capture.capture_id,options: { kinds: ['text', 'icon'], min_confidence: 0.8, max_regions: 100 },});- return parseVisualRegions(result, capture.capture_id, pid, windowId);- } catch {- return undefined;+ const visual = parseVisualRegions(result, capture.capture_id, pid, windowId);+ return { visual, status: visualStatus('ok', undefined, visual) };+ } catch (error: unknown) {+ if (error instanceof DriverToolError) {+ if (error.code === 'not_installed') {+ return { status: visualStatus('not_installed', 'not_installed') };+ }+ return { status: visualStatus('error', error.code ?? 'driver_error') };+ }+ if (error instanceof VisualObservationError) {+ return { status: visualStatus('error', error.code) };+ }+ // parseVisualRegions reports other contract violations as plain errors.+ if (error instanceof Error && /^(visual (result|region)|unsupported visual)/.test(error.message)) {+ return { status: visualStatus('error', 'invalid_visual_result') };+ }+ return { status: visualStatus('error', 'driver_error') };+ }+}++export async function optionalVisualObservation(+ driver: Driver,+ pid: number,+ windowId: number,+ availableTools: ReadonlySet<string>,+ captureBoundClick: boolean+): Promise<VisualObservation | undefined> {+ return (await observeVisual(driver, pid, windowId, availableTools, captureBoundClick)).visual;+}++/**+ * Build one step's candidates, parsing visual regions only when useful. In+ * auto mode the capture and parse run only when the page structure offers no+ * executable candidate, because only then can a visual region add one. always+ * restores the per-step parse; off never parses.+ */+export async function candidatesForStep(+ driver: Driver,+ snapshot: BrowserSnapshot,+ token: string,+ pid: number,+ windowId: number,+ availableTools: ReadonlySet<string>,+ captureBoundClick: boolean,+ visualMode: VisualMode = 'auto',+ visualDelivery: VisualDelivery = 'background'+): Promise<{ candidates: Candidate[]; visual?: VisualObservation; status: VisualStatus }> {+ let candidates = buildCandidates(snapshot, token, undefined, captureBoundClick, visualDelivery);+ if (visualMode === 'off') {+ return { candidates, status: visualStatus('skipped', undefined, undefined, 'disabled') };+ }+ if (visualMode === 'auto' && hasExecutableCandidate(candidates)) {+ return {+ candidates,+ status: visualStatus('skipped', undefined, undefined, 'page_structure_candidate'),+ };}+ const { visual, status } = await observeVisual(+ driver,+ pid,+ windowId,+ availableTools,+ captureBoundClick+ );+ if (visual) {+ candidates = buildCandidates(snapshot, token, visual, captureBoundClick, visualDelivery);+ }+ return { candidates, visual, status };}async function fixtureState(fixtureUrl: string): Promise<{ submitted: string | null }> {@@ -175,6 +328,7 @@ async function run(args: Arguments): Promise<Outcome> {});const client = new Client({ name: 'cua-driver-jev-use-example', version: '0.1.0' });const history: Record<string, unknown>[] = [];+ let visualDelivery: VisualDelivery = 'background';if (args.log) await writeFile(args.log, '', 'utf8');await resetFixture(args.fixtureUrl);@@ -216,16 +370,28 @@ async function run(args: Arguments): Promise<Outcome> {tab_id: tabId,snapshot_format: 'semantic_v2',})) as BrowserSnapshot;- const visual = await optionalVisualObservation(+ const {+ candidates,+ visual,+ status: visualRecord,+ } = await candidatesForStep(driver,+ snapshot,+ token,pid,Number(window.window_id),availableTools,- captureBoundClick+ captureBoundClick,+ args.visualObservation,+ visualDelivery);- const candidates = buildCandidates(snapshot, token, visual, captureBoundClick);if (!candidates.length) {- await writeEvent(args.log, { event: 'outcome', outcome: 'abstained', step });+ await writeEvent(args.log, {+ event: 'outcome',+ outcome: 'abstained',+ step,+ visual: visualRecord,+ });return 'abstained';}const answer =@@ -246,6 +412,8 @@ async function run(args: Arguments): Promise<Outcome> {decision_ms: decisionMs,action_ms: 0,dry_run: args.dryRun,+ tool: null,+ visual: visualRecord,};history.push(event);await writeEvent(args.log, event);@@ -259,6 +427,7 @@ async function run(args: Arguments): Promise<Outcome> {step,confidence: answer.confidence,probabilities: answer.probabilities,+ visual: visualRecord,});return 'abstained';}@@ -270,12 +439,38 @@ async function run(args: Arguments): Promise<Outcome> {if (!candidate.tool) throw new Error('selected candidate has no executable tool');await driver.call(candidate.tool, candidate.arguments);} catch (error: unknown) {+ const refusal = backgroundRefusalCode(candidate, error);+ if (refusal) {+ // Do not retry background. The next step takes a fresh capture and+ // offers a distinct foreground candidate.+ visualDelivery = 'foreground';+ const event = {+ event: 'step',+ step,+ candidate: candidate.id,+ confidence: answer.confidence,+ probabilities: answer.probabilities,+ decision_ms: decisionMs,+ action_ms: Math.round((performance.now() - actionStarted) * 100) / 100,+ dry_run: args.dryRun,+ tool: candidate.tool,+ delivery_mode: 'background',+ action_error: refusal,+ escalation: { from: 'background', to: 'foreground', reason: refusal },+ visual: visualRecord,+ };+ history.push(event);+ await writeEvent(args.log, event);+ continue;+ }await writeEvent(args.log, {event: 'outcome',outcome: 'unknown',step,phase: 'action',error: error instanceof Error ? error.name : 'UnknownError',+ tool: candidate.tool,+ visual: visualRecord,});return 'unknown';}@@ -290,11 +485,14 @@ async function run(args: Arguments): Promise<Outcome> {decision_ms: decisionMs,action_ms: actionMs,dry_run: args.dryRun,+ tool: candidate.tool,+ delivery_mode: candidate.arguments.delivery_mode ?? null,+ visual: visualRecord,};history.push(event);await writeEvent(args.log, event);if (args.dryRun) return 'unknown';- if (candidate.id === 'submit-form') {+ if (SUBMIT_IDS.has(candidate.id)) {for (let attempt = 0; attempt < 20; attempt += 1) {const oracle = await fixtureState(args.fixtureUrl);const outcome = classify(oracle.submitted, token, step, args.maxSteps);diff --git a/libs/cua-driver/examples/jev-use/verify_setup.py b/libs/cua-driver/examples/jev-use/verify_setup.pyindex 5a85df7fbc..e74b55e984 100644--- a/libs/cua-driver/examples/jev-use/verify_setup.py+++ b/libs/cua-driver/examples/jev-use/verify_setup.py@@ -17,9 +17,13 @@ from fixture_server import FixtureServerBASE = Path(__file__).resolve().parent+VISUAL_STATUSES = ('ok', 'not_installed', 'error', 'unavailable')+SUBMIT_IDS = ('submit-form', 'submit-form-foreground')++@contextmanager-def fixture(port: int = 0):- with FixtureServer(('127.0.0.1', port)) as server:+def fixture(port: int = 0, *, visual: bool = False):+ with FixtureServer(('127.0.0.1', port), visual=visual) as server:thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()try:@@ -29,17 +33,86 @@ def fixture(port: int = 0):thread.join(timeout=5)-def verify(command: list[str], url: str, token: str, log: Path) -> dict:- subprocess.run(command, cwd=BASE, check=True, timeout=180)- events = [json.loads(line) for line in log.read_text().splitlines()]+def acted_path(events: list[dict]) -> dict:+ """Report which Driver path acted, from the runner's redacted JSONL log.++ ``submit_tool`` is ``browser_click`` for the DOM page-structure path, ``click``+ for the capture-bound visual path, or ``None`` when nothing submitted.+ """+ steps = [event for event in events if event.get('event') == 'step']+ submits = [+ event for event in steps+ if event.get('candidate') in SUBMIT_IDS and not event.get('action_error')+ ]+ statuses = [+ event['visual']['status'] if isinstance(event.get('visual'), dict) else None+ for event in events+ if event.get('event') == 'step' or 'visual' in event+ ]+ tool = submits[-1].get('tool') if submits else None+ path = {'browser_click': 'page_structure', 'click': 'visual'}.get(tool) if tool else None+ return {+ 'submit_tool': tool,+ 'acted_path': path,+ 'submit_delivery_mode': submits[-1].get('delivery_mode') if submits else None,+ 'visual_statuses': statuses,+ 'escalations': [event['escalation'] for event in steps if isinstance(event.get('escalation'), dict)],+ }+++def verify(+ command: list[str],+ url: str,+ token: str,+ log: Path,+ *,+ require_visual: bool = False,+ expect_visual_status: str | None = None,+ visual_fixture: bool = False,+) -> dict:+ """Run one runner and independently verify what it did.++ With ``expect_visual_status`` other than ``ok`` on the visual fixture, no+ page-structure Submit exists, so the correct result is a logged fallback+ that never submits and never claims success.+ """+ expect_fallback = visual_fixture and expect_visual_status not in (None, 'ok')+ completed = subprocess.run(command, cwd=BASE, check=False, timeout=180)+ events = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []+ path = acted_path(events)+ if expect_visual_status is not None:+ # Steps that skipped the parse because the page structure already offered+ # an action are not visual attempts; at least one attempt must exist.+ attempted = [status for status in path['visual_statuses'] if status != 'skipped']+ if not attempted or any(status != expect_visual_status for status in attempted):+ raise RuntimeError(+ f'Runner did not log visual status {expect_visual_status!r} on every step: '+ f'{path["visual_statuses"]}'+ )+ with urlopen(url + 'state', timeout=2) as response:+ observed = json.load(response)+ if expect_fallback:+ if path['submit_tool'] is not None:+ raise RuntimeError('Runner submitted without a usable visual observation')+ if observed != {'submitted': None}:+ raise RuntimeError('Independent fixture state shows an unexpected submission')+ final = events[-1] if events else {}+ if final.get('event') != 'outcome' or final.get('outcome') == 'verified':+ raise RuntimeError('Runner did not report a non-verified fallback outcome')+ return {'outcome': final['outcome'], 'token': token, 'observed': observed, **path}+ if completed.returncode != 0:+ raise subprocess.CalledProcessError(completed.returncode, command)expected = {'event': 'outcome', 'outcome': 'verified', 'token': token}if not events or events[-1] != expected:raise RuntimeError('Runner did not report the expected verified outcome')- with urlopen(url + 'state', timeout=2) as response:- observed = json.load(response)if observed != {'submitted': token}:raise RuntimeError('Independent fixture state does not match the expected token')- return {'outcome': 'verified', 'token': token, 'observed': observed}+ if require_visual and path['acted_path'] != 'visual':+ raise RuntimeError(+ 'Visual path was required but the runner submitted with '+ f'{path["submit_tool"] or "no action"}; visual statuses: {path["visual_statuses"]}'+ )+ return {'outcome': 'verified', 'token': token, 'observed': observed, **path}def require_key() -> None:@@ -66,14 +139,32 @@ def main() -> None:parser.add_argument('--port', type=int, default=0, help='fixture port; defaults to an unused loopback port')parser.add_argument('--max-steps', type=int, default=4, help='maximum decisions per runner')parser.add_argument('--output-dir', type=Path, required=True, help='new directory for evidence; existing paths are refused')+ parser.add_argument('--visual-fixture', action='store_true',+ help='serve a Submit control with no DOM button ref so only the capture-bound visual click can submit')+ parser.add_argument('--require-visual-path', action='store_true',+ help='fail unless every runner submitted through the capture-bound visual click')+ parser.add_argument('--expect-visual-status', choices=VISUAL_STATUSES,+ help='fail unless every step that attempted a visual observation logs this status; '+ 'with --visual-fixture and a non-ok status, '+ 'require a logged fallback that never submits')args = parser.parse_args()+ if args.require_visual_path and args.expect_visual_status not in (None, 'ok'):+ parser.error('--require-visual-path needs a working visual observation')if args.live:require_key()output = args.output_dir.resolve()output.mkdir(mode=0o700, parents=True, exist_ok=False)- summary = {'complete': False, 'live_requested': args.live, 'typescript_requested': args.typescript, 'checks': []}+ summary = {+ 'complete': False,+ 'live_requested': args.live,+ 'typescript_requested': args.typescript,+ 'fixture': 'visual' if args.visual_fixture else 'default',+ 'visual_path_required': args.require_visual_path,+ 'expected_visual_status': args.expect_visual_status,+ 'checks': [],+ }try:- with fixture(args.port) as url:+ with fixture(args.port, visual=args.visual_fixture) as url:print(json.dumps({'event': 'fixture_ready', 'url': url}), flush=True)summary['fixture_url'] = urlfor language in (['python', 'typescript'] if args.typescript else ['python']):@@ -82,7 +173,19 @@ def main() -> None:log = output / f'{language}-{provider}.jsonl'command = runner_command(language, provider)command += ['--fixture-url', url, '--token', token, '--max-steps', str(args.max_steps), '--log', str(log)]- result = {'language': language, 'provider': provider, **verify(command, url, token, log)}+ result = {+ 'language': language,+ 'provider': provider,+ **verify(+ command,+ url,+ token,+ log,+ require_visual=args.require_visual_path,+ expect_visual_status=args.expect_visual_status,+ visual_fixture=args.visual_fixture,+ ),+ }summary['checks'].append(result)print(json.dumps({'event': 'independently_verified', **result}), flush=True)summary['complete'] = True