Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): keep the jev-use visual path choosing actions when Submit is visual-only (#4266)

Francesco Bonacci4b933fb1f19b
diff --git a/libs/cua-driver/examples/jev-use/README.md b/libs/cua-driver/examples/jev-use/README.md
index 0e1c2842e7..90263a058d 100644
--- a/libs/cua-driver/examples/jev-use/README.md
+++ b/libs/cua-driver/examples/jev-use/README.md
@@ -18,9 +18,14 @@ candidate IDs and descriptions plus a compact observation. When visual regions
are present, that observation includes their typed bounds and the exact
`capture_id`; it never includes screenshot bytes or extension internals. The
observation also carries a `form` summary that the runner derives from the page
-structure. The summary reports whether the verification field is `empty`, holds
-the required token (`contains_required_token`), or holds `contains_other_value`,
-and whether a Submit button ref is `available`. The token itself is replaced
+structure and any validated visual regions. The summary reports whether the
+verification field is `empty`, holds the required token
+(`contains_required_token`), or holds `contains_other_value`. It also reports
+the Submit control: `available` for a page-structure button ref. When there is
+no ref and the capture-bound visual path is enabled, it reports `visual_only`
+for a unique validated visual Submit region, `visual_check_pending` before that
+step's visual regions are parsed, or `not_found_visually`. Without a visual path,
+it reports `not_in_page_structure`. The token itself is replaced
with `[verification token]` in the page, outline, and visual text. `history` lists
one `{step, selected_id, outcome}` item per earlier decision. Timings and model
probabilities stay in the JSONL log only. A live answer must be one of the supplied IDs before the runner resolves it to the
diff --git a/libs/cua-driver/examples/jev-use/fixtures/jev-visual-replay-v1.json b/libs/cua-driver/examples/jev-use/fixtures/jev-visual-replay-v1.json
new file mode 100644
index 0000000000..38b330c707
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/fixtures/jev-visual-replay-v1.json
@@ -0,0 +1,838 @@
+{
+ "schema": "cua.jev_use_visual_replay_v1",
+ "description": "Visual-path fixture (--visual-fixture: Submit is a presentational element with no button ref). Snapshots are real get_browser_state semantic_v2 results and visual_regions is a real parse_visual_regions result, captured on Linux X11 with released Cua Driver 0.30.1 and cua-perception 0.2.1. recorded_live_runs are the step choices TypeSafe Jev made in live visual-fixture runs: *_pre_4255 before the filled-form-state change (all verified) and *_post_4255_regression after it (Jev reobserved at step 1 every time). pre_fix_step1 is the exact state and candidate criteria the runner sent Jev at step 1 in those regressed runs.",
+ "token": "jev-guide-live",
+ "snapshots": {
+ "before_typing": {
+ "outline": "- main\n - heading \"Cua Driver + TypeSafe Jev fixture\"\n - paragraph\n - statictext \"Enter the verification value and submit it.\"\n - form\n - generic [editable=\"plaintext\"]\n - textbox \"verification value\" [editable=\"plaintext\",focusable=true,required=true]\n - statictext \"Submit\"\n - status\n - statictext \"status=waiting\"",
+ "page": {
+ "title": "about:blank",
+ "url": "http://127.0.0.1:41605/"
+ },
+ "refs": [
+ {
+ "actions": ["type", "pointer"],
+ "frame": "main",
+ "name": "verification value",
+ "ref": "p1:0",
+ "role": "textbox",
+ "states": {
+ "editable": "plaintext",
+ "focusable": true,
+ "required": true
+ },
+ "value": null,
+ "visibility": "in_viewport"
+ },
+ {
+ "actions": ["click", "pointer"],
+ "frame": "main",
+ "name": "Submit",
+ "ref": "p1:1",
+ "role": "statictext",
+ "states": {},
+ "value": null,
+ "visibility": "in_viewport"
+ },
+ {
+ "actions": ["type"],
+ "frame": "main",
+ "name": null,
+ "ref": "p1:10",
+ "role": "generic",
+ "states": {
+ "editable": "plaintext"
+ },
+ "value": null,
+ "visibility": "unknown"
+ }
+ ],
+ "tab_id": "tab-11edc8ea-1185-4d45-be26-6df2f7082d7e",
+ "target_id": "bt-aeb40534-c16c-4da9-9567-aee3d2d4958a"
+ },
+ "after_typing": {
+ "outline": "- main\n - heading \"Cua Driver + TypeSafe Jev fixture\"\n - paragraph\n - statictext \"Enter the verification value and submit it.\"\n - form\n - textbox \"verification value\": jev-guide-live [editable=\"plaintext\",focusable=true,focused=true,required=true]\n - generic [editable=\"plaintext\"]\n - statictext \"Submit\"\n - status\n - statictext \"jev-guide-live\" [editable=\"plaintext\"]\n - statictext \"status=waiting\"",
+ "page": {
+ "title": "about:blank",
+ "url": "http://127.0.0.1:41605/"
+ },
+ "refs": [
+ {
+ "actions": ["type", "pointer"],
+ "frame": "main",
+ "name": "verification value",
+ "ref": "p2:1",
+ "role": "textbox",
+ "states": {
+ "editable": "plaintext",
+ "focusable": true,
+ "focused": true,
+ "required": true
+ },
+ "value": "jev-guide-live",
+ "visibility": "in_viewport"
+ },
+ {
+ "actions": ["click", "pointer"],
+ "frame": "main",
+ "name": "Submit",
+ "ref": "p2:2",
+ "role": "statictext",
+ "states": {},
+ "value": null,
+ "visibility": "in_viewport"
+ },
+ {
+ "actions": ["type"],
+ "frame": "main",
+ "name": null,
+ "ref": "p2:10",
+ "role": "generic",
+ "states": {
+ "editable": "plaintext"
+ },
+ "value": null,
+ "visibility": "unknown"
+ },
+ {
+ "actions": ["type"],
+ "frame": "main",
+ "name": "jev-guide-live",
+ "ref": "p2:11",
+ "role": "statictext",
+ "states": {
+ "editable": "plaintext"
+ },
+ "value": null,
+ "visibility": "unknown"
+ }
+ ],
+ "tab_id": "tab-11edc8ea-1185-4d45-be26-6df2f7082d7e",
+ "target_id": "bt-aeb40534-c16c-4da9-9567-aee3d2d4958a"
+ }
+ },
+ "visual_regions": {
+ "capture": {
+ "action_coordinate_space": {
+ "kind": "screenshot_pixels"
+ },
+ "capture_id": "capture_8a22ffd72f02467f9ff0f0b6de791b6e_0000000000000000",
+ "screenshot": {
+ "height": 1033,
+ "mime_type": "image/png",
+ "reference": "png-sha256:2be15022cfea6b1c45bf72902bd4db54075cec6748d1defec5ecd1d75cc9259a",
+ "sha256": "2be15022cfea6b1c45bf72902bd4db54075cec6748d1defec5ecd1d75cc9259a",
+ "width": 945
+ },
+ "source": {
+ "kind": "window",
+ "pid": 2539,
+ "window_id": 52428804
+ }
+ },
+ "parser": {
+ "backend": "onnx_runtime_cpu",
+ "extension_id": "cua-perception",
+ "extension_version": "0.2.1",
+ "model_id": "omniparser-v2-ppocrv5-en",
+ "model_manifest_sha256": "59f5197c98d0bbe20668993771a19fa495624027e69ef87a75c6606986a60b13",
+ "model_source_revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",
+ "model_version": "2026-09-17",
+ "onnx_runtime_library_sha256": "5bd5bedf736fc501692435d0ec4f6e8b2bdf48cd30af8e6d00d61b3ddc9a7ab8",
+ "onnx_runtime_version": "1.26.0",
+ "runtime": "onnx_runtime_cpu"
+ },
+ "regions": [
+ {
+ "bounds": {
+ "height": 19,
+ "width": 18,
+ "x": 252,
+ "y": 10
+ },
+ "confidence": 0.8168784976005554,
+ "id": "text-9",
+ "interactive": false,
+ "kind": "text",
+ "text": "×"
+ },
+ {
+ "bounds": {
+ "height": 14,
+ "width": 14,
+ "x": 288,
+ "y": 13
+ },
+ "confidence": 0.8311772346496582,
+ "id": "text-11",
+ "interactive": false,
+ "kind": "text",
+ "text": "+"
+ },
+ {
+ "bounds": {
+ "height": 36,
+ "width": 34,
+ "x": 10,
+ "y": 45
+ },
+ "confidence": 0.8110984563827515,
+ "id": "icon-15",
+ "interactive": false,
+ "kind": "icon",
+ "label": "icon-class-0"
+ },
+ {
+ "bounds": {
+ "height": 36,
+ "width": 32,
+ "x": 83,
+ "y": 46
+ },
+ "confidence": 0.8079566955566406,
+ "id": "icon-17",
+ "interactive": false,
+ "kind": "icon",
+ "label": "icon-class-0"
+ },
+ {
+ "bounds": {
+ "height": 34,
+ "width": 31,
+ "x": 47,
+ "y": 46
+ },
+ "confidence": 0.8043645024299622,
+ "id": "icon-18",
+ "interactive": false,
+ "kind": "icon",
+ "label": "icon-class-0"
+ },
+ {
+ "bounds": {
+ "height": 18,
+ "width": 20,
+ "x": 17,
+ "y": 54
+ },
+ "confidence": 0.8558894395828247,
+ "id": "text-26",
+ "interactive": false,
+ "kind": "text",
+ "text": "←"
+ },
+ {
+ "bounds": {
+ "height": 47,
+ "width": 118,
+ "x": 175,
+ "y": 389
+ },
+ "confidence": 0.8023205995559692,
+ "id": "text-28",
+ "interactive": false,
+ "kind": "text",
+ "text": "Cua"
+ },
+ {
+ "bounds": {
+ "height": 52,
+ "width": 302,
+ "x": 471,
+ "y": 389
+ },
+ "confidence": 0.8917925357818604,
+ "id": "text-29",
+ "interactive": false,
+ "kind": "text",
+ "text": "TypeSafe Jev"
+ },
+ {
+ "bounds": {
+ "height": 46,
+ "width": 207,
+ "x": 270,
+ "y": 390
+ },
+ "confidence": 0.865290641784668,
+ "id": "text-30",
+ "interactive": false,
+ "kind": "text",
+ "text": "Driver +"
+ },
+ {
+ "bounds": {
+ "height": 63,
+ "width": 132,
+ "x": 637,
+ "y": 561
+ },
+ "confidence": 0.9488332271575928,
+ "id": "icon-33",
+ "interactive": false,
+ "kind": "icon",
+ "label": "icon-class-0"
+ },
+ {
+ "bounds": {
+ "height": 65,
+ "width": 449,
+ "x": 172,
+ "y": 562
+ },
+ "confidence": 0.9535441398620604,
+ "id": "icon-34",
+ "interactive": false,
+ "kind": "icon",
+ "label": "icon-class-0"
+ },
+ {
+ "bounds": {
+ "height": 35,
+ "width": 149,
+ "x": 188,
+ "y": 575
+ },
+ "confidence": 0.8249707818031311,
+ "id": "text-35",
+ "interactive": false,
+ "kind": "text",
+ "text": "jev-guide-live"
+ },
+ {
+ "bounds": {
+ "height": 32,
+ "width": 85,
+ "x": 662,
+ "y": 575
+ },
+ "confidence": 0.8971455097198486,
+ "id": "text-36",
+ "interactive": false,
+ "kind": "text",
+ "text": "Submit"
+ }
+ ],
+ "schema": "cua.visual_regions_v1",
+ "timing": {
+ "duration_ms": 3893
+ }
+ },
+ "pre_fix_step1": {
+ "state": {
+ "goal": "Enter the required verification token into the verification field, then submit the form.",
+ "observation": {
+ "page": {
+ "title": "about:blank",
+ "url": "http://127.0.0.1:41605/"
+ },
+ "form": {
+ "verification_field": "empty",
+ "submit_button": "not_in_page_structure"
+ },
+ "outline": "- main\n - heading \"Cua Driver + TypeSafe Jev fixture\"\n - paragraph\n - statictext \"Enter the verification value and submit it.\"\n - form\n - generic [editable=\"plaintext\"]\n - textbox \"verification value\" [editable=\"plaintext\",focusable=true,required=true]\n - statictext \"Submit\"\n - status\n - statictext \"status=waiting\"",
+ "visual": null
+ },
+ "history": []
+ },
+ "criteria": {
+ "type-verification-value": "Type the required verification token into the verification field, replacing its current contents.",
+ "reobserve": "Take no action and obtain a fresh Driver observation, because the current observation is stale, incomplete, or contradicts the reported form state.",
+ "abstain": "Stop without acting if none of the proposed actions is safe for the observed state."
+ }
+ },
+ "recorded_live_runs": {
+ "linux_python_pre_4255_a": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.1,
+ "reobserve": 0.08,
+ "type-verification-value": 0.82
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.17,
+ "reobserve": 0.3,
+ "submit-form": 0.53
+ },
+ "action_error": "background_unavailable"
+ },
+ {
+ "step": 3,
+ "selected_id": "submit-form-foreground",
+ "probabilities": {
+ "abstain": 0.06,
+ "reobserve": 0.21,
+ "submit-form-foreground": 0.73
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "linux_typescript_pre_4255_a": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.09,
+ "reobserve": 0.1,
+ "type-verification-value": 0.81
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.2,
+ "reobserve": 0.4,
+ "submit-form": 0.4
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.17,
+ "reobserve": 0.25,
+ "submit-form": 0.58
+ },
+ "action_error": "background_unavailable"
+ },
+ {
+ "step": 4,
+ "selected_id": "submit-form-foreground",
+ "probabilities": {
+ "abstain": 0.13,
+ "reobserve": 0.17,
+ "submit-form-foreground": 0.7
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "linux_python_pre_4255_b": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.09,
+ "reobserve": 0.07,
+ "type-verification-value": 0.84
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.15,
+ "reobserve": 0.22,
+ "submit-form": 0.63
+ },
+ "action_error": "background_unavailable"
+ },
+ {
+ "step": 3,
+ "selected_id": "submit-form-foreground",
+ "probabilities": {
+ "abstain": 0.09,
+ "reobserve": 0.21,
+ "submit-form-foreground": 0.7
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "linux_typescript_pre_4255_b": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.1,
+ "reobserve": 0.1,
+ "type-verification-value": 0.8
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.18,
+ "reobserve": 0.4,
+ "submit-form": 0.42
+ },
+ "action_error": "background_unavailable"
+ },
+ {
+ "step": 3,
+ "selected_id": "submit-form-foreground",
+ "probabilities": {
+ "abstain": 0.08,
+ "reobserve": 0.25,
+ "submit-form-foreground": 0.67
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "windows_python_pre_4255_a": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.06,
+ "reobserve": 0.08,
+ "type-verification-value": 0.86
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.29,
+ "reobserve": 0.47000000000000003,
+ "submit-form": 0.24
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.27,
+ "reobserve": 0.41,
+ "submit-form": 0.32
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.19,
+ "reobserve": 0.34,
+ "submit-form": 0.47
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "windows_typescript_pre_4255_a": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.13,
+ "reobserve": 0.09,
+ "type-verification-value": 0.78
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.26,
+ "reobserve": 0.51,
+ "submit-form": 0.23
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.27,
+ "reobserve": 0.3,
+ "submit-form": 0.43
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "windows_python_pre_4255_b": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.09,
+ "reobserve": 0.08,
+ "type-verification-value": 0.83
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.25,
+ "reobserve": 0.47,
+ "submit-form": 0.28
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.21,
+ "reobserve": 0.36,
+ "submit-form": 0.43
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "windows_typescript_pre_4255_b": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "type-verification-value",
+ "probabilities": {
+ "abstain": 0.09,
+ "reobserve": 0.09,
+ "type-verification-value": 0.82
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.18,
+ "reobserve": 0.47,
+ "submit-form": 0.35
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.28,
+ "reobserve": 0.41,
+ "submit-form": 0.31
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "submit-form",
+ "probabilities": {
+ "abstain": 0.2,
+ "reobserve": 0.21,
+ "submit-form": 0.59
+ }
+ }
+ ],
+ "outcome": "verified"
+ },
+ "linux_python_post_4255_regression_1": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.05,
+ "reobserve": 0.74,
+ "type-verification-value": 0.21
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.78,
+ "type-verification-value": 0.2
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.82,
+ "type-verification-value": 0.16
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.83,
+ "type-verification-value": 0.15
+ }
+ }
+ ],
+ "outcome": "budget_exhausted"
+ },
+ "linux_python_post_4255_regression_2": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.04,
+ "reobserve": 0.7,
+ "type-verification-value": 0.26
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.79,
+ "type-verification-value": 0.19
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.81,
+ "type-verification-value": 0.17
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.79,
+ "type-verification-value": 0.19
+ }
+ }
+ ],
+ "outcome": "budget_exhausted"
+ },
+ "linux_python_post_4255_regression_3": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.04,
+ "reobserve": 0.7,
+ "type-verification-value": 0.26
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.03,
+ "reobserve": 0.75,
+ "type-verification-value": 0.22
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.85,
+ "type-verification-value": 0.13
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.79,
+ "type-verification-value": 0.19
+ }
+ }
+ ],
+ "outcome": "budget_exhausted"
+ },
+ "linux_python_post_4255_regression_4": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.03,
+ "reobserve": 0.73,
+ "type-verification-value": 0.24
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.78,
+ "type-verification-value": 0.2
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.79,
+ "type-verification-value": 0.19
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.8,
+ "type-verification-value": 0.18
+ }
+ }
+ ],
+ "outcome": "budget_exhausted"
+ },
+ "linux_python_post_4255_regression_5": {
+ "steps": [
+ {
+ "step": 1,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.04,
+ "reobserve": 0.71,
+ "type-verification-value": 0.25
+ }
+ },
+ {
+ "step": 2,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.04,
+ "reobserve": 0.75,
+ "type-verification-value": 0.21
+ }
+ },
+ {
+ "step": 3,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.78,
+ "type-verification-value": 0.2
+ }
+ },
+ {
+ "step": 4,
+ "selected_id": "reobserve",
+ "probabilities": {
+ "abstain": 0.02,
+ "reobserve": 0.8,
+ "type-verification-value": 0.18
+ }
+ }
+ ],
+ "outcome": "budget_exhausted"
+ }
+ }
+}
diff --git a/libs/cua-driver/examples/jev-use/python/core.py b/libs/cua-driver/examples/jev-use/python/core.py
index a911bbe12e..a4c1b4cd9e 100644
--- a/libs/cua-driver/examples/jev-use/python/core.py
+++ b/libs/cua-driver/examples/jev-use/python/core.py
@@ -231,11 +231,38 @@ def _form_refs(snapshot: Mapping[str, Any]) -> tuple[Any, Any]:
return field, button
-def form_state(snapshot: Mapping[str, Any], token: str) -> dict[str, str]:
+def visual_submit_region(visual: VisualObservation | None) -> VisualRegion | None:
+ """Return the unique validated visual Submit region, or ``None``."""
+ if visual is None:
+ return None
+ matches = [
+ region
+ for region in visual.regions
+ if region.confidence >= 0.8
+ and _ascii_lower(region.text or region.label or "") == "submit"
+ ]
+ return matches[0] if len(matches) == 1 else None
+
+
+def form_state(
+ snapshot: Mapping[str, Any],
+ token: str,
+ visual: VisualObservation | None = None,
+ *,
+ visual_path: bool = False,
+) -> dict[str, str]:
"""Summarize the form for the decision model without revealing the token.
The raw field value never leaves the runner; the model receives only whether
the field is empty, holds the required token, or holds something else.
+
+ ``submit_button`` is ``available`` for a clickable page-structure ref. When
+ the page structure has none and the capture-bound visual path is enabled
+ (``visual_path``), it is ``visual_only`` if this observation holds a unique
+ validated visual Submit region, ``visual_check_pending`` if no visual regions
+ were parsed for this step yet (the runner parses them once no page-structure
+ action remains), and ``not_found_visually`` otherwise. Without a visual path
+ it is ``not_in_page_structure``.
"""
field, button = _form_refs(snapshot)
if field is None:
@@ -246,10 +273,17 @@ def form_state(snapshot: Mapping[str, Any], token: str) -> dict[str, str]:
field_state = "contains_required_token"
else:
field_state = "contains_other_value"
- return {
- "verification_field": field_state,
- "submit_button": "available" if button is not None else "not_in_page_structure",
- }
+ if button is not None:
+ submit_state = "available"
+ elif not visual_path:
+ submit_state = "not_in_page_structure"
+ elif visual is None:
+ submit_state = "visual_check_pending"
+ elif visual_submit_region(visual) is not None:
+ submit_state = "visual_only"
+ else:
+ submit_state = "not_found_visually"
+ return {"verification_field": field_state, "submit_button": submit_state}
def redact_token(value: Any, token: str) -> Any:
@@ -296,7 +330,10 @@ def _reserved_candidates() -> list[Candidate]:
Candidate(
"reobserve",
"Take no action and obtain a fresh Driver observation, because the current "
- "observation is stale, incomplete, or contradicts the reported form state.",
+ "observation is stale or contradicts the reported form state. A Submit control "
+ "that is visual-only, or whose visual check is still pending, is not a reason to "
+ "reobserve: the runner parses visual regions for Submit once no page-structure "
+ "action remains.",
None,
{},
),
@@ -357,14 +394,9 @@ def build_candidates(
and visual
and capture_bound_click
):
- matches = [
- region
- for region in visual.regions
- if region.confidence >= 0.8
- and _ascii_lower(region.text or region.label or "") == "submit"
- ]
- if len(matches) == 1:
- x, y = visual.screenshot_center(matches[0])
+ region = visual_submit_region(visual)
+ if region is not None:
+ x, y = visual.screenshot_center(region)
foreground = visual_delivery == "foreground"
candidates.append(
Candidate(
diff --git a/libs/cua-driver/examples/jev-use/python/jev_adapter.py b/libs/cua-driver/examples/jev-use/python/jev_adapter.py
index 2b67916874..90db703b65 100644
--- a/libs/cua-driver/examples/jev-use/python/jev_adapter.py
+++ b/libs/cua-driver/examples/jev-use/python/jev_adapter.py
@@ -103,18 +103,20 @@ def decision_state(
visual: VisualObservation | None,
history: list[dict[str, Any]],
token: str,
+ visual_path: bool = False,
) -> dict[str, Any]:
"""Build the compact, deterministic, token-redacted state sent to Jev.
``form`` states the field and Submit status the runner verified from the page
- structure, so the model does not have to infer it from the outline. The token
+ structure and, when ``visual_path`` is enabled, from the validated visual
+ regions, so the model does not have to infer it from the outline. The token
itself is replaced everywhere, including the outline and visual text.
"""
return {
"goal": GOAL,
"observation": {
"page": redact_token(snapshot.get("page"), token),
- "form": form_state(snapshot, token),
+ "form": form_state(snapshot, token, visual, visual_path=visual_path),
"outline": redact_token(snapshot.get("outline"), token),
"visual": redact_token(visual_decision_state(visual), token),
},
@@ -129,12 +131,13 @@ def choose_with_typesafe(
visual: VisualObservation | None,
history: list[dict[str, Any]],
token: str,
+ visual_path: bool = False,
) -> tuple[str, float, dict[str, float]]:
from typesafe_sdk import Choice
criteria = _candidate_criteria(candidates)
response = client.system_one(
- state=decision_state(snapshot, visual, history, token),
+ state=decision_state(snapshot, visual, history, token, visual_path),
questions={
"driver_action": Choice(
instructions="Which complete executable action should Cua Driver run next?",
@@ -154,11 +157,14 @@ def choose_live(
visual: VisualObservation | None,
history: list[dict[str, Any]],
token: str,
+ visual_path: bool = False,
) -> tuple[str, float, dict[str, float]]:
from typesafe_sdk import TypeSafeClient
with TypeSafeClient() as client:
- return choose_with_typesafe(client, candidates, snapshot, visual, history, token)
+ return choose_with_typesafe(
+ client, candidates, snapshot, visual, history, token, visual_path
+ )
def choose_mock_adapter(
@@ -167,5 +173,6 @@ def choose_mock_adapter(
_visual: VisualObservation | None,
_history: list[dict[str, Any]],
_token: str,
+ _visual_path: bool = False,
) -> tuple[str | None, float, dict[str, float]]:
return choose_mock(candidates)
diff --git a/libs/cua-driver/examples/jev-use/python/run.py b/libs/cua-driver/examples/jev-use/python/run.py
index b78b850cdc..1ec01b93b1 100644
--- a/libs/cua-driver/examples/jev-use/python/run.py
+++ b/libs/cua-driver/examples/jev-use/python/run.py
@@ -308,6 +308,9 @@ async def run(args: argparse.Namespace) -> str:
advertised_tools = (await session.list_tools()).tools
available_tools = {tool.name for tool in advertised_tools}
capture_bound_click = supports_capture_bound_click(advertised_tools)
+ # Whether a Submit missing from the page structure can still be found
+ # through a capture-bound visual region; reported in the form state.
+ visual_path = capture_bound_click and args.visual_observation != "off"
driver = Driver(session, label)
prepared = await driver.call(
"browser_prepare",
@@ -361,11 +364,11 @@ async def run(args: argparse.Namespace) -> str:
if args.provider == "mock":
choice, confidence, probabilities = choose_mock_adapter(
- candidates, snapshot, visual, history, token
+ candidates, snapshot, visual, history, token, visual_path
)
else:
choice, confidence, probabilities = await asyncio.to_thread(
- choose_live, candidates, snapshot, visual, history, token
+ choose_live, candidates, snapshot, visual, history, token, visual_path
)
if choice is None:
return "abstained"
diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_decision_state.py b/libs/cua-driver/examples/jev-use/python/tests/test_decision_state.py
index fbdac75e53..530ceae0af 100644
--- a/libs/cua-driver/examples/jev-use/python/tests/test_decision_state.py
+++ b/libs/cua-driver/examples/jev-use/python/tests/test_decision_state.py
@@ -126,7 +126,7 @@ class SubmitStepObservationTest(unittest.TestCase):
criteria = {candidate.id: candidate.description for candidate in candidates}
self.assertEqual(list(criteria), ["submit-form", "reobserve", "abstain"])
self.assertIn("already contains the required token", criteria["submit-form"])
- self.assertIn("stale, incomplete", criteria["reobserve"])
+ self.assertIn("stale or contradicts", criteria["reobserve"])
self.assertNotIn(TOKEN, json.dumps(criteria))
def test_visual_text_is_redacted_too(self) -> None:
diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_visual_decision_state.py b/libs/cua-driver/examples/jev-use/python/tests/test_visual_decision_state.py
new file mode 100644
index 0000000000..e905a6158f
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/tests/test_visual_decision_state.py
@@ -0,0 +1,224 @@
+from __future__ import annotations
+
+import json
+import sys
+import unittest
+from dataclasses import replace
+from pathlib import Path
+from types import SimpleNamespace
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core import (
+ SUBMIT_IDS,
+ build_candidates,
+ choose_mock,
+ form_state,
+ has_executable_candidate,
+ history_entry,
+ parse_visual_regions,
+ validate_choice,
+ visual_submit_region,
+)
+from jev_adapter import choose_with_typesafe, decision_state
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures"
+VISUAL = json.loads((FIXTURES / "jev-visual-replay-v1.json").read_text(encoding="utf-8"))
+PAGE = json.loads((FIXTURES / "jev-page-structure-replay-v1.json").read_text(encoding="utf-8"))
+TOKEN = VISUAL["token"]
+BEFORE = VISUAL["snapshots"]["before_typing"]
+AFTER = VISUAL["snapshots"]["after_typing"]
+PAYLOAD = VISUAL["visual_regions"]
+
+
+def observation():
+ source = PAYLOAD["capture"]["source"]
+ return parse_visual_regions(
+ PAYLOAD,
+ expected_capture_id=PAYLOAD["capture"]["capture_id"],
+ expected_pid=source["pid"],
+ expected_window_id=source["window_id"],
+ )
+
+
+class ReplayClient:
+ """Return recorded live choices in order and keep every request."""
+
+ def __init__(self, recorded: list[dict]) -> None:
+ self.recorded = list(recorded)
+ self.requests: list[dict] = []
+
+ def system_one(self, **request):
+ self.requests.append(request)
+ step = self.recorded.pop(0)
+ answer = SimpleNamespace(
+ choice=step["selected_id"],
+ confidence=max(step["probabilities"].values()),
+ probabilities=step["probabilities"],
+ )
+ return SimpleNamespace(choices={"driver_action": answer})
+
+
+class VisualFormStateTest(unittest.TestCase):
+ def test_fixture_exposes_submit_only_as_text_and_as_one_visual_region(self) -> None:
+ for snapshot in (BEFORE, AFTER):
+ self.assertFalse(any(ref["role"] == "button" for ref in snapshot["refs"]))
+ self.assertIn('statictext "Submit"', snapshot["outline"])
+ region = visual_submit_region(observation())
+ self.assertIsNotNone(region)
+ self.assertEqual(region.text, "Submit")
+
+ def test_submit_state_names_the_visual_path_instead_of_a_missing_button(self) -> None:
+ visual = observation()
+ self.assertEqual(form_state(BEFORE, TOKEN)["submit_button"], "not_in_page_structure")
+ self.assertEqual(
+ form_state(BEFORE, TOKEN, visual_path=True),
+ {"verification_field": "empty", "submit_button": "visual_check_pending"},
+ )
+ self.assertEqual(
+ form_state(AFTER, TOKEN, visual, visual_path=True),
+ {"verification_field": "contains_required_token", "submit_button": "visual_only"},
+ )
+ without_submit = replace(
+ visual, regions=tuple(r for r in visual.regions if r.text != "Submit")
+ )
+ self.assertEqual(
+ form_state(AFTER, TOKEN, without_submit, visual_path=True)["submit_button"],
+ "not_found_visually",
+ )
+ submit = visual_submit_region(visual)
+ duplicated = replace(visual, regions=visual.regions + (replace(submit, id="dup"),))
+ self.assertEqual(
+ form_state(AFTER, TOKEN, duplicated, visual_path=True)["submit_button"],
+ "not_found_visually",
+ )
+ # A page-structure Submit ref always wins, with or without a visual path.
+ page_after = PAGE["snapshots"]["after_typing"]
+ self.assertEqual(
+ form_state(page_after, PAGE["token"], visual, visual_path=True)["submit_button"],
+ "available",
+ )
+
+ def test_pre_fix_step_one_state_contradicted_the_outline(self) -> None:
+ # Pins the regression: the outline shows Submit text, the form said the
+ # button was missing, and reobserve invited "incomplete" observations.
+ old = VISUAL["pre_fix_step1"]
+ self.assertEqual(
+ old["state"]["observation"]["form"]["submit_button"], "not_in_page_structure"
+ )
+ self.assertIn('statictext "Submit"', old["state"]["observation"]["outline"])
+ self.assertIn("incomplete", old["criteria"]["reobserve"])
+
+ new_state = decision_state(BEFORE, None, [], TOKEN, visual_path=True)
+ self.assertEqual(new_state["observation"]["form"]["submit_button"], "visual_check_pending")
+ expected = json.loads(json.dumps(old["state"]))
+ expected["observation"]["form"]["submit_button"] = "visual_check_pending"
+ self.assertEqual(new_state, expected)
+
+ criteria = {c.id: c.description for c in build_candidates(BEFORE, TOKEN)}
+ self.assertEqual(list(criteria), list(old["criteria"]))
+ self.assertNotIn("incomplete", criteria["reobserve"])
+ self.assertIn("visual-only", criteria["reobserve"])
+ self.assertIn("still pending", criteria["reobserve"])
+
+
+class DeterministicPathsTest(unittest.TestCase):
+ def test_page_structure_fixture_types_then_submits_with_browser_click(self) -> None:
+ token = PAGE["token"]
+ first = build_candidates(PAGE["snapshots"]["before_typing"], token)
+ self.assertEqual(choose_mock(first)[0], "type-verification-value")
+ second = build_candidates(PAGE["snapshots"]["after_typing"], token)
+ choice = validate_choice(choose_mock(second)[0], second)
+ self.assertEqual((choice.id, choice.tool), ("submit-form", "browser_click"))
+
+ def test_visual_fixture_types_then_submits_with_a_capture_bound_click(self) -> None:
+ first = build_candidates(BEFORE, TOKEN, capture_bound_click=True)
+ choice = validate_choice(choose_mock(first)[0], first)
+ self.assertEqual((choice.id, choice.tool), ("type-verification-value", "browser_type"))
+
+ # After typing the page structure offers no action, so the runner parses.
+ self.assertFalse(
+ has_executable_candidate(build_candidates(AFTER, TOKEN, capture_bound_click=True))
+ )
+ visual = observation()
+ second = build_candidates(AFTER, TOKEN, visual, capture_bound_click=True)
+ choice = validate_choice(
+ choose_mock(second)[0], second, current_capture_id=visual.capture_id
+ )
+ submit = visual_submit_region(visual)
+ self.assertEqual((choice.id, choice.tool), ("submit-form", "click"))
+ self.assertEqual(choice.arguments["capture_id"], visual.capture_id)
+ self.assertEqual(choice.arguments["delivery_mode"], "background")
+ self.assertEqual(
+ (choice.arguments["x"], choice.arguments["y"]), visual.screenshot_center(submit)
+ )
+
+ third = build_candidates(
+ AFTER, TOKEN, visual, capture_bound_click=True, visual_delivery="foreground"
+ )
+ choice = validate_choice(choose_mock(third)[0], third, current_capture_id=visual.capture_id)
+ self.assertEqual(
+ (choice.id, choice.arguments["delivery_mode"]), ("submit-form-foreground", "foreground")
+ )
+
+
+class VisualReplayTest(unittest.TestCase):
+ def test_recorded_visual_run_choices_replay_through_the_new_state(self) -> None:
+ visual = observation()
+ for name, run in VISUAL["recorded_live_runs"].items():
+ with self.subTest(run=name):
+ client = ReplayClient(run["steps"])
+ history: list[dict] = []
+ typed = False
+ delivery = "background"
+ outcome = "budget_exhausted"
+ for recorded in run["steps"]:
+ step = recorded["step"]
+ snapshot = AFTER if typed else BEFORE
+ current = visual if typed else None
+ candidates = build_candidates(
+ snapshot,
+ TOKEN,
+ current,
+ capture_bound_click=True,
+ visual_delivery=delivery,
+ )
+ self.assertEqual(set(recorded["probabilities"]), {c.id for c in candidates})
+ choice, _, _ = choose_with_typesafe(
+ client, candidates, snapshot, current, history, TOKEN, True
+ )
+ candidate = validate_choice(
+ choice,
+ candidates,
+ current_capture_id=current.capture_id if current else None,
+ )
+ request = client.requests[-1]
+ form = request["state"]["observation"]["form"]
+ self.assertNotIn(TOKEN, json.dumps(request["state"], sort_keys=True))
+ self.assertEqual(
+ form,
+ {
+ "verification_field": "contains_required_token" if typed else "empty",
+ "submit_button": "visual_only" if typed else "visual_check_pending",
+ },
+ )
+ criteria = request["questions"]["driver_action"].criteria
+ self.assertNotIn("incomplete", criteria["reobserve"])
+ for item in request["state"]["history"]:
+ self.assertEqual(set(item), {"step", "selected_id", "outcome"})
+ refusal = recorded.get("action_error")
+ history.append(history_entry(step, candidate.id, refusal=refusal))
+ if candidate.id == "type-verification-value":
+ typed = True
+ elif candidate.id in SUBMIT_IDS:
+ self.assertEqual(candidate.tool, "click")
+ if refusal:
+ delivery = "foreground"
+ else:
+ outcome = "verified"
+ break
+ self.assertEqual(outcome, run["outcome"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/examples/jev-use/typescript/core.ts b/libs/cua-driver/examples/jev-use/typescript/core.ts
index cf05df3226..55d860917e 100644
--- a/libs/cua-driver/examples/jev-use/typescript/core.ts
+++ b/libs/cua-driver/examples/jev-use/typescript/core.ts
@@ -221,16 +221,46 @@ function formRefs(snapshot: BrowserSnapshot) {
return { field, button };
}
+export type SubmitButtonState =
+ | 'available'
+ | 'visual_only'
+ | 'visual_check_pending'
+ | 'not_found_visually'
+ | 'not_in_page_structure';
+
export type FormState = Readonly<{
verification_field: 'not_found' | 'empty' | 'contains_required_token' | 'contains_other_value';
- submit_button: 'available' | 'not_in_page_structure';
+ submit_button: SubmitButtonState;
}>;
+/** Return the unique validated visual Submit region, or undefined. */
+export function visualSubmitRegion(visual?: VisualObservation) {
+ if (!visual) return undefined;
+ const matches = visual.regions.filter(
+ (region) =>
+ region.confidence >= 0.8 && asciiLower(region.text ?? region.label ?? '') === 'submit'
+ );
+ return matches.length === 1 ? matches[0] : undefined;
+}
+
/**
* Summarize the form for the decision model without revealing the token. The
* raw field value never leaves the runner.
+ *
+ * submit_button is 'available' for a clickable page-structure ref. When the
+ * page structure has none and the capture-bound visual path is enabled
+ * (visualPath), it is 'visual_only' if this observation holds a unique
+ * validated visual Submit region, 'visual_check_pending' if no visual regions
+ * were parsed for this step yet (the runner parses them once no page-structure
+ * action remains), and 'not_found_visually' otherwise. Without a visual path it
+ * is 'not_in_page_structure'.
*/
-export function formState(snapshot: BrowserSnapshot, token: string): FormState {
+export function formState(
+ snapshot: BrowserSnapshot,
+ token: string,
+ visual?: VisualObservation,
+ visualPath = false
+): FormState {
const { field, button } = formRefs(snapshot);
const verificationField = !field
? 'not_found'
@@ -239,10 +269,16 @@ export function formState(snapshot: BrowserSnapshot, token: string): FormState {
: field.value === token
? 'contains_required_token'
: 'contains_other_value';
- return {
- verification_field: verificationField,
- submit_button: button ? 'available' : 'not_in_page_structure',
- };
+ const submitButton: SubmitButtonState = button
+ ? 'available'
+ : !visualPath
+ ? 'not_in_page_structure'
+ : !visual
+ ? 'visual_check_pending'
+ : visualSubmitRegion(visual)
+ ? 'visual_only'
+ : 'not_found_visually';
+ return { verification_field: verificationField, submit_button: submitButton };
}
/** Replace every occurrence of the token in strings nested in value. */
@@ -287,7 +323,10 @@ function reservedCandidates(): Candidate[] {
id: 'reobserve',
description:
'Take no action and obtain a fresh Driver observation, because the current ' +
- 'observation is stale, incomplete, or contradicts the reported form state.',
+ 'observation is stale or contradicts the reported form state. A Submit control ' +
+ 'that is visual-only, or whose visual check is still pending, is not a reason to ' +
+ 'reobserve: the runner parses visual regions for Submit once no page-structure ' +
+ 'action remains.',
tool: null,
arguments: {},
}),
@@ -345,13 +384,8 @@ export function buildCandidates(
visual &&
captureBoundClick
) {
- const matches = visual.regions.filter(
- (region) =>
- region.confidence >= 0.8 &&
- asciiLower(region.text ?? region.label ?? '') === 'submit'
- );
- if (matches.length === 1) {
- const region = matches[0];
+ const region = visualSubmitRegion(visual);
+ if (region) {
const x = region.x + region.width / 2;
const y = region.y + region.height / 2;
const foreground = visualDelivery === 'foreground';
diff --git a/libs/cua-driver/examples/jev-use/typescript/decision_state.test.ts b/libs/cua-driver/examples/jev-use/typescript/decision_state.test.ts
index 2decc9d2a6..4e805b7ca3 100644
--- a/libs/cua-driver/examples/jev-use/typescript/decision_state.test.ts
+++ b/libs/cua-driver/examples/jev-use/typescript/decision_state.test.ts
@@ -114,7 +114,7 @@ test('after typing the observation states the filled form', () => {
);
assert.deepEqual(Object.keys(criteria), ['submit-form', 'reobserve', 'abstain']);
assert.ok(criteria['submit-form'].includes('already contains the required token'));
- assert.ok(criteria.reobserve.includes('stale, incomplete'));
+ assert.ok(criteria.reobserve.includes('stale or contradicts'));
assert.equal(JSON.stringify(criteria).includes(TOKEN), false);
});
diff --git a/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts b/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts
index 1286ee20c2..5cec3b910c 100644
--- a/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts
+++ b/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts
@@ -105,19 +105,21 @@ export const GOAL =
/**
* Build the compact, deterministic, token-redacted state sent to Jev. `form`
* states the field and Submit status the runner verified from the page
- * structure; the token is replaced everywhere, including outline and visual text.
+ * structure and, when visualPath is enabled, from the validated visual regions;
+ * the token is replaced everywhere, including outline and visual text.
*/
export function decisionState(
snapshot: BrowserSnapshot,
visual: VisualObservation | undefined,
history: readonly HistoryEntry[],
- token: string
+ token: string,
+ visualPath = false
) {
return {
goal: GOAL,
observation: {
page: JSON.stringify(redactToken(snapshot.page ?? null, token)),
- form: JSON.stringify(formState(snapshot, token)),
+ form: JSON.stringify(formState(snapshot, token, visual, visualPath)),
outline: redactToken(snapshot.outline ?? '', token) as string,
visual: JSON.stringify(redactToken(visualDecisionState(visual), token)),
},
@@ -131,11 +133,12 @@ export async function chooseWithTypeSafe(
snapshot: BrowserSnapshot,
visual: VisualObservation | undefined,
history: readonly HistoryEntry[],
- token: string
+ token: string,
+ visualPath = false
) {
const criteria = candidateCriteria(candidates);
const response = await client.systemOne({
- state: decisionState(snapshot, visual, history, token),
+ state: decisionState(snapshot, visual, history, token, visualPath),
questions: {
driver_action: choice(
'Which complete executable action should Cua Driver run next?',
@@ -156,9 +159,18 @@ export function chooseLive(
snapshot: BrowserSnapshot,
visual: VisualObservation | undefined,
history: readonly HistoryEntry[],
- token: string
+ token: string,
+ visualPath = false
) {
- return chooseWithTypeSafe(new TypeSafeClient(), candidates, snapshot, visual, history, token);
+ return chooseWithTypeSafe(
+ new TypeSafeClient(),
+ candidates,
+ snapshot,
+ visual,
+ history,
+ token,
+ visualPath
+ );
}
export function chooseMockAdapter(
@@ -166,7 +178,8 @@ export function chooseMockAdapter(
_snapshot: BrowserSnapshot,
_visual: VisualObservation | undefined,
_history: readonly HistoryEntry[],
- _token: string
+ _token: string,
+ _visualPath = false
) {
return chooseMock(candidates);
}
diff --git a/libs/cua-driver/examples/jev-use/typescript/run.ts b/libs/cua-driver/examples/jev-use/typescript/run.ts
index 239ace676d..d34b97da92 100644
--- a/libs/cua-driver/examples/jev-use/typescript/run.ts
+++ b/libs/cua-driver/examples/jev-use/typescript/run.ts
@@ -341,6 +341,9 @@ async function run(args: Arguments): Promise<Outcome> {
const advertisedTools = (await client.listTools()).tools;
const availableTools = new Set(advertisedTools.map((tool) => tool.name));
const captureBoundClick = supportsCaptureBoundClick(advertisedTools);
+ // Whether a Submit missing from the page structure can still be found through
+ // a capture-bound visual region; reported in the form state.
+ const visualPath = captureBoundClick && args.visualObservation !== 'off';
const driver = new Driver(client, `jev-typescript-${randomUUID().slice(0, 8)}`);
const prepared = await driver.call('browser_prepare', {
allow_launch: true,
@@ -400,8 +403,8 @@ async function run(args: Arguments): Promise<Outcome> {
}
const answer =
args.provider === 'mock'
- ? chooseMockAdapter(candidates, snapshot, visual, history, token)
- : await chooseLive(candidates, snapshot, visual, history, token);
+ ? chooseMockAdapter(candidates, snapshot, visual, history, token, visualPath)
+ : await chooseLive(candidates, snapshot, visual, history, token, visualPath);
if (!answer.choice) return 'abstained';
const candidate = validateChoice(answer.choice, candidates, visual?.captureId);
const decisionMs = Math.round((performance.now() - decisionStarted) * 100) / 100;
diff --git a/libs/cua-driver/examples/jev-use/typescript/visual_decision_state.test.ts b/libs/cua-driver/examples/jev-use/typescript/visual_decision_state.test.ts
new file mode 100644
index 0000000000..b9f561f080
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/typescript/visual_decision_state.test.ts
@@ -0,0 +1,215 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+
+import {
+ SUBMIT_IDS,
+ buildCandidates,
+ chooseMock,
+ formState,
+ hasExecutableCandidate,
+ historyEntry,
+ parseVisualRegions,
+ validateChoice,
+ visualSubmitRegion,
+ type BrowserSnapshot,
+ type HistoryEntry,
+ type VisualDelivery,
+ type VisualObservation,
+} from './core.js';
+import { chooseWithTypeSafe, decisionState } from './jev_adapter.js';
+
+const load = (name: string) =>
+ JSON.parse(readFileSync(new URL(`../fixtures/${name}`, import.meta.url), 'utf8'));
+const VISUAL = load('jev-visual-replay-v1.json');
+const PAGE = load('jev-page-structure-replay-v1.json');
+const TOKEN: string = VISUAL.token;
+const BEFORE: BrowserSnapshot = VISUAL.snapshots.before_typing;
+const AFTER: BrowserSnapshot = VISUAL.snapshots.after_typing;
+const PAYLOAD = VISUAL.visual_regions;
+
+type RecordedStep = {
+ step: number;
+ selected_id: string;
+ probabilities: Record<string, number>;
+ action_error?: string;
+};
+
+function observation(): VisualObservation {
+ const source = PAYLOAD.capture.source;
+ return parseVisualRegions(PAYLOAD, PAYLOAD.capture.capture_id, source.pid, source.window_id);
+}
+
+function replayClient(recorded: RecordedStep[]) {
+ const queue = [...recorded];
+ const requests: any[] = [];
+ return {
+ requests,
+ systemOne: async (request: any) => {
+ requests.push(request);
+ const step = queue.shift()!;
+ return {
+ answers: {
+ driver_action: {
+ type: 'choice' as const,
+ choice: step.selected_id,
+ confidence: Math.max(...Object.values(step.probabilities)),
+ probabilities: step.probabilities,
+ },
+ },
+ };
+ },
+ };
+}
+
+test('visual fixture exposes Submit only as text and as one visual region', () => {
+ for (const snapshot of [BEFORE, AFTER]) {
+ assert.equal(
+ (snapshot.refs ?? []).some((ref) => ref.role === 'button'),
+ false
+ );
+ assert.ok((snapshot.outline ?? '').includes('statictext "Submit"'));
+ }
+ assert.equal(visualSubmitRegion(observation())?.text, 'Submit');
+});
+
+test('submit state names the visual path instead of a missing button', () => {
+ const visual = observation();
+ assert.equal(formState(BEFORE, TOKEN).submit_button, 'not_in_page_structure');
+ assert.deepEqual(formState(BEFORE, TOKEN, undefined, true), {
+ verification_field: 'empty',
+ submit_button: 'visual_check_pending',
+ });
+ assert.deepEqual(formState(AFTER, TOKEN, visual, true), {
+ verification_field: 'contains_required_token',
+ submit_button: 'visual_only',
+ });
+ const withoutSubmit = { ...visual, regions: visual.regions.filter((r) => r.text !== 'Submit') };
+ assert.equal(formState(AFTER, TOKEN, withoutSubmit, true).submit_button, 'not_found_visually');
+ const submit = visualSubmitRegion(visual)!;
+ const duplicated = { ...visual, regions: [...visual.regions, { ...submit, id: 'dup' }] };
+ assert.equal(formState(AFTER, TOKEN, duplicated, true).submit_button, 'not_found_visually');
+ // A page-structure Submit ref always wins, with or without a visual path.
+ assert.equal(
+ formState(PAGE.snapshots.after_typing, PAGE.token, visual, true).submit_button,
+ 'available'
+ );
+});
+
+test('pre-fix step-one state contradicted the outline', () => {
+ const old = VISUAL.pre_fix_step1;
+ assert.equal(old.state.observation.form.submit_button, 'not_in_page_structure');
+ assert.ok(old.state.observation.outline.includes('statictext "Submit"'));
+ assert.ok(old.criteria.reobserve.includes('incomplete'));
+
+ const state = decisionState(BEFORE, undefined, [], TOKEN, true);
+ assert.deepEqual(JSON.parse(state.observation.form), {
+ verification_field: 'empty',
+ submit_button: 'visual_check_pending',
+ });
+ assert.equal(state.observation.outline, old.state.observation.outline);
+
+ const criteria = Object.fromEntries(
+ buildCandidates(BEFORE, TOKEN).map((candidate) => [candidate.id, candidate.description])
+ );
+ assert.deepEqual(Object.keys(criteria), Object.keys(old.criteria));
+ assert.equal(criteria.reobserve.includes('incomplete'), false);
+ assert.ok(criteria.reobserve.includes('visual-only'));
+ assert.ok(criteria.reobserve.includes('still pending'));
+});
+
+test('page-structure fixture types then submits with browser_click', () => {
+ const first = buildCandidates(PAGE.snapshots.before_typing, PAGE.token);
+ assert.equal(chooseMock(first).choice, 'type-verification-value');
+ const second = buildCandidates(PAGE.snapshots.after_typing, PAGE.token);
+ const choice = validateChoice(chooseMock(second).choice!, second);
+ assert.deepEqual([choice.id, choice.tool], ['submit-form', 'browser_click']);
+});
+
+test('visual fixture types then submits with a capture-bound click', () => {
+ const first = buildCandidates(BEFORE, TOKEN, undefined, true);
+ const typed = validateChoice(chooseMock(first).choice!, first);
+ assert.deepEqual([typed.id, typed.tool], ['type-verification-value', 'browser_type']);
+
+ // After typing the page structure offers no action, so the runner parses.
+ assert.equal(hasExecutableCandidate(buildCandidates(AFTER, TOKEN, undefined, true)), false);
+ const visual = observation();
+ const second = buildCandidates(AFTER, TOKEN, visual, true);
+ const submit = validateChoice(chooseMock(second).choice!, second, visual.captureId);
+ const region = visualSubmitRegion(visual)!;
+ assert.deepEqual([submit.id, submit.tool], ['submit-form', 'click']);
+ assert.equal(submit.arguments.capture_id, visual.captureId);
+ assert.equal(submit.arguments.delivery_mode, 'background');
+ assert.deepEqual(
+ [submit.arguments.x, submit.arguments.y],
+ [region.x + region.width / 2, region.y + region.height / 2]
+ );
+
+ const third = buildCandidates(AFTER, TOKEN, visual, true, 'foreground');
+ const foreground = validateChoice(chooseMock(third).choice!, third, visual.captureId);
+ assert.deepEqual(
+ [foreground.id, foreground.arguments.delivery_mode],
+ ['submit-form-foreground', 'foreground']
+ );
+});
+
+test('recorded visual-run choices replay through the new state', async () => {
+ const visual = observation();
+ for (const [name, run] of Object.entries<any>(VISUAL.recorded_live_runs)) {
+ const client = replayClient(run.steps);
+ const history: HistoryEntry[] = [];
+ let typed = false;
+ let delivery: VisualDelivery = 'background';
+ let outcome = 'budget_exhausted';
+ for (const recorded of run.steps as RecordedStep[]) {
+ const snapshot = typed ? AFTER : BEFORE;
+ const current = typed ? visual : undefined;
+ const candidates = buildCandidates(snapshot, TOKEN, current, true, delivery);
+ assert.deepEqual(
+ new Set(Object.keys(recorded.probabilities)),
+ new Set(candidates.map((candidate) => candidate.id)),
+ name
+ );
+ const answer = await chooseWithTypeSafe(
+ client as never,
+ candidates,
+ snapshot,
+ current,
+ history,
+ TOKEN,
+ true
+ );
+ const candidate = validateChoice(answer.choice, candidates, current?.captureId);
+ const request = client.requests.at(-1);
+ assert.equal(JSON.stringify(request.state).includes(TOKEN), false, name);
+ assert.deepEqual(
+ JSON.parse(request.state.observation.form),
+ {
+ verification_field: typed ? 'contains_required_token' : 'empty',
+ submit_button: typed ? 'visual_only' : 'visual_check_pending',
+ },
+ name
+ );
+ assert.equal(
+ request.questions.driver_action.criteria.reobserve.includes('incomplete'),
+ false
+ );
+ for (const item of JSON.parse(request.state.history)) {
+ assert.deepEqual(Object.keys(item).sort(), ['outcome', 'selected_id', 'step'], name);
+ }
+ history.push(historyEntry(recorded.step, candidate.id, recorded.action_error));
+ if (candidate.id === 'type-verification-value') {
+ typed = true;
+ } else if (SUBMIT_IDS.has(candidate.id)) {
+ assert.equal(candidate.tool, 'click', name);
+ if (recorded.action_error) {
+ delivery = 'foreground';
+ } else {
+ outcome = 'verified';
+ break;
+ }
+ }
+ }
+ assert.equal(outcome, run.outcome, name);
+ }
+});