Skip to content

Fastest and cheapest web agent

Python

Reduce browser round trips and record a 7-second Flights demo

Gregor Žunič452c1ad2dd62
diff --git a/.env.example b/.env.example
index abf34cb..ea68998 100644
--- a/.env.example
+++ b/.env.example
@@ -3,5 +3,5 @@ TYPESAFE_MODEL=jev-latest
# Required for TYPE_TEXT. OpenAI-compatible helper; credentials stay server-side.
TEXT_MODEL_API_KEY=
TEXT_MODEL_BASE_URL=https://openrouter.ai/api/v1
-TEXT_MODEL=google/gemini-2.5-flash-lite
+TEXT_MODEL=inception/mercury-2.5
TEXT_MODEL_REASONING=none
diff --git a/README.md b/README.md
index e82c9ba..0a4639d 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
Give it one goal. [TypeSafe's Jev](https://docs.typesafe.ai/introduction) picks an operation and an element. A small LLM writes text only when the operation is `TYPE_TEXT`.
-**Zürich → London on Google Flights in 11.4 seconds.** One natural-language goal, actual text generation, and loading waits included.
+**Zürich → London on Google Flights in 7.1 seconds.** One natural-language goal, actual text generation, and loading waits included.
<a href="docs/demo.mp4"><img src="docs/demo.gif" alt="A real Google Flights search at 1× speed, with generated city names and dynamic operation/target decisions" width="100%" /></a>
@@ -61,7 +61,7 @@ Open **http://127.0.0.1:8766** and click **Start demo → Run automatically**. T
Chrome connects through [Browser Harness](https://github.com/browser-use/browser-harness), installed by `uv sync`. Run `uv run browser-harness --doctor` if it needs connecting. Allow remote debugging in Chrome when prompted.
-`TEXT_MODEL_API_KEY` is an OpenRouter key in the example configuration. The current demo uses `google/gemini-2.5-flash-lite` with reasoning disabled. GLM and DeepSeek can also use the OpenAI-compatible text helper; configure the appropriate model, endpoint, and reasoning setting.
+`TEXT_MODEL_API_KEY` is an OpenRouter key in the example configuration. The current demo uses `inception/mercury-2.5` with reasoning disabled. Gemini, GLM, and DeepSeek can also use the OpenAI-compatible text helper; configure the appropriate model, endpoint, and reasoning setting.
## Use the library
@@ -91,7 +91,9 @@ uv run --env-file .env python examples/run.py \
- **One request per decision cycle.** Operation and target heads share the same observed state.
- **No screenshots in the default agent loop.** Jev consumes structured state. The inspector opts into screenshots; the video uses a separate continuous screencast.
-- **Read candidate elements.** Cache DOM references and batch fresh geometry reads instead of copying the entire page's scripts and markup each step.
+- **One browser call per snapshot.** Read visible controls, their names, values, and text atomically. Keep references to the actual DOM nodes.
+- **Validate the selected target.** Clicks check the document, form values, target, and nearby context. Animation alone does not force another prediction. Resolve current geometry and reject covered controls before input.
+- **Wait for useful state.** After typing into a combobox, wait for visible suggestions, capped at 200 ms. Other interactions get at most two animation frames or 50 ms. These reads happen after execution is logged.
- **Keep hidden tabs rendering.** Focus emulation prevents background animation throttling without switching Chrome's visible tab.
- **Send visible text.** Offscreen article bodies and footers do not fill the model context.
- **Reuse an interrupted text request.** A generated value survives a stale-page retry only if the entire text-helper input is unchanged.
@@ -103,20 +105,21 @@ Every executed target is resolved from an observed node. The executor rechecks p
| File | Job |
| --- | --- |
| [agent.py](jev_ultrafast/agent.py) | The complete loop and text-helper handoff |
-| [browser.py](jev_ultrafast/browser.py) | Accessibility tree, visible text, fresh geometry, execution |
+| [snapshot.js](jev_ultrafast/snapshot.js) | Atomic DOM snapshot, indexed controls, freshness guards |
+| [browser.py](jev_ultrafast/browser.py) | Browser connection, current geometry, execution |
| [model.py](jev_ultrafast/model.py) | Dynamic operation/target heads and text generation |
| [questions.py](jev_ultrafast/questions.py) | Model instructions |
| [demo.py](jev_ultrafast/demo.py) | Local inspector |
## Evidence and limits
-The current video is an **11,387 ms** Google Flights run. Timing starts after initial page observation and includes model calls, real generated text, browser work, stale decisions, and loading waits. An independent check verifies the one-way setting, Zürich, London, September 20, 2026, and visible flight options. The video plays at 1× with short opening/closing holds.
+The current video is a **7,073 ms** Google Flights run. Timing starts after initial page observation and includes model calls, generated text, browser work, stale decisions, and loading waits. A fresh independent check verifies the one-way setting, Zürich, London, September 20, 2026, and visible flight options. The video plays at 1×, with no opening hold and a 0.5-second final hold.
-The same operation/target policy has also opened the requested Wikipedia article. These are small live demonstrations, not a general reliability benchmark. Earlier development runs, failures, model choices, and measurement boundaries are documented in [performance.md](docs/performance.md).
+In six alternating runs with identical models and settings, both versions passed **3/3**. Median task time went from **9.450 s → 7.092 s**, a **25% reduction**; median browser protocol calls went from **1,092 → 101**. This is three repeats of one task on one browser profile, not a general reliability benchmark.
-The recording predates a shared-rule fix for search/filter targets. The final policy passed the same flight search again in 12.9 seconds and a local filter regression in 4.4 seconds; the original recording and regression measurements are kept separately.
+The same policy opened the requested Wikipedia article in **2.798 s** and passed a local hotel search/filter task in **1.896 s**. Runs, failures, source hashes, and measurement boundaries are in [performance.md](docs/performance.md).
-The older 12.9-second video used five prepared steps and copied quoted strings. It is historical evidence, not the current architecture. A `DONE` choice still requires independent outcome verification. Frames, canvas, uploads, pop-up tabs, nested scrolling, and arbitrary keyboard widgets remain outside this MVP. Owned tabs share the existing Chrome profile.
+A `DONE` choice still requires independent outcome verification. The DOM reader handles common HTML and ARIA controls, not the full accessible-name specification. Shadow roots, frames, canvas, uploads, pop-up tabs, nested scrolling, and arbitrary keyboard widgets remain outside this MVP. Owned tabs share the existing Chrome profile.
## Development
@@ -124,10 +127,11 @@ The older 12.9-second video used five prepared steps and copied quoted strings.
uv run ruff check .
uv run pytest
node --check jev_ultrafast/static/app.js
+node --check jev_ultrafast/snapshot.js
uv build
```
-Tests are offline. Live examples and recording scripts make paid API calls. `scripts/record_flights.py` captures original browser timestamps; `scripts/render_demo.py` renders the selected verified run at 1× and crops out the Google account strip. Credentials and raw traces stay ignored.
+Tests are offline. `uv run python scripts/check_guards.py` checks real controls in a local browser without model calls. Live examples and recording scripts make paid API calls. `scripts/record_flights.py <new-folder>` captures original browser timestamps; `scripts/render_demo.py <recording-folder>` renders that verified run at 1× and crops out the Google account strip. Credentials and raw traces stay ignored.
---
diff --git a/docs/demo.gif b/docs/demo.gif
index f997d98..3bb7ace 100644
Binary files a/docs/demo.gif and b/docs/demo.gif differ
diff --git a/docs/demo.mp4 b/docs/demo.mp4
index db87af4..c82feb7 100644
Binary files a/docs/demo.mp4 and b/docs/demo.mp4 differ
diff --git a/docs/design.md b/docs/design.md
index 0770ed4..52f93a5 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -10,11 +10,15 @@ TYPE_TEXT sends the goal, selected field, visible page context, and recent actio
## Runtime
-Accessibility supplies names, roles, values, and backend node IDs. Cached remote object references avoid resolving the same DOM node every observation; a single read obtains current rectangles and dropdown options. New references resolve concurrently. Document changes invalidate the cache. Geometry is never cached across decisions.
+One browser-side DOM snapshot supplies common HTML/ARIA roles, names, values, visible text, and executable targets. A WeakMap gives each actual node a code-owned identity; a Map keeps the live references used for execution. Replaced elements receive new identities, disconnected references are pruned, and navigation starts a new cache. These IDs are not CDP backend node IDs. Geometry is always read again immediately before input.
-The model sees visible text and accessible alerts/status. Background focus emulation keeps animation frames running in the owned tab. Screenshots are optional and disabled in library calls by default; `screenshots=True` or `record_dir=...` enables them. The inspector enables them explicitly. A continuous screencast can record a run separately.
+The model sees visible text. Background focus emulation keeps animation frames running in the owned tab. Screenshots are optional and disabled in library calls by default; `screenshots=True` or `record_dir=...` enables them. The inspector enables them explicitly. A continuous screencast can record a run separately.
-A full DOM mutation marker plus current form properties invalidates stale decisions. Replaced nodes, changed values, and covered targets cannot silently reuse an old click. Browser mutations are not retried by transport recovery. Completed execution is logged before the next observation, including when that observation encounters a navigation.
+Freshness compares semantic state instead of counting DOM mutations. Before a click/select, guards compare the document, full URL, viewport, safe form values/states, selected target, and nearby form/dialog/row context. Text generation, typing, scrolling, waiting, and completion use a full semantic comparison. The executor rechecks target visibility, enabled state, geometry, and click occlusion. Scoped guards intentionally permit unrelated visible content to change; this is a practical heuristic, not proof that arbitrary page changes are irrelevant to the goal.
+
+Browser mutations are not retried by transport recovery. Completed execution is logged before the next observation, including when that observation encounters a navigation. An interrupted native-select evaluation stops because its change event may already have fired. Typing uses a browser select-all command followed by CDP text insertion, so existing input contents are replaced.
+
+The next observation waits for up to two animation frames or 50 ms after an interaction. Editable ARIA comboboxes instead wait for visible options, capped at 200 ms. This avoids paying for a prediction before autocomplete suggestions arrive. An explicit WAIT remains 100 ms; network loading is never fast-forwarded in the recording.
## What changed after the first demo
@@ -26,4 +30,4 @@ The audit also found that treating every INPUT as editable misclassified checkbo
Sixty browser actions and 120 decision requests bound a run. Up to 250 action candidates are retained; truncated candidates cannot be selected. The service stays loopback-only, serializes inspector actions, and checks Host, Origin, and a local request token. Credentials remain server-side. Tabs share the existing Chrome profile.
-The policy is generic, but two websites do not establish broad reliability. Unsupported frames, canvas, uploads, nested scrolling, pop-ups, and complex keyboard interactions can block progress. A valid action can still be wrong. Independent checks, rather than the model's DONE choice, determine whether the demonstrated task succeeded.
+The policy is generic, but two websites do not establish broad reliability. Name resolution covers common labels, ARIA references, and text; it is not the browser's full accessibility algorithm. Shadow roots, frames, canvas, uploads, nested scrolling, pop-ups, and complex keyboard interactions can block progress. A valid action can still be wrong. Independent checks, rather than the model's DONE choice, determine whether the demonstrated task succeeded.
diff --git a/docs/flights-measurement.json b/docs/flights-measurement.json
index 304f121..0315d4a 100644
--- a/docs/flights-measurement.json
+++ b/docs/flights-measurement.json
@@ -1,28 +1,27 @@
{
- "task": "Find one-way flights from Zurich to London on September 20, 2026, for one adult in economy. Stop when matching flight options are visible. Do not select or book a flight.",
- "elapsed_ms": 11387,
+ "elapsed_ms": 7073,
+ "decision_requests": 17,
+ "decision_median_ms": 178,
+ "decision_total_ms": 3720,
+ "browser_actions": 11,
+ "wait_actions": 1,
"models": {
"decision": [
"jev-1.13.0"
],
"text": [
- "google/gemini-2.5-flash-lite"
+ "inception/mercury-2.5"
]
},
- "decision_requests": 23,
- "decision_median_ms": 175,
- "decision_total_ms": 4160,
- "browser_actions": 11,
- "wait_actions": 1,
"text_calls": [
{
- "model": "google/gemini-2.5-flash-lite",
- "latency_ms": 873,
+ "model": "inception/mercury-2.5",
+ "latency_ms": 581,
"usage": {
- "prompt_tokens": 324,
- "completion_tokens": 7,
- "total_tokens": 331,
- "cost": 3.52e-05,
+ "prompt_tokens": 440,
+ "completion_tokens": 78,
+ "total_tokens": 518,
+ "cost": 2.93e-05,
"is_byok": false,
"prompt_tokens_details": {
"cached_tokens": 0,
@@ -31,9 +30,9 @@
"video_tokens": 0
},
"cost_details": {
- "upstream_inference_cost": 3.52e-05,
- "upstream_inference_prompt_cost": 3.24e-05,
- "upstream_inference_completions_cost": 2.8e-06
+ "upstream_inference_cost": 2.93e-05,
+ "upstream_inference_prompt_cost": 1.76e-05,
+ "upstream_inference_completions_cost": 1.17e-05
},
"completion_tokens_details": {
"reasoning_tokens": 0,
@@ -45,13 +44,13 @@
"value": "Zurich"
},
{
- "model": "google/gemini-2.5-flash-lite",
- "latency_ms": 590,
+ "model": "inception/mercury-2.5",
+ "latency_ms": 346,
"usage": {
- "prompt_tokens": 357,
- "completion_tokens": 6,
- "total_tokens": 363,
- "cost": 3.81e-05,
+ "prompt_tokens": 483,
+ "completion_tokens": 94,
+ "total_tokens": 577,
+ "cost": 3.342e-05,
"is_byok": false,
"prompt_tokens_details": {
"cached_tokens": 0,
@@ -60,9 +59,9 @@
"video_tokens": 0
},
"cost_details": {
- "upstream_inference_cost": 3.81e-05,
- "upstream_inference_prompt_cost": 3.57e-05,
- "upstream_inference_completions_cost": 2.4e-06
+ "upstream_inference_cost": 3.342e-05,
+ "upstream_inference_prompt_cost": 1.932e-05,
+ "upstream_inference_completions_cost": 1.41e-05
},
"completion_tokens_details": {
"reasoning_tokens": 0,
@@ -86,44 +85,66 @@
"results": true
},
"visible_flights": [
- "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
- "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
- "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
]
},
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "6ef6c0cf9041f648c49bb09adf6b83d73ba301de5e87ffdeb03b0a4ce9e487ab",
+ "snapshot.js": "e50473501c8fb8e70f3b21866d987393e3f2315c639d638bd477d170e81ed78d",
+ "agent.py": "aaf8b271cb0ee6643fe7beb525328ab80de8568c7ac044d02b9c6721161e7c8b",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 90558,
+ "output_tokens": 6325
+ },
+ "task": "Find one-way flights from Zurich to London on September 20, 2026, for one adult in economy. Stop when matching flight options are visible. Do not select or book a flight.",
+ "timing": "First prediction after initial homepage observation through final DONE; setup and independent final verification excluded.",
+ "video": {
+ "source_frames": 187,
+ "speed": 1,
+ "intro_hold_ms": 0,
+ "end_hold_ms": 500,
+ "crop": "Top 64 px account/navigation strip removed from every frame."
+ },
"actions": [
{
"operation": "CLICK",
- "target": "19",
+ "target": "12",
"action": "Change ticket type. Round trip",
"kind": "click",
"text": null,
- "executed_ms": 597,
- "elapsed_ms": 641,
- "latency_ms": 204,
+ "executed_ms": 336,
+ "elapsed_ms": 372,
+ "latency_ms": 299,
"text_latency_ms": 0
},
{
"operation": "CLICK",
- "target": "2",
+ "target": "14",
"action": "One way",
"kind": "click",
"text": null,
- "executed_ms": 978,
- "elapsed_ms": 1209,
- "latency_ms": 149,
+ "executed_ms": 640,
+ "elapsed_ms": 725,
+ "latency_ms": 217,
"text_latency_ms": 0
},
{
"operation": "TYPE_TEXT",
- "target": "22",
+ "target": "15",
"action": "Where from?",
"kind": "fill",
"text": "Zurich",
- "executed_ms": 2313,
- "elapsed_ms": 2332,
- "latency_ms": 152,
- "text_latency_ms": 873
+ "executed_ms": 1595,
+ "elapsed_ms": 1770,
+ "latency_ms": 126,
+ "text_latency_ms": 581
},
{
"operation": "CLICK",
@@ -131,21 +152,21 @@
"action": "Z\u00fcrich, Switzerland",
"kind": "click",
"text": null,
- "executed_ms": 2727,
- "elapsed_ms": 2780,
- "latency_ms": 206,
+ "executed_ms": 1930,
+ "elapsed_ms": 1959,
+ "latency_ms": 121,
"text_latency_ms": 0
},
{
"operation": "TYPE_TEXT",
- "target": "22",
+ "target": "16",
"action": "Where to? ",
"kind": "fill",
"text": "London",
- "executed_ms": 4323,
- "elapsed_ms": 4350,
- "latency_ms": 157,
- "text_latency_ms": 590
+ "executed_ms": 2748,
+ "elapsed_ms": 2875,
+ "latency_ms": 120,
+ "text_latency_ms": 346
},
{
"operation": "CLICK",
@@ -153,53 +174,53 @@
"action": "London, United Kingdom",
"kind": "click",
"text": null,
- "executed_ms": 4704,
- "elapsed_ms": 4757,
- "latency_ms": 152,
+ "executed_ms": 3053,
+ "elapsed_ms": 3085,
+ "latency_ms": 143,
"text_latency_ms": 0
},
{
"operation": "CLICK",
- "target": "23",
+ "target": "18",
"action": "Open Departure",
"kind": "click",
"text": null,
- "executed_ms": 5271,
- "elapsed_ms": 5526,
- "latency_ms": 142,
+ "executed_ms": 3452,
+ "elapsed_ms": 3520,
+ "latency_ms": 112,
"text_latency_ms": 0
},
{
"operation": "CLICK",
- "target": "9",
+ "target": "7",
"action": "Sunday, September 20, 2026",
"kind": "click",
"text": null,
- "executed_ms": 5739,
- "elapsed_ms": 5866,
- "latency_ms": 176,
+ "executed_ms": 3769,
+ "elapsed_ms": 3810,
+ "latency_ms": 203,
"text_latency_ms": 0
},
{
"operation": "CLICK",
- "target": "2",
+ "target": "56",
"action": "Done. Search for one-way flights, departing on September 20, 2026",
"kind": "click",
"text": null,
- "executed_ms": 6165,
- "elapsed_ms": 6742,
- "latency_ms": 250,
+ "executed_ms": 4097,
+ "elapsed_ms": 4136,
+ "latency_ms": 247,
"text_latency_ms": 0
},
{
"operation": "CLICK",
- "target": "13",
+ "target": "19",
"action": "Search",
"kind": "click",
"text": null,
- "executed_ms": 6937,
- "elapsed_ms": 7298,
- "latency_ms": 143,
+ "executed_ms": 5217,
+ "elapsed_ms": 5320,
+ "latency_ms": 178,
"text_latency_ms": 0
},
{
@@ -208,68 +229,10 @@
"action": "Wait for the page to update",
"kind": "wait",
"text": null,
- "executed_ms": 7659,
- "elapsed_ms": 7728,
- "latency_ms": 248,
+ "executed_ms": 5587,
+ "elapsed_ms": 5594,
+ "latency_ms": 141,
"text_latency_ms": 0
}
- ],
- "timing": "First prediction after initial homepage observation through final DONE. Includes text generation, browser work, stale decisions and loading. Initial navigation/setup excluded.",
- "video": {
- "source_frames": 309,
- "speed": 1,
- "intro_hold_ms": 750,
- "end_hold_ms": 2000,
- "crop": "Top 64 px Google account/navigation strip removed from every frame."
- },
- "second_site": {
- "task": "Find and open the Wikipedia article about G\u00f6del\u2019s incompleteness theorems.",
- "elapsed_ms": 3678,
- "url": "https://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems",
- "decision_requests": 3,
- "text_calls": 1,
- "verification": {
- "passed": true
- }
- },
- "source_hashes": {
- "questions.py": "9b4cf0c64c60621c91a1e345abe23a98e69c2b505a5b824ad680711a4fa21902",
- "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
- "model.py": "e4fbecf3a2d2c5426c8f944f297901c573b5195891e9e6868ab1299383aa895d",
- "browser.py": "d2b0e468c2dac3f4d3cbba51f3619fe26fe44fb1554446363d8d1aff5efe22f2",
- "agent.py": "be5434b79de0410352485e734ff4bb7a5d9556ce22ae47f231b5be3aa67161a4",
- "demo.py": "57daa14331d4622e3de4d533ca8f7a6154e56ef4678d80a74db7f3179b16a73c"
- },
- "scope": "Two single-goal tasks with live APIs, one existing Chrome profile. Not a matched benchmark or general reliability claim.",
- "final_policy_regression": {
- "elapsed_ms": 12898,
- "decision_requests": 23,
- "text_model_calls": 2,
- "verification": {
- "passed": true,
- "checks": {
- "search_page": true,
- "one_way": true,
- "origin": true,
- "destination": true,
- "date": true,
- "year": true,
- "results": true
- },
- "visible_flights": [
- "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
- "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
- "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
- ]
- },
- "source_hashes": {
- "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
- "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
- "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
- "browser.py": "d2b0e468c2dac3f4d3cbba51f3619fe26fe44fb1554446363d8d1aff5efe22f2",
- "agent.py": "be5434b79de0410352485e734ff4bb7a5d9556ce22ae47f231b5be3aa67161a4",
- "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
- },
- "note": "Recorded video predates shared operation/target rules, explicit toggle state, and search-submission rule. Separate final-policy regression; original recording hashes above are unchanged."
- }
+ ]
}
diff --git a/docs/flights-result.png b/docs/flights-result.png
index 7cbf1c7..53af3f5 100644
Binary files a/docs/flights-result.png and b/docs/flights-result.png differ
diff --git a/docs/full-speed-measurement.json b/docs/full-speed-measurement.json
new file mode 100644
index 0000000..d491488
--- /dev/null
+++ b/docs/full-speed-measurement.json
@@ -0,0 +1,895 @@
+{
+ "task": "Find one-way flights from Zurich to London on September 20, 2026, for one adult in economy. Stop when matching flight options are visible. Do not select or book a flight.",
+ "baseline_commit": "68c077bf79caca4e817b8e8a5854b2efa0c81ff6",
+ "summary": {
+ "baseline": {
+ "runs": 3,
+ "passed": 3,
+ "median_ms": 9450,
+ "median_cdp_calls": 1092
+ },
+ "candidate": {
+ "runs": 3,
+ "passed": 3,
+ "median_ms": 7092,
+ "median_cdp_calls": 101
+ }
+ },
+ "runs": [
+ {
+ "elapsed_ms": 11214,
+ "decision_requests": 26,
+ "decision_median_ms": 195.5,
+ "decision_total_ms": 5913,
+ "browser_actions": 13,
+ "wait_actions": 3,
+ "models": {
+ "decision": [
+ "jev-1.13.0"
+ ],
+ "text": [
+ "inception/mercury-2.5"
+ ]
+ },
+ "text_calls": [
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 490,
+ "usage": {
+ "prompt_tokens": 447,
+ "completion_tokens": 51,
+ "total_tokens": 498,
+ "cost": 2.553e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.553e-05,
+ "upstream_inference_prompt_cost": 1.788e-05,
+ "upstream_inference_completions_cost": 7.65e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where from?",
+ "value": "Zurich"
+ },
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 792,
+ "usage": {
+ "prompt_tokens": 482,
+ "completion_tokens": 60,
+ "total_tokens": 542,
+ "cost": 2.828e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.828e-05,
+ "upstream_inference_prompt_cost": 1.928e-05,
+ "upstream_inference_completions_cost": 9e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where to? ",
+ "value": "London"
+ }
+ ],
+ "verification": {
+ "passed": true,
+ "checks": {
+ "search_page": true,
+ "one_way": true,
+ "origin": true,
+ "destination": true,
+ "date": true,
+ "year": true,
+ "results": true
+ },
+ "visible_flights": [
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ ]
+ },
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "d2b0e468c2dac3f4d3cbba51f3619fe26fe44fb1554446363d8d1aff5efe22f2",
+ "agent.py": "be5434b79de0410352485e734ff4bb7a5d9556ce22ae47f231b5be3aa67161a4",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 133633,
+ "output_tokens": 9468
+ },
+ "arm": "baseline",
+ "pair": 1,
+ "configuration": {
+ "TYPESAFE_MODEL": null,
+ "TEXT_MODEL": "inception/mercury-2.5",
+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",
+ "TEXT_MODEL_REASONING": "none"
+ },
+ "browser_version": "Chrome/152.0.7977.83",
+ "task_hash": "bce327f45dc380ca9cd76fac5b70bfddd7ce36f8e083c1f900522af2a3499ff9",
+ "cdp": {
+ "Runtime.evaluate": {
+ "count": 158,
+ "ms": 1487.242
+ },
+ "Accessibility.getFullAXTree": {
+ "count": 30,
+ "ms": 1238.199
+ },
+ "Runtime.callFunctionOn": {
+ "count": 40,
+ "ms": 223.157
+ },
+ "DOM.resolveNode": {
+ "count": 828,
+ "ms": 1215.957
+ },
+ "DOM.getBoxModel": {
+ "count": 10,
+ "ms": 8.559
+ },
+ "DOM.getNodeForLocation": {
+ "count": 10,
+ "ms": 10.932
+ },
+ "Input.dispatchMouseEvent": {
+ "count": 20,
+ "ms": 351.816
+ },
+ "Input.dispatchKeyEvent": {
+ "count": 4,
+ "ms": 35.583
+ },
+ "Input.insertText": {
+ "count": 2,
+ "ms": 11.208
+ }
+ },
+ "error": null,
+ "browser_closed": true
+ },
+ {
+ "elapsed_ms": 6964,
+ "decision_requests": 17,
+ "decision_median_ms": 169,
+ "decision_total_ms": 3284,
+ "browser_actions": 13,
+ "wait_actions": 3,
+ "models": {
+ "decision": [
+ "jev-1.13.0"
+ ],
+ "text": [
+ "inception/mercury-2.5"
+ ]
+ },
+ "text_calls": [
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 448,
+ "usage": {
+ "prompt_tokens": 456,
+ "completion_tokens": 59,
+ "total_tokens": 515,
+ "cost": 2.709e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.709e-05,
+ "upstream_inference_prompt_cost": 1.824e-05,
+ "upstream_inference_completions_cost": 8.85e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where from?",
+ "value": "Zurich"
+ },
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 310,
+ "usage": {
+ "prompt_tokens": 471,
+ "completion_tokens": 62,
+ "total_tokens": 533,
+ "cost": 2.814e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.814e-05,
+ "upstream_inference_prompt_cost": 1.884e-05,
+ "upstream_inference_completions_cost": 9.3e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where to? ",
+ "value": "London"
+ }
+ ],
+ "verification": {
+ "passed": true,
+ "checks": {
+ "search_page": true,
+ "one_way": true,
+ "origin": true,
+ "destination": true,
+ "date": true,
+ "year": true,
+ "results": true
+ },
+ "visible_flights": [
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ ]
+ },
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "6ef6c0cf9041f648c49bb09adf6b83d73ba301de5e87ffdeb03b0a4ce9e487ab",
+ "snapshot.js": "e50473501c8fb8e70f3b21866d987393e3f2315c639d638bd477d170e81ed78d",
+ "agent.py": "aaf8b271cb0ee6643fe7beb525328ab80de8568c7ac044d02b9c6721161e7c8b",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 84650,
+ "output_tokens": 5899
+ },
+ "arm": "candidate",
+ "pair": 1,
+ "configuration": {
+ "TYPESAFE_MODEL": null,
+ "TEXT_MODEL": "inception/mercury-2.5",
+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",
+ "TEXT_MODEL_REASONING": "none"
+ },
+ "browser_version": "Chrome/152.0.7977.83",
+ "task_hash": "bce327f45dc380ca9cd76fac5b70bfddd7ce36f8e083c1f900522af2a3499ff9",
+ "cdp": {
+ "Runtime.evaluate": {
+ "count": 75,
+ "ms": 2251.328
+ },
+ "Input.dispatchMouseEvent": {
+ "count": 20,
+ "ms": 322.317
+ },
+ "Input.dispatchKeyEvent": {
+ "count": 4,
+ "ms": 22.038
+ },
+ "Input.insertText": {
+ "count": 2,
+ "ms": 8.988
+ }
+ },
+ "error": null,
+ "browser_closed": true
+ },
+ {
+ "elapsed_ms": 7913,
+ "decision_requests": 18,
+ "decision_median_ms": 182.5,
+ "decision_total_ms": 3595,
+ "browser_actions": 13,
+ "wait_actions": 3,
+ "models": {
+ "decision": [
+ "jev-1.13.0"
+ ],
+ "text": [
+ "inception/mercury-2.5"
+ ]
+ },
+ "text_calls": [
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 415,
+ "usage": {
+ "prompt_tokens": 440,
+ "completion_tokens": 47,
+ "total_tokens": 487,
+ "cost": 2.465e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.465e-05,
+ "upstream_inference_prompt_cost": 1.76e-05,
+ "upstream_inference_completions_cost": 7.05e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where from?",
+ "value": "Zurich"
+ },
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 1137,
+ "usage": {
+ "prompt_tokens": 485,
+ "completion_tokens": 511,
+ "total_tokens": 996,
+ "cost": 9.605e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 9.605e-05,
+ "upstream_inference_prompt_cost": 1.94e-05,
+ "upstream_inference_completions_cost": 7.665e-05
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where to? ",
+ "value": "London"
+ }
+ ],
+ "verification": {
+ "passed": true,
+ "checks": {
+ "search_page": true,
+ "one_way": true,
+ "origin": true,
+ "destination": true,
+ "date": true,
+ "year": true,
+ "results": true
+ },
+ "visible_flights": [
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ ]
+ },
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "6ef6c0cf9041f648c49bb09adf6b83d73ba301de5e87ffdeb03b0a4ce9e487ab",
+ "snapshot.js": "e50473501c8fb8e70f3b21866d987393e3f2315c639d638bd477d170e81ed78d",
+ "agent.py": "aaf8b271cb0ee6643fe7beb525328ab80de8568c7ac044d02b9c6721161e7c8b",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 88844,
+ "output_tokens": 6242
+ },
+ "arm": "candidate",
+ "pair": 2,
+ "configuration": {
+ "TYPESAFE_MODEL": null,
+ "TEXT_MODEL": "inception/mercury-2.5",
+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",
+ "TEXT_MODEL_REASONING": "none"
+ },
+ "browser_version": "Chrome/152.0.7977.83",
+ "task_hash": "bce327f45dc380ca9cd76fac5b70bfddd7ce36f8e083c1f900522af2a3499ff9",
+ "cdp": {
+ "Runtime.evaluate": {
+ "count": 77,
+ "ms": 2076.599
+ },
+ "Input.dispatchMouseEvent": {
+ "count": 20,
+ "ms": 334.491
+ },
+ "Input.dispatchKeyEvent": {
+ "count": 4,
+ "ms": 23.523
+ },
+ "Input.insertText": {
+ "count": 2,
+ "ms": 10.362
+ }
+ },
+ "error": null,
+ "browser_closed": true
+ },
+ {
+ "elapsed_ms": 8984,
+ "decision_requests": 21,
+ "decision_median_ms": 167,
+ "decision_total_ms": 4004,
+ "browser_actions": 12,
+ "wait_actions": 2,
+ "models": {
+ "decision": [
+ "jev-1.13.0"
+ ],
+ "text": [
+ "inception/mercury-2.5"
+ ]
+ },
+ "text_calls": [
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 395,
+ "usage": {
+ "prompt_tokens": 460,
+ "completion_tokens": 74,
+ "total_tokens": 534,
+ "cost": 2.95e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.95e-05,
+ "upstream_inference_prompt_cost": 1.84e-05,
+ "upstream_inference_completions_cost": 1.11e-05
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where from?",
+ "value": "Zurich"
+ },
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 338,
+ "usage": {
+ "prompt_tokens": 492,
+ "completion_tokens": 43,
+ "total_tokens": 535,
+ "cost": 2.613e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.613e-05,
+ "upstream_inference_prompt_cost": 1.968e-05,
+ "upstream_inference_completions_cost": 6.45e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where to? ",
+ "value": "London"
+ }
+ ],
+ "verification": {
+ "passed": true,
+ "checks": {
+ "search_page": true,
+ "one_way": true,
+ "origin": true,
+ "destination": true,
+ "date": true,
+ "year": true,
+ "results": true
+ },
+ "visible_flights": [
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ ]
+ },
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "d2b0e468c2dac3f4d3cbba51f3619fe26fe44fb1554446363d8d1aff5efe22f2",
+ "agent.py": "be5434b79de0410352485e734ff4bb7a5d9556ce22ae47f231b5be3aa67161a4",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 106691,
+ "output_tokens": 7531
+ },
+ "arm": "baseline",
+ "pair": 2,
+ "configuration": {
+ "TYPESAFE_MODEL": null,
+ "TEXT_MODEL": "inception/mercury-2.5",
+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",
+ "TEXT_MODEL_REASONING": "none"
+ },
+ "browser_version": "Chrome/152.0.7977.83",
+ "task_hash": "bce327f45dc380ca9cd76fac5b70bfddd7ce36f8e083c1f900522af2a3499ff9",
+ "cdp": {
+ "Runtime.evaluate": {
+ "count": 146,
+ "ms": 1595.322
+ },
+ "Accessibility.getFullAXTree": {
+ "count": 30,
+ "ms": 1311.762
+ },
+ "Runtime.callFunctionOn": {
+ "count": 40,
+ "ms": 315.525
+ },
+ "DOM.resolveNode": {
+ "count": 828,
+ "ms": 846.738
+ },
+ "DOM.getBoxModel": {
+ "count": 10,
+ "ms": 8.759
+ },
+ "DOM.getNodeForLocation": {
+ "count": 10,
+ "ms": 12.157
+ },
+ "Input.dispatchMouseEvent": {
+ "count": 20,
+ "ms": 337.511
+ },
+ "Input.dispatchKeyEvent": {
+ "count": 4,
+ "ms": 38.385
+ },
+ "Input.insertText": {
+ "count": 2,
+ "ms": 11.307
+ }
+ },
+ "error": null,
+ "browser_closed": true
+ },
+ {
+ "elapsed_ms": 9450,
+ "decision_requests": 22,
+ "decision_median_ms": 187.0,
+ "decision_total_ms": 4261,
+ "browser_actions": 12,
+ "wait_actions": 2,
+ "models": {
+ "decision": [
+ "jev-1.13.0"
+ ],
+ "text": [
+ "inception/mercury-2.5"
+ ]
+ },
+ "text_calls": [
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 460,
+ "usage": {
+ "prompt_tokens": 460,
+ "completion_tokens": 55,
+ "total_tokens": 515,
+ "cost": 2.665e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.665e-05,
+ "upstream_inference_prompt_cost": 1.84e-05,
+ "upstream_inference_completions_cost": 8.25e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where from?",
+ "value": "Zurich"
+ },
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 513,
+ "usage": {
+ "prompt_tokens": 491,
+ "completion_tokens": 63,
+ "total_tokens": 554,
+ "cost": 2.909e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.909e-05,
+ "upstream_inference_prompt_cost": 1.964e-05,
+ "upstream_inference_completions_cost": 9.45e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where to? ",
+ "value": "London"
+ }
+ ],
+ "verification": {
+ "passed": true,
+ "checks": {
+ "search_page": true,
+ "one_way": true,
+ "origin": true,
+ "destination": true,
+ "date": true,
+ "year": true,
+ "results": true
+ },
+ "visible_flights": [
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ ]
+ },
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "d2b0e468c2dac3f4d3cbba51f3619fe26fe44fb1554446363d8d1aff5efe22f2",
+ "agent.py": "be5434b79de0410352485e734ff4bb7a5d9556ce22ae47f231b5be3aa67161a4",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 115547,
+ "output_tokens": 8131
+ },
+ "arm": "baseline",
+ "pair": 3,
+ "configuration": {
+ "TYPESAFE_MODEL": null,
+ "TEXT_MODEL": "inception/mercury-2.5",
+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",
+ "TEXT_MODEL_REASONING": "none"
+ },
+ "browser_version": "Chrome/152.0.7977.83",
+ "task_hash": "bce327f45dc380ca9cd76fac5b70bfddd7ce36f8e083c1f900522af2a3499ff9",
+ "cdp": {
+ "Runtime.evaluate": {
+ "count": 148,
+ "ms": 1452.987
+ },
+ "Accessibility.getFullAXTree": {
+ "count": 30,
+ "ms": 1382.719
+ },
+ "Runtime.callFunctionOn": {
+ "count": 40,
+ "ms": 254.649
+ },
+ "DOM.resolveNode": {
+ "count": 828,
+ "ms": 1792.588
+ },
+ "DOM.getBoxModel": {
+ "count": 10,
+ "ms": 9.862
+ },
+ "DOM.getNodeForLocation": {
+ "count": 10,
+ "ms": 11.54
+ },
+ "Input.dispatchMouseEvent": {
+ "count": 20,
+ "ms": 356.041
+ },
+ "Input.dispatchKeyEvent": {
+ "count": 4,
+ "ms": 41.423
+ },
+ "Input.insertText": {
+ "count": 2,
+ "ms": 12.43
+ }
+ },
+ "error": null,
+ "browser_closed": true
+ },
+ {
+ "elapsed_ms": 7092,
+ "decision_requests": 16,
+ "decision_median_ms": 182.5,
+ "decision_total_ms": 2996,
+ "browser_actions": 12,
+ "wait_actions": 2,
+ "models": {
+ "decision": [
+ "jev-1.13.0"
+ ],
+ "text": [
+ "inception/mercury-2.5"
+ ]
+ },
+ "text_calls": [
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 540,
+ "usage": {
+ "prompt_tokens": 453,
+ "completion_tokens": 74,
+ "total_tokens": 527,
+ "cost": 2.922e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.922e-05,
+ "upstream_inference_prompt_cost": 1.812e-05,
+ "upstream_inference_completions_cost": 1.11e-05
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where from?",
+ "value": "Zurich"
+ },
+ {
+ "model": "inception/mercury-2.5",
+ "latency_ms": 499,
+ "usage": {
+ "prompt_tokens": 483,
+ "completion_tokens": 59,
+ "total_tokens": 542,
+ "cost": 2.817e-05,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 2.817e-05,
+ "upstream_inference_prompt_cost": 1.932e-05,
+ "upstream_inference_completions_cost": 8.85e-06
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "field": "Where to? ",
+ "value": "London"
+ }
+ ],
+ "verification": {
+ "passed": true,
+ "checks": {
+ "search_page": true,
+ "one_way": true,
+ "origin": true,
+ "destination": true,
+ "date": true,
+ "year": true,
+ "results": true
+ },
+ "visible_flights": [
+ "From 216 US dollars.This price does not include overhead bin access. Nonstop flight with easyJet. Leaves Zurich Airport at 4:45 PM on Sunday, September 20 and arrives at London Gatwick Airport at 5:35 PM on Sunday, September 20. Total duration 1 hr 50 min. Select flight",
+ "From 265 US dollars. Nonstop flight with British Airways. Operated by BA Cityflyer. Leaves Zurich Airport at 8:25 PM on Sunday, September 20 and arrives at London City Airport at 9:00 PM on Sunday, September 20. Total duration 1 hr 35 min. Select flight",
+ "From 271 US dollars. Nonstop flight with British Airways. Leaves Zurich Airport at 1:20 PM on Sunday, September 20 and arrives at Heathrow Airport at 2:20 PM on Sunday, September 20. Total duration 2 hr. Select flight"
+ ]
+ },
+ "source_hashes": {
+ "questions.py": "66a7054b85040b949e1757311257ea0c5a843c635f9a40c99f6d15ad660fb422",
+ "__init__.py": "60f025b8d24465e2c0f7a3547d43b8020fd8843de7b6cb3f892ef63f5548cf63",
+ "model.py": "a85ada8458d23642c5c8a4095acf0565e6268f81dcda26f6308942b653e9c9f3",
+ "browser.py": "6ef6c0cf9041f648c49bb09adf6b83d73ba301de5e87ffdeb03b0a4ce9e487ab",
+ "snapshot.js": "e50473501c8fb8e70f3b21866d987393e3f2315c639d638bd477d170e81ed78d",
+ "agent.py": "aaf8b271cb0ee6643fe7beb525328ab80de8568c7ac044d02b9c6721161e7c8b",
+ "demo.py": "a0cfb10909b370efb284cbbe16bdb4b7e7e06ba6385827404169027645a1d8a4"
+ },
+ "tokens": {
+ "input_tokens": 82661,
+ "output_tokens": 5783
+ },
+ "arm": "candidate",
+ "pair": 3,
+ "configuration": {
+ "TYPESAFE_MODEL": null,
+ "TEXT_MODEL": "inception/mercury-2.5",
+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",
+ "TEXT_MODEL_REASONING": "none"
+ },
+ "browser_version": "Chrome/152.0.7977.83",
+ "task_hash": "bce327f45dc380ca9cd76fac5b70bfddd7ce36f8e083c1f900522af2a3499ff9",
+ "cdp": {
+ "Runtime.evaluate": {
+ "count": 71,
+ "ms": 2483.491
+ },
+ "Input.dispatchMouseEvent": {
+ "count": 20,
+ "ms": 328.154
+ },
+ "Input.dispatchKeyEvent": {
+ "count": 4,
+ "ms": 20.116
+ },
+ "Input.insertText": {
+ "count": 2,
+ "ms": 8.988
+ }
+ },
+ "error": null,
+ "browser_closed": true
+ }
+ ],
+ "scope": "Three alternating pairs of one task in one existing Chrome profile, 1120x780 viewport. All attempts included. Same goal, independent checker, models, and budgets. Live site/network/caches not controlled.",
+ "final_source_note": "After timing and recording, added stop-on-interruption handling for native SELECT. It changes a failure path not exercised by Flights. Covered by offline fault-injection and local browser checks."
+}
diff --git a/docs/launch-draft.md b/docs/launch-draft.md
new file mode 100644
index 0000000..875483d
--- /dev/null
+++ b/docs/launch-draft.md
@@ -0,0 +1,19 @@
+# Tweet draft
+
+browser agents should move like this
+
+Zurich → London on Google Flights in 7.1 seconds. real time.
+
+> Jev picks the action + element
+> a small LLM writes the text
+> one goal, dynamic controls
+
+still waiting for Google to load haha
+
+https://github.com/browser-use/jev-ultrafast
+
+---
+
+Draft only. Attach demo.mp4. Based on the 7.073-second verified recording; setup and initial navigation precede the timer.
+
+Voice reference: recovered the “Find high-impact X posts” Codex task and its saved authored-post archive, including [the Qwen browser demo post](https://x.com/gregpr07/status/2090985180773388547). Short opening, concrete demo, compact technical explanation.
diff --git a/docs/performance.md b/docs/performance.md
index c1e3e80..43f31cc 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -1,52 +1,55 @@
-# Real tasks, dynamic actions
+# Faster on the real web
-The current agent accepts one natural-language goal, indexes the live page, and asks TypeSafe for an operation plus operation-specific targets in one request. A small LLM generates text. There are no prepared browser steps or quoted-value extraction in these runs.
+The current video completes the Google Flights task in **7.073 seconds at 1×**. It starts with one natural-language goal and uses dynamic controls throughout. Jev selects operation + target in one request; Mercury generates the city strings when TYPE_TEXT is selected.
-| Recorded smoke | Agent time | Jev requests | Text-model calls | Independent result |
-| --- | ---: | ---: | ---: | --- |
-| Google Flights: Zürich → London, one way, 20 September 2026 | **11.387 s** | 23 | 2 | Route, date, year, one-way setting, visible flights checked |
-| Wikipedia: open Gödel’s incompleteness theorems | **3.678 s** | 3 | 1 | Exact destination article URL checked |
+[Video](demo.mp4) · [Recording measurements](flights-measurement.json) · [Matched run measurements](full-speed-measurement.json)
-[Google Flights recording](demo.mp4) · [Machine-readable evidence](flights-measurement.json)
+## Matched runtime comparison
-These are two live smoke tasks, not a broad benchmark or a matched causal speed claim. They used an existing Chrome profile, live network responses, and caches. The policy is site-independent; the outcome checks are task-specific and are not shown to the model.
+Six alternating runs, one task, one existing Chrome profile. Both arms used the same natural-language goal, independent result checker, 1120×780 viewport, TypeSafe `jev-1.13.0`, `inception/mercury-2.5`, disabled text reasoning, and action/request budgets. Initial navigation is excluded in both arms. Each run creates and closes its own tab. All six attempts are included; no provider or verification failures occurred.
-## Recorded flight run
+| Pair | Original runtime | Optimized runtime | Verified |
+| --- | ---: | ---: | --- |
+| 1 | 11.214 s | 6.964 s | Both |
+| 2 | 8.984 s | 7.913 s | Both |
+| 3 | 9.450 s | 7.092 s | Both |
+| **Median** | **9.450 s** | **7.092 s** | **3/3 each** |
-The clock starts with the first prediction, after the generic Google Flights homepage is observed. It ends at the final DONE choice. It includes generated text, model requests, browser operations, observation, discarded stale decisions, and loading waits. Initial navigation, browser setup, and independent post-run checks are outside the clock.
+The optimized runtime was faster in all three pairs. Median task time was **25.0% lower**, median TypeSafe requests fell **22 → 17**, and median browser protocol calls fell **1,092 → 101**. Three pairs are too few for a strong statistical claim (two-sided sign-test p = 0.25). This is a small controlled-input comparison, not a broad agent benchmark; Google, network responses, routing, and browser caches remain live.
-- TypeSafe: `jev-1.13.0`, 23 requests, 175 ms median, 4,160 ms total request time.
-- Text helper: `google/gemini-2.5-flash-lite`, JSON output, reasoning disabled.
-- Generated values: Zurich in 873 ms; London in 590 ms. Two actual helper requests.
-- Browser: 10 interactions and one explicit wait. Additional loading was observed during freshness recovery.
-- Video: 309 continuous screencast frames at original timestamps. 1× playback, with a 750 ms intro and 2-second final hold. Every frame crops out the Google account/navigation strip.
+The original arm is the frozen source from `68c077bf79caca4e817b8e8a5854b2efa0c81ff6`. Both arms use Mercury so the runtime comparison does not conflate a helper-model change with code changes. Per-run source hashes, model settings, token counts, helper costs, browser version, protocol counts, and verification results are in the measurement JSON.
-Observed results included easyJet ZRH → LGW, 16:45–17:35, $216; British Airways/BA Cityflyer ZRH → LCY, 20:25–21:00, $265; and British Airways ZRH → LHR, 13:20–14:20, $271. These are observed fares, not a guarantee of current or cheapest pricing. No flight was selected or booked.
+## Where the time went
-## Changes and failures retained
+The original loop invalidated decisions on every DOM mutation, including animations. It also read the accessibility tree repeatedly and resolved hundreds of DOM nodes. The new snapshot reads common HTML/ARIA controls in one browser call. Click guards compare the selected target and nearby context, plus document/form state. Current geometry and hit-testing still run before input.
-The audit found blocking screenshots in a text-only policy, repeated whole-DOM copies, and hidden-tab animation throttling. Reading current geometry for cached candidate nodes reduced a settled Google homepage observation from roughly 100 ms to 30 ms in the local probe. Removing screenshots initially broke menus because Chrome throttled hidden rendering; focus emulation fixed that cause without switching the visible tab.
+A brief event-based combobox wait lets suggestions arrive before asking Jev to choose from an incomplete popup. Text comes from an actual LLM: the recorded run generated **Zurich in 581 ms** and **London in 346 ms**. Native text replacement was also fixed to issue the browser's select-all command explicitly.
-A first natural-goal flight run took 15.580 s with unnecessary waits after the form was ready. The next took 13.753 s using GLM. The first continuous recording with Gemini took 13.152 s. The final run took 11.387 s after reducing page text to the visible viewport. These changed-code/provider development attempts are **not matched performance comparisons**.
+The recording contains **17 Jev requests**, **10 interactions plus one explicit WAIT**, and **two helper calls**. Median Jev latency was **178 ms**. Search executed at **5.217 s**; final verified completion was **7.073 s**. That final interval includes Google's results loading, state changes, and the completion decision. It stays in the video.
-Wikipedia initially hit a transient document-evaluation error during navigation. After adding read-only navigation recovery, it completed in 11.645 s; the final visible-context version completed in 3.678 s. Provider latency and page context changed, so the difference is not attributed solely to the code.
+Timing begins at the first prediction after initial homepage observation and ends at the accepted DONE choice. It includes text generation, model requests, browser work, stale decisions, and loading. Browser setup, initial navigation, and fresh independent post-run verification are outside the clock. The video contains 186 continuous screencast frames plus the initial screenshot, uses original timestamps, has no opening hold, and adds a 0.5-second final hold. Only the top account/navigation strip is cropped.
-Text-helper probes also rejected two tempting shortcuts: Llama 3.1 8B returned the destination for an origin field, and a Qwen route emitted commentary. The helper now requires exactly one valid JSON `text` field and stops before typing malformed output. This validates the output format, not the semantic correctness of every generated value.
+The recording reports 90,558 TypeSafe input tokens and 6,325 output tokens across all requests. OpenRouter reported **$0.00006272** for the two text calls. That is the text-helper charge, not total task cost: the TypeSafe responses contain token counts without a billed dollar amount, and browser costs are excluded.
-### Filter regression after the recording
+## Other checks
-A local hotel fixture exposed a policy failure: the agent opened a matching property before applying requested filters, returned to the list repeatedly, and could report DONE with unmet requirements. One earlier attempt reached the 60-action limit. The diagnostic runner now writes its trace even on exceptions and retains separate attempt directories.
+| Task | Time | Independent result |
+| --- | ---: | --- |
+| Wikipedia: open Gödel’s incompleteness theorems | 2.798 s | Exact article URL |
+| Local hotel fixture: search Lisbon, Design, Free cancellation, open Casa Flora | 1.896 s | Property plus all three applied filters |
-The target question lacked the operation question's next-step rules. Both now receive the same rules; each target also includes checked/selected state directly. A further rule distinguishes typing into a search field from submitting that search. This keeps the policy generic, with no hotel selectors or prepared browser steps.
+These are separate smoke checks, not matched speed comparisons. Local browser checks cover moved/replaced/hidden/disabled controls, field and checkbox properties, changed nearby context, overlay blocking, native-select execution, real text replacement, autocomplete arrival, and navigation. Offline tests cover the model contract, stale retries, interrupted mutations, helper validation, and independent trip verification.
-After these changes, the original task, “Find a Design stay in Lisbon with Free cancellation and open Casa Flora,” passed in **4.404 s**, with six Jev requests, one text-helper call, and five actions. An explicitly worded search/filter task passed in **1.846 s**. Both independently checked the final property and all three applied filters. The original wording's pre-fix failure is retained; the explicit wording is a separate diagnostic, not a matched improvement claim.
+After the timed runs, native-select interruption handling was tightened: uncertain mutation results stop instead of being treated as retryable stale reads. Flights does not exercise native SELECT. Its timing and recording hashes are retained unchanged; the final failure path is covered by offline fault injection and local browser checks.
-The final policy then passed the same Google Flights task in **12.898 s**, with 23 Jev requests and two text-helper calls. Route, date, year, one-way setting, and visible results passed a fresh post-run observation. The **11.387 s video predates this filter-policy change**; its original source hashes remain in the recording manifest, alongside the separate final-policy regression hashes. These are development smoke runs, not a reliability estimate.
+## Development attempts retained
-## Historical prepared demo
+Before freezing the candidate, the original runtime passed once in 9.302 s. Two accessibility-tree/semantic-guard candidates took 9.395 s and 10.157 s. The first direct-DOM candidate took 8.697 s but failed independent verification because name/value extraction was incomplete. Recursive labels and combobox values fixed that failure; subsequent verified diagnostics took 8.051, 8.631, 8.395, 8.385, and 7.741 s. A Mercury diagnostic passed in 7.559 s. These are changed-code development attempts, not the matched comparison above.
-The original 12.884-second flight demo used five hand-written goal steps and copied quoted city strings. It is not the current architecture. Its measurements remain in [flights-prepared-measurement.json](flights-prepared-measurement.json) and [performance-prepared.md](performance-prepared.md). The earlier 1.086–1.311-second hotel runs were authored local fixtures, documented in [measurement.json](measurement.json).
+A six-call helper probe used the two real flight-field contexts with Gemini 2.5 Flash Lite, Gemini 3.1 Flash Lite, and Mercury 2.5. All returned the correct values in this tiny probe. Mercury then passed the live Flights, Wikipedia, and local filter checks. This does not establish general semantic accuracy. Earlier probes had rejected a model that swapped origin/destination and another that emitted commentary instead of valid JSON.
-## Remaining limits
+The previous 11.387-second recording and post-recording 12.898-second policy regression are described in the [original performance report](https://github.com/browser-use/jev-ultrafast/blob/68c077bf79caca4e817b8e8a5854b2efa0c81ff6/docs/performance.md). The older prepared-step prototype remains in [performance-prepared.md](performance-prepared.md). Raw attempts and original-timestamp frames remain in ignored local artifacts.
-A DONE choice is not independent evidence of success. The action space is capped and can omit elements; frames, canvas, uploads, pop-up tabs, nested scrolling, and arbitrary keyboard controls are unsupported. The two successful tasks demonstrate the same runtime on two sites, not broad generalization or production reliability.
+## Limits
+
+This DOM reader supports common HTML and ARIA controls; it does not implement the full accessible-name algorithm or traverse shadow roots/frames. Scoped click guards deliberately allow unrelated visible updates. Canvas, uploads, new tabs, nested scrolling, and arbitrary keyboard widgets remain unsupported. A valid operation can still be wrong, and DONE is never independent evidence of success.
diff --git a/jev_ultrafast/agent.py b/jev_ultrafast/agent.py
index 2e3ce0a..726d880 100644
--- a/jev_ultrafast/agent.py
+++ b/jev_ultrafast/agent.py
@@ -89,11 +89,11 @@ class Agent:
raise ValueError("Observe and choose before acting")
# Consume once, before any mutation or model call. A retry cannot double-click.
state["decision"] = None
- if not state["browser"].fresh(page):
- state["status"] = "ready"
- raise StalePage("Page changed since the decision. Choose again.")
selected = decision["choice"]
if selected in {"DONE", "BLOCKED"}:
+ if not state["browser"].fresh(page):
+ state["status"] = "ready"
+ raise StalePage("Page changed since the decision. Choose again.")
state["status"] = "done" if selected == "DONE" else "blocked"
state["plan_index"] = int(selected == "DONE")
state["elapsed_ms"] = round((time.perf_counter() - state["started_at"]) * 1000)
@@ -104,6 +104,8 @@ class Agent:
raise ValueError(f"Stopped at the {MAX_STEPS}-action demo budget")
text, helper = None, None
if action["kind"] == "fill":
+ if not state["browser"].fresh(page):
+ raise StalePage("Page changed before text generation. Choose again.")
context = field_context(state["goal"], action, page, state["history"])
if self.pending_text and self.pending_text[0] == context:
_, text, helper = self.pending_text
@@ -111,9 +113,7 @@ class Agent:
text, helper = field_text(context)
self.pending_text = (context, text, helper)
state["text_calls"].append({**helper, "field": action["label"], "value": text})
- # Text generation can take seconds. Re-check freshness after it as well.
- if text is not None and not state["browser"].fresh(page):
- raise StalePage("Page changed while generating text. Choose again.")
+ # Browser.act checks freshness immediately before input, including after text generation.
state["browser"].act(action, page, text=text)
self.pending_text = None
state["elapsed_ms"] = round((time.perf_counter() - state["started_at"]) * 1000)
diff --git a/jev_ultrafast/browser.py b/jev_ultrafast/browser.py
index 9ca3425..38e3ace 100644
--- a/jev_ultrafast/browser.py
+++ b/jev_ultrafast/browser.py
@@ -4,26 +4,14 @@ import hashlib
import json
import sys
import time
-from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
from browser_harness.admin import ensure_daemon
from browser_harness.helpers import cdp
-MARKER = """(() => {
- if (!document.documentElement) return null;
- if (!window.__jevVersion) {
- window.__jevVersion = {n: 1};
- const bump = () => window.__jevVersion.n++;
- new MutationObserver(bump).observe(document.documentElement,
- {subtree:true,childList:true,attributes:true,characterData:true});
- addEventListener('input', bump, true); addEventListener('change', bump, true);
- }
- return [performance.timeOrigin, location.href, window.__jevVersion.n, scrollX, scrollY,
- [...document.querySelectorAll('input,textarea,select')]
- .filter(e=>!['password','file','hidden'].includes(e.type))
- .map(e=>[e.value,e.checked,e.selectedIndex])];
-})()"""
-
+# Atomically read visible content and controls, preserving actual DOM node identity.
+READ_STATE = Path(__file__).with_name("snapshot.js").read_text()
+MARKER = f"(() => {{ const state={READ_STATE}; return state?.marker ?? null; }})()"
class StalePage(ValueError):
"""A decision no longer refers to the observed page."""
@@ -32,9 +20,6 @@ class StalePage(ValueError):
class Browser:
def __init__(self, url):
ensure_daemon()
- self.objects = {}
- self.document_id = None
- self.readers = ThreadPoolExecutor(max_workers=8)
self.target = cdp("Target.createTarget", url="about:blank", background=True)["targetId"]
self.session = cdp("Target.attachToTarget", targetId=self.target, flatten=True)["sessionId"]
self.call("Emulation.setDeviceMetricsOverride", width=1120, height=780, deviceScaleFactor=1, mobile=False)
@@ -57,10 +42,42 @@ class Browser:
return response.get("result", {}).get("value")
def observe(self, screenshot=True):
+ if getattr(self, "after_input", None):
+ action, self.after_input = self.after_input, None
+ # This is read-only and happens after execution was logged, even if navigation interrupts it.
+ try:
+ self.call(
+ "Runtime.evaluate",
+ expression="""(action => new Promise(resolve => {
+ const field=window.__jevFast?.nodes.get(action.node);
+ const autocomplete=action.kind==='fill' && field?.getAttribute('role')==='combobox';
+ let frames=0, stopped=false;
+ const finish=()=>{stopped=true;resolve()};
+ setTimeout(finish,autocomplete ? 200 : 50);
+ const ready=()=>{
+ if (stopped) return;
+ const ids=(field?.getAttribute('aria-controls')||field?.getAttribute('aria-owns')||'')
+ .split(/\\s+/).filter(Boolean);
+ const roots=ids.length ? ids.map(id=>document.getElementById(id)).filter(Boolean) : [document];
+ const options=roots.flatMap(root=>[...root.querySelectorAll('[role="option"]')]);
+ if (++frames>=2 && (!autocomplete || options.some(e=>{
+ const r=e.getBoundingClientRect();
+ return r.width && r.height && r.bottom>0 && r.top<innerHeight &&
+ e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});
+ }))) finish();
+ else requestAnimationFrame(ready);
+ };
+ requestAnimationFrame(ready);
+ }))(""" + json.dumps(action) + ")",
+ awaitPromise=True,
+ returnByValue=True,
+ )
+ except RuntimeError:
+ pass
for attempt in range(10):
try:
return browser_operation(
- {"operation": "observe", "session": self.session, "screenshot": screenshot, "layout": self.layout}
+ {"operation": "observe", "session": self.session, "screenshot": screenshot}
)
except StalePage:
if attempt == 9:
@@ -68,58 +85,28 @@ class Browser:
time.sleep(0.02)
raise StalePage("Page did not settle")
- def layout(self, nodes, document_id):
- """Read current geometry for AX candidates without copying scripts or the entire DOM."""
- if document_id != self.document_id or len(self.objects) > 1000:
- self.call("Runtime.releaseObjectGroup", objectGroup="jev-layout")
- self.objects.clear()
- self.document_id = document_id
-
- def resolve(backend):
- try:
- obj = self.call("DOM.resolveNode", backendNodeId=backend, objectGroup="jev-layout")
- return backend, obj["object"]["objectId"]
- except RuntimeError:
- return backend, None # Detached between AX capture and resolution.
-
- missing = {n["backendDOMNodeId"] for n in nodes} - self.objects.keys()
- self.objects.update((backend, obj) for backend, obj in self.readers.map(resolve, missing) if obj)
- backends = [n["backendDOMNodeId"] for n in nodes if n["backendDOMNodeId"] in self.objects]
- references = [{"objectId": self.objects[backend]} for backend in backends]
- if not references:
- return {}
- response = self.call(
- "Runtime.callFunctionOn",
- objectId=references[0]["objectId"],
- arguments=references,
- returnByValue=True,
- functionDeclaration="""function(...elements) { return elements.map(e => {
- if (!e.isConnected || !e.getBoundingClientRect) return null;
- const r=e.getBoundingClientRect();
- return {x:r.x, y:r.y, w:r.width, h:r.height, tag:e.tagName,
- attrs:{type:e.getAttribute('type'), readonly:e.hasAttribute('readonly'),
- placeholder:e.getAttribute('placeholder')},
- options:e.tagName==='SELECT' ? [...e.options].filter(o=>!o.disabled)
- .map(o=>({value:o.value,label:o.label,selected:o.selected})) : []};
- }); }""",
- )
- if response.get("exceptionDetails"):
- self.objects.clear()
- raise StalePage("Document changed while reading target geometry")
- return {backend: element for backend, element in zip(backends, response["result"]["value"]) if element}
-
- def fresh(self, page):
+ def fresh(self, page, action=None):
+ if action is not None and action["kind"] in {"click", "select"}:
+ node = action["node"]
+ if type(node) is not int:
+ return False
+ current = self.evaluate(
+ "(() => { const c=window.__jevFast; "
+ f"return c ? [c.pageKey(),c.guard(c.nodes.get({node}))] : null; }})()"
+ )
+ return current == [page["page_key"], page["guards"].get(str(node))]
return self.evaluate(MARKER) == page["marker"]
def act(self, action, page, text=None):
- if not self.fresh(page):
+ if not self.fresh(page, action):
raise StalePage("Page changed since this decision. Observe again.")
if action["kind"] == "wait":
time.sleep(0.1)
- return browser_operation({"operation": "act", "session": self.session, "action": action, "text": text})
+ result = browser_operation({"operation": "act", "session": self.session, "action": action, "text": text})
+ self.after_input = action if action["kind"] != "wait" else None
+ return result
def close(self):
- self.readers.shutdown(wait=True, cancel_futures=True)
if self.target:
cdp("Target.closeTarget", targetId=self.target)
self.target = None
@@ -140,6 +127,8 @@ def browser_operation(request):
def evaluate(expression):
result = call("Runtime.evaluate", expression=expression, returnByValue=True)
if result.get("exceptionDetails"):
+ if operation == "act" and request["action"]["kind"] == "select":
+ raise RuntimeError("Dropdown execution was interrupted; inspect before retrying.")
raise StalePage("Document changed during evaluation")
return result.get("result", {}).get("value")
@@ -149,42 +138,32 @@ def browser_operation(request):
if kind == "scroll":
call("Input.dispatchMouseEvent", type="mouseWheel", x=550, y=650, deltaX=0, deltaY=action["delta"])
elif kind != "wait":
- node = action["node"]
- # Resolve the observed backend node again. A replaced node fails instead of hitting a new index.
- obj = call("DOM.resolveNode", backendNodeId=node)["object"]["objectId"]
- if kind == "select":
- result = call(
- "Runtime.callFunctionOn",
- objectId=obj,
- returnByValue=True,
- functionDeclaration="""function(value) {
- if (!this.isConnected || this.disabled || this.tagName !== 'SELECT') return false;
- const option = [...this.options].find(o => o.value === value && !o.disabled);
- if (!option) return false;
- this.value = value;
- this.dispatchEvent(new Event('input', {bubbles:true}));
- this.dispatchEvent(new Event('change', {bubbles:true})); return true;
- }""",
- arguments=[{"value": action["value"]}],
- )
- if not result.get("result", {}).get("value"):
- raise RuntimeError("Dropdown changed; observe again")
- else:
- box = call("DOM.getBoxModel", backendNodeId=node)["model"]["content"]
- x, y = sum(box[0::2]) / 4, sum(box[1::2]) / 4
- hit = call("DOM.getNodeForLocation", x=round(x), y=round(y))
- hit_obj = call("DOM.resolveNode", backendNodeId=hit["backendNodeId"])["object"]["objectId"]
- valid = call(
- "Runtime.callFunctionOn",
- objectId=obj,
- returnByValue=True,
- functionDeclaration=(
- "function(hit){return this.isConnected && !this.disabled && this.contains(hit)}"
- ),
- arguments=[{"objectId": hit_obj}],
- )
- if not valid.get("result", {}).get("value"):
- raise RuntimeError("Target is covered or changed; observe again")
+ if type(action["node"]) is not int:
+ raise ValueError("Invalid observed node")
+ # Code-owned node IDs refer to actual observed elements, never model-generated selectors.
+ target = evaluate("""(action => {
+ const e=window.__jevFast?.nodes.get(action.node);
+ if (!e?.isConnected || e.matches(':disabled') || e.closest('[aria-disabled="true"],[inert]') ||
+ !e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true})) return null;
+ if (action.kind==='fill' && (e.readOnly || e.getAttribute('aria-readonly')==='true')) return null;
+ const r=e.getBoundingClientRect(), x=r.x+r.width/2, y=r.y+r.height/2;
+ if (!r.width || !r.height || x<0 || y<0 || x>=innerWidth || y>=innerHeight) return null;
+ if (!e.contains(document.elementFromPoint(x,y))) return null;
+ if (action.kind==='select') {
+ if (e.tagName!=='SELECT' || ![...e.options].some(o=>o.value===action.value &&
+ !o.disabled && !o.closest('optgroup[disabled]'))) return null;
+ e.value=action.value;
+ e.dispatchEvent(new Event('input',{bubbles:true}));
+ e.dispatchEvent(new Event('change',{bubbles:true}));
+ }
+ return {x,y};
+ })(""" + json.dumps(action) + ")")
+ if target is None:
+ if kind == "select":
+ raise RuntimeError("Dropdown execution was not confirmed; inspect before retrying.")
+ raise StalePage("Target changed or is covered. Observe again.")
+ if kind != "select":
+ x, y = target["x"], target["y"]
for event in ("mousePressed", "mouseReleased"):
call("Input.dispatchMouseEvent", type=event, x=x, y=y, button="left", clickCount=1)
if kind == "fill":
@@ -194,6 +173,7 @@ def browser_operation(request):
key="a",
code="KeyA",
modifiers=4 if sys.platform == "darwin" else 2,
+ commands=["selectAll"],
)
call(
"Input.dispatchKeyEvent",
@@ -205,127 +185,10 @@ def browser_operation(request):
call("Input.insertText", text=request["text"])
return {"executed": action["id"]}
- marker = evaluate(MARKER)
- if marker is None:
+ info = evaluate(READ_STATE)
+ if info is None:
raise StalePage("Document is navigating")
- info = evaluate("""(() => {
- const words=[], walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);
- const range=document.createRange(); let node, length=0;
- while ((node=walker.nextNode()) && length<6000) {
- const value=node.textContent.trim(), parent=node.parentElement;
- if (!value || !parent || parent.closest('script,style,noscript,template') ||
- !parent.checkVisibility({checkOpacity:true,checkVisibilityCSS:true})) continue;
- range.selectNodeContents(node); const r=range.getBoundingClientRect();
- if (r.width>0 && r.height>0 && r.bottom>0 && r.top<innerHeight && r.right>0 && r.left<innerWidth) {
- words.push(value); length+=value.length;
- }
- }
- return {url:location.href,title:document.title,w:innerWidth,h:innerHeight,text:words.join('\\n'),
- scroll:{y:scrollY,height:document.documentElement.scrollHeight}};
- })()""")
- nodes = call("Accessibility.getFullAXTree")["nodes"]
- roles = {
- "button",
- "link",
- "checkbox",
- "radio",
- "switch",
- "tab",
- "menuitem",
- "menuitemradio",
- "option",
- "gridcell",
- "combobox",
- "textbox",
- "searchbox",
- "spinbutton",
- }
- candidates = [
- n
- for n in nodes
- if not n.get("ignored") and n.get("role", {}).get("value") in roles and n.get("backendDOMNodeId")
- ]
- rendered = request["layout"](candidates, marker[0])
- actions, texts, seen = [], [], set()
- for node in nodes:
- if node.get("ignored"):
- continue
- role = node.get("role", {}).get("value", "")
- name = node.get("name", {}).get("value", "")
- if role in {"alert", "status"} and name and name not in seen:
- texts.append(name)
- seen.add(name)
- props = {p["name"]: p.get("value", {}).get("value") for p in node.get("properties", [])}
- if role not in roles or props.get("disabled") or not node.get("backendDOMNodeId"):
- continue
- backend = node["backendDOMNodeId"]
- if backend not in rendered:
- continue
- try:
- element = rendered[backend]
- x, y, w, h = (element[k] for k in ("x", "y", "w", "h"))
- tag, attrs = element["tag"], element["attrs"]
- if w <= 0 or h <= 0 or not (0 <= x + w / 2 < info["w"] and 0 <= y + h / 2 < info["h"]):
- continue
- if attrs.get("type") in {"password", "file", "hidden"}:
- continue
- base = {
- "node": backend,
- "role": role,
- "label": name or attrs.get("placeholder") or role,
- "rect": {"x": x, "y": y, "w": w, "h": h},
- }
- value = node.get("value", {}).get("value", "")
- if "checked" in props:
- base["checked"] = props["checked"]
- if "selected" in props:
- base["selected"] = props["selected"]
- if role == "combobox" and tag == "SELECT":
- options = element["options"]
- for option in options:
- if not option["selected"]:
- actions.append(
- {
- **base,
- "kind": "select",
- "value": option["value"],
- "current_value": value,
- "label": f"{base['label']} → {option['label']}",
- }
- )
- else:
- editable = (
- not attrs["readonly"]
- and not props.get("readonly")
- and (
- role in {"textbox", "searchbox", "spinbutton"}
- or (role == "combobox" and tag in {"INPUT", "TEXTAREA"})
- )
- )
- kind = "fill" if editable else "click"
- actions.append({**base, "kind": kind, "value": value})
- if kind == "fill":
- actions.append({**base, "kind": "click", "value": value, "label": f"Open {base['label']}"})
- except RuntimeError:
- continue # Non-rendered or detached AX nodes are not actionable.
- total = len(actions)
- actions = actions[:250]
- for i, action in enumerate(actions, 1):
- action["id"] = f"e{i}"
- if info["scroll"]["y"] + info["h"] < info["scroll"]["height"] - 2:
- actions.append({"id": "scroll_down", "kind": "scroll", "label": "Scroll down", "delta": 560})
- if info["scroll"]["y"] > 0:
- actions.append({"id": "scroll_up", "kind": "scroll", "label": "Scroll up", "delta": -560})
- actions.extend([{"id": "wait", "kind": "wait", "label": "Wait for the page to update"}])
- info.update(
- actions=actions,
- text=(info.get("text", "") + "\n" + "\n".join(texts))[:6000],
- omitted_actions=max(0, total - 250),
- )
- info["marker"] = marker
info["fingerprint"] = fingerprint(info)
- if evaluate(MARKER) != marker:
- raise StalePage("Page changed during observation")
if request.get("screenshot", True):
info["screenshot"] = call("Page.captureScreenshot", format="jpeg", quality=72)["data"]
return info
diff --git a/jev_ultrafast/snapshot.js b/jev_ultrafast/snapshot.js
new file mode 100644
index 0000000..cf74837
--- /dev/null
+++ b/jev_ultrafast/snapshot.js
@@ -0,0 +1,107 @@
+(() => {
+ if (!document.body) return null;
+ const cache = window.__jevFast ||= {ids:new WeakMap(), nodes:new Map(), next:1};
+ const identity = e => {
+ if (!cache.ids.has(e)) cache.ids.set(e,cache.next++);
+ const id=cache.ids.get(e); cache.nodes.set(id,e); return id;
+ };
+ for (const [id,e] of cache.nodes) if (!e.isConnected) cache.nodes.delete(id);
+ const safe = e => !['password','file','hidden'].includes(e.type);
+ const visible = e => !e.closest('[aria-hidden="true"],[inert]') &&
+ e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});
+ const name = (e,seen=new Set()) => {
+ if (!e || seen.has(e)) return '';
+ seen.add(e);
+ const referenced=(e.getAttribute('aria-labelledby')||'').split(/\s+/)
+ .map(id=>name(document.getElementById(id),seen)).filter(Boolean).join(' ');
+ return referenced || e.getAttribute('aria-label') ||
+ [...(e.labels||[])].map(l=>name(l,seen)).filter(Boolean).join(' ') ||
+ (['button','submit','reset'].includes(e.type) ? e.value : '') || e.getAttribute('alt') ||
+ (e.tagName==='INPUT' ? '' : [...e.childNodes].map(n=>n.nodeType===3 ? n.textContent :
+ n.nodeType===1 && n.getAttribute('aria-hidden')!=='true' ? name(n,seen) : '').join(' ').trim()) ||
+ e.getAttribute('title') || e.getAttribute('placeholder') || '';
+ };
+ const roles=['button','link','checkbox','radio','switch','tab','menuitem','menuitemradio',
+ 'option','gridcell','combobox','textbox','searchbox','spinbutton'];
+ const selector='a[href],button,input,textarea,select,summary,[contenteditable="true"],'+
+ roles.map(role=>'[role="'+role+'"]').join(',');
+ const role = e => {
+ const explicit=e.getAttribute('role');
+ if (roles.includes(explicit)) return explicit;
+ if (e.tagName==='BUTTON' || e.tagName==='SUMMARY') return 'button';
+ if (e.tagName==='A') return 'link';
+ if (e.tagName==='SELECT') return 'combobox';
+ if (e.tagName==='TEXTAREA' || e.isContentEditable) return 'textbox';
+ if (e.tagName==='INPUT') {
+ if (['checkbox','radio'].includes(e.type)) return e.type;
+ if (['button','submit','reset','image'].includes(e.type)) return 'button';
+ if (e.type==='search') return 'searchbox';
+ if (e.type==='number') return 'spinbutton';
+ if (['text','email','url','tel'].includes(e.type)) return 'textbox';
+ }
+ return null;
+ };
+ cache.pageKey=()=>[performance.timeOrigin,location.href,scrollX,scrollY,innerWidth,innerHeight,
+ [...document.querySelectorAll('input,textarea,select')].filter(safe)
+ .map(e=>[identity(e),e.value,e.checked,e.selectedIndex,e.disabled,e.readOnly])];
+ cache.guard=e=>{
+ if (!e?.isConnected || !visible(e)) return null;
+ const scope=e.closest('form,dialog,[role="dialog"],article,li,tr,[role="row"]') || e.parentElement;
+ return [identity(e),role(e),name(e),e.value??null,e.checked??null,e.selectedIndex??null,
+ e.readOnly??null,e.matches(':disabled'),e.getAttribute('aria-disabled'),
+ e.getAttribute('aria-expanded'),e.getAttribute('aria-checked'),e.getAttribute('aria-selected'),
+ e.getAttribute('href'),scope?.innerText?.slice(0,6000)||''];
+ };
+ const actions=[];
+ for (const e of document.querySelectorAll(selector)) {
+ if (!safe(e) || !visible(e) || e.matches(':disabled') || e.closest('[aria-disabled="true"]')) continue;
+ const r=e.getBoundingClientRect(), x=r.x+r.width/2, y=r.y+r.height/2, rname=role(e);
+ if (!rname || r.width<=0 || r.height<=0 || x<0 || y<0 || x>=innerWidth || y>=innerHeight) continue;
+ if (rname==='gridcell' && e.querySelector('button,[role="button"]')) continue;
+ const base={node:identity(e),role:rname,label:name(e)||rname,
+ rect:{x:r.x,y:r.y,w:r.width,h:r.height}};
+ for (const key of ['checked','selected','expanded']) {
+ const value=e.getAttribute('aria-'+key);
+ if (value!==null) base[key]=value;
+ }
+ if (['checkbox','radio'].includes(e.type)) base.checked=String(e.checked);
+ if (e.tagName==='SELECT') {
+ for (const o of e.options) if (!o.selected && !o.disabled && !o.closest('optgroup[disabled]'))
+ actions.push({...base,kind:'select',value:o.value,
+ current_value:[...e.selectedOptions].map(o=>o.label).join(', '),label:base.label+' → '+o.label});
+ } else {
+ const editable=!e.readOnly && e.getAttribute('aria-readonly')!=='true' &&
+ (['textbox','searchbox','spinbutton'].includes(rname) ||
+ (rname==='combobox' && ['INPUT','TEXTAREA'].includes(e.tagName)));
+ const value='value' in e ? String(e.value) :
+ e.isContentEditable || rname==='combobox' ? e.innerText.trim() : '';
+ actions.push({...base,kind:editable?'fill':'click',value});
+ if (editable) actions.push({...base,kind:'click',value,label:'Open '+base.label});
+ }
+ }
+ const words=[], walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);
+ const range=document.createRange(); let node,length=0;
+ while ((node=walker.nextNode()) && length<6000) {
+ const value=node.textContent.trim(), parent=node.parentElement;
+ if (!value || !parent || parent.closest('script,style,noscript,template') || !visible(parent)) continue;
+ range.selectNodeContents(node); const r=range.getBoundingClientRect();
+ if (r.width>0 && r.height>0 && r.bottom>0 && r.top<innerHeight && r.right>0 && r.left<innerWidth) {
+ words.push(value); length+=value.length;
+ }
+ }
+ const text=words.join('\n').slice(0,6000), height=document.documentElement.scrollHeight;
+ const page_key=cache.pageKey(), guards={};
+ for (const a of actions) if (!(a.node in guards)) guards[a.node]=cache.guard(cache.nodes.get(a.node));
+ // Compare meaning and identity. Geometry is always resolved and hit-tested just before input.
+ const semantics=actions.map(({rect,...action})=>action);
+ const marker=[performance.timeOrigin,location.href,scrollX,scrollY,innerWidth,innerHeight,
+ document.title,text,semantics,page_key[6]];
+ const omitted_actions=Math.max(0,actions.length-250);
+ actions.splice(250);
+ actions.forEach((a,i)=>a.id='e'+(i+1));
+ if (scrollY+innerHeight<height-2) actions.push({id:'scroll_down',kind:'scroll',label:'Scroll down',delta:560});
+ if (scrollY>0) actions.push({id:'scroll_up',kind:'scroll',label:'Scroll up',delta:-560});
+ actions.push({id:'wait',kind:'wait',label:'Wait for the page to update'});
+ return {url:location.href,title:document.title,w:innerWidth,h:innerHeight,text,
+ scroll:{y:scrollY,height},actions,marker,page_key,guards,omitted_actions};
+})()
diff --git a/scripts/check_guards.py b/scripts/check_guards.py
new file mode 100644
index 0000000..a9da23b
--- /dev/null
+++ b/scripts/check_guards.py
@@ -0,0 +1,137 @@
+"""Local-browser freshness/execution regressions. No model calls or external websites."""
+
+from urllib.parse import quote
+
+from jev_ultrafast.browser import Browser, StalePage
+
+HTML = """<!doctype html><title>Guard checks</title>
+<style>body{margin:30px}button{width:180px;height:50px}#outside{position:absolute;top:3000px}</style>
+<p id="context">Cart total: $10</p>
+<button id="target" onclick="window.clicks=(window.clicks||0)+1">Continue</button>
+<label>City<input id="field" value="Zurich"></label>
+<label><input id="toggle" type="checkbox">Refundable</label>
+<select aria-label="Category"><option>All</option><option>Design</option></select>
+<p id="outside">Unrelated offscreen text</p>"""
+
+
+def main():
+ browser = Browser("data:text/html," + quote(HTML))
+ passed = []
+ try:
+ page = browser.observe(screenshot=False)
+ action = next(a for a in page["actions"] if a["label"] == "Continue")
+ browser.evaluate("document.querySelector('#target').style.transform='translateX(200px)'")
+ assert browser.fresh(page), "Movement should use fresh geometry, not another model call"
+ browser.act(action, page)
+ assert browser.evaluate("window.clicks") == 1
+ passed.append("moving target clicked at its current location")
+
+ browser.evaluate("document.querySelector('#outside').textContent='Updated outside the viewport'")
+ assert browser.fresh(page)
+ passed.append("unrelated offscreen text does not invalidate")
+
+ mutations = {
+ "visible context": "document.querySelector('#context').textContent='Cart total: $100'",
+ "accessible label": "document.querySelector('#target').setAttribute('aria-label','Delete account')",
+ "field property": "document.querySelector('#field').value='London'",
+ "checkbox property": "document.querySelector('#toggle').checked=true",
+ "disabled target": "document.querySelector('#target').disabled=true",
+ "read-only field": "document.querySelector('#field').readOnly=true",
+ "hidden target": "document.querySelector('#target').style.display='none'",
+ "replaced node": "document.querySelector('#target').outerHTML=document.querySelector('#target').outerHTML",
+ "dropdown option": "document.querySelector('select').options[1].text='Coastal'",
+ }
+ for label, expression in mutations.items():
+ browser.evaluate("document.querySelector('#target').style.display='block'; "
+ "document.querySelector('#target').disabled=false")
+ page = browser.observe(screenshot=False)
+ browser.evaluate(expression)
+ assert not browser.fresh(page), label
+ passed.append(label + " invalidates")
+
+ browser.evaluate("document.querySelector('#target').disabled=false; "
+ "document.querySelector('#target').style.display='block'")
+ page = browser.observe(screenshot=False)
+ action = next(a for a in page["actions"] if a["label"] == "Delete account")
+ # A textless overlay does not alter the model's semantic state, but must block a click.
+ browser.evaluate("const cover=document.createElement('div'); "
+ "cover.style.cssText='position:fixed;inset:0;z-index:9999;background:white'; "
+ "document.body.append(cover)")
+ assert browser.fresh(page)
+ try:
+ browser.act(action, page)
+ except (RuntimeError, StalePage):
+ pass
+ else:
+ raise AssertionError("Covered target was clicked")
+ assert browser.evaluate("window.clicks") == 1
+ passed.append("overlay blocked before input")
+
+ browser.evaluate("document.body.innerHTML=" + repr("""
+ <form><p id="price">Total $10</p>
+ <button type="button" id="buy">Buy</button>
+ <label>Search <input id="query" role="combobox" aria-controls="suggestions"></label>
+ <div role="listbox" id="suggestions"></div>
+ <label><input id="check" type="checkbox">Enabled</label>
+ <label><input id="radio" type="radio">Choice</label>
+ <input id="readonly" aria-label="Read only" readonly>
+ <input id="secret" type="password" value="never expose this">
+ <button id="off" disabled>Disabled</button>
+ <select id="category" aria-label="Category">
+ <option>All</option><option>Design</option><option disabled>Unavailable</option>
+ </select></form><aside id="unrelated">News</aside>
+ """))
+ page = browser.observe(screenshot=False)
+ buy = next(a for a in page["actions"] if a["label"] == "Buy")
+ browser.evaluate("document.querySelector('#unrelated').textContent='New unrelated news'")
+ assert browser.fresh(page, buy)
+ assert not browser.fresh(page)
+ passed.append("click guard accepts unrelated visible updates; terminal guard rejects them")
+ for label, expression in {
+ "nearby price": "document.querySelector('#price').textContent='Total $100'",
+ "form value": "document.querySelector('#query').value='changed'",
+ "form toggle": "document.querySelector('#check').checked=true",
+ "target replacement": "document.querySelector('#buy').outerHTML=document.querySelector('#buy').outerHTML",
+ }.items():
+ page = browser.observe(screenshot=False)
+ buy = next(a for a in page["actions"] if a["label"] == "Buy")
+ browser.evaluate(expression)
+ assert not browser.fresh(page, buy), label
+ passed.append(label + " invalidates action-specific guard")
+
+ page = browser.observe(screenshot=False)
+ actions = page["actions"]
+ for role in ("checkbox", "radio"):
+ assert {a["kind"] for a in actions if a.get("role") == role} == {"click"}
+ assert {a["kind"] for a in actions if a["label"] == "Read only"} == {"click"}
+ assert not any(a["label"] == "Disabled" or a.get("value") == "never expose this" for a in actions)
+ assert [a["value"] for a in actions if a["kind"] == "select"] == ["Design"]
+ passed.append("native controls expose only supported operations and safe values")
+
+ select = next(a for a in actions if a["kind"] == "select")
+ browser.act(select, page)
+ assert browser.evaluate("document.querySelector('#category').value") == "Design"
+ passed.append("native dropdown selects an observed option")
+
+ browser.evaluate("document.querySelector('#query').addEventListener('input',()=>setTimeout(()=>{"
+ "document.querySelector('#suggestions').innerHTML='<div role=option>Generated</div>'"
+ "},60))")
+ page = browser.observe(screenshot=False)
+ field = next(a for a in page["actions"] if a["kind"] == "fill")
+ browser.act(field, page, text="Generated")
+ page = browser.observe(screenshot=False)
+ value = browser.evaluate("document.querySelector('#query').value")
+ assert value == "Generated", repr(value)
+ assert any(a.get("role") == "option" for a in page["actions"])
+ passed.append("real text input waits for asynchronous combobox suggestions")
+ browser.call("Page.navigate", url="about:blank")
+ assert not browser.fresh(page, field)
+ passed.append("navigation invalidates the old document")
+ finally:
+ browser.close()
+ print("\n".join(passed))
+ print(f"PASS: {len(passed)} browser guard checks; no model calls")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/measure_flights.py b/scripts/measure_flights.py
index dc5cde6..0f40015 100644
--- a/scripts/measure_flights.py
+++ b/scripts/measure_flights.py
@@ -3,6 +3,7 @@
import argparse
import hashlib
import json
+import os
import sys
import time
from collections import defaultdict
@@ -21,7 +22,11 @@ sys.path.append(str(Path(__file__).resolve().parents[1]))
from examples.flights import GOALS, URL, verify # noqa: E402
folder = Path(args.output)
-folder.mkdir(parents=True, exist_ok=True)
+folder.mkdir(parents=True, exist_ok=False)
+source_hashes = {
+ p.name: hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in (source / "jev_ultrafast").iterdir() if p.suffix in {".py", ".js"}
+}
raw = browser_module.cdp
calls = defaultdict(list)
@@ -52,10 +57,13 @@ finally:
state["verification"] = verify(final)
state["error"] = error
state["cdp"] = measured_calls
- state["source_hashes"] = {
- p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (source / "jev_ultrafast").glob("*.py")
- }
+ state["source_hashes"] = source_hashes
state["task_hash"] = hashlib.sha256(json.dumps([URL, GOALS]).encode()).hexdigest()
+ state["configuration"] = {
+ key: os.environ.get(key)
+ for key in ("TYPESAFE_MODEL", "TEXT_MODEL", "TEXT_MODEL_BASE_URL", "TEXT_MODEL_REASONING")
+ }
+ state["browser_version"] = agent.browser.call("Browser.getVersion")["product"]
state["final_page"] = final
(folder / "state.json").write_text(json.dumps(state, indent=2))
agent.close()
diff --git a/scripts/record_flights.py b/scripts/record_flights.py
index 0c31de4..2a8c5de 100644
--- a/scripts/record_flights.py
+++ b/scripts/record_flights.py
@@ -1,6 +1,7 @@
"""A measured live run with continuous CDP screencast; original timestamps retained."""
import base64
+import hashlib
import json
import sys
import threading
@@ -14,7 +15,12 @@ from examples.flights import GOALS, URL, verify # noqa: E402
from jev_ultrafast import Agent # noqa: E402
folder = Path(sys.argv[1] if len(sys.argv) > 1 else "artifacts/flights/recorded")
-folder.mkdir(parents=True, exist_ok=True)
+folder.mkdir(parents=True, exist_ok=False)
+source_hashes = {
+ p.name: hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in (Path(__file__).resolve().parents[1] / "jev_ultrafast").iterdir()
+ if p.suffix in {".py", ".js"}
+}
agent = Agent(URL, GOALS)
(folder / "frames").mkdir(exist_ok=True)
(folder / "frames" / "000000.jpg").write_bytes(
@@ -57,7 +63,9 @@ finally:
worker.join(timeout=3)
agent.browser.call("Page.stopScreencast")
state = agent.snapshot()
- state["verification"] = verify(state["page"])
+ state["final_page"] = agent.browser.observe(screenshot=False)
+ state["verification"] = verify(state["final_page"])
+ state["source_hashes"] = source_hashes
state["recording_errors"] = errors
(folder / "state.json").write_text(json.dumps(state, indent=2))
(folder / "session.json").write_text(json.dumps({"target": agent.browser.target, "session": agent.browser.session}))
diff --git a/scripts/render_demo.py b/scripts/render_demo.py
index e48b4c8..463de11 100644
--- a/scripts/render_demo.py
+++ b/scripts/render_demo.py
@@ -1,5 +1,6 @@
"""Render the actual Google Flights screencast at 1x, including every loading wait."""
+import argparse
import json
import statistics
import subprocess
@@ -8,14 +9,17 @@ from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parents[1]
-source = ROOT / "artifacts/dynamic/flights-final"
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument("source", type=Path, help="Exact verified recording directory")
+args = parser.parse_args()
+source = args.source.resolve()
state = json.loads((source / "state.json").read_text())
assert state["verification"]["passed"] and not state["recording_errors"]
frames = [(0, Image.open(source / "frames/000000.jpg").convert("RGB"))]
frames += sorted((int(p.stem), Image.open(p).convert("RGB")) for p in (source / "screencast").glob("*.jpg"))
end = state["elapsed_ms"]
-folder = ROOT / "artifacts/dynamic/video-frames"
-folder.mkdir(parents=True, exist_ok=True)
+folder = source / "video-frames"
+folder.mkdir(parents=True, exist_ok=False)
font_path = "/System/Library/Fonts/Supplemental/Arial.ttf"
font_bold = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"
@@ -36,8 +40,8 @@ steps = [
("20 September", "Done. Search"),
("Search flights", "Search"),
]
-for i in range(round((end + 2750) * 30 / 1000)):
- t = min(end, max(0, round(i * 1000 / 30) - 750))
+for i in range(round((end + 500) * 30 / 1000)):
+ t = min(end, round(i * 1000 / 30))
screenshot = next(im for ts, im in reversed(frames) if ts <= t)
canvas = Image.new("RGB", (1536, 1000), "#f3f4ec")
d = ImageDraw.Draw(canvas)
@@ -85,7 +89,8 @@ for i in range(round((end + 2750) * 30 / 1000)):
d.line((37, 960, 37 + (1498 - 37) * t / end, 960), fill=green, width=3)
d.text(
(37, 973),
- "Operation + index by Jev. Text by Gemini Flash Lite. Original timing; waits included.",
+ f"Operation + index by Jev. Text by {state['text_calls'][0]['model'].split('/')[-1]}. "
+ "Original timing; waits included.",
font=font(14),
fill=muted,
)
@@ -130,4 +135,4 @@ subprocess.run(
],
check=True,
)
-print("Rendered", len(frames), "source frames at original timing:", end, "ms, plus 750ms intro and 2000ms end hold.")
+print("Rendered", len(frames), "source frames at original timing:", end, "ms, plus a 500ms end hold.")
diff --git a/tests/test_agent.py b/tests/test_agent.py
index 43a10b9..41fc390 100644
--- a/tests/test_agent.py
+++ b/tests/test_agent.py
@@ -189,20 +189,20 @@ def test_stale_decision_is_consumed_before_any_mutation(runner):
def test_generated_text_reused_only_for_identical_retry_context(runner, monkeypatch):
helper = Mock(return_value=("book", {"model": "test", "latency_ms": 10}))
monkeypatch.setattr(loop, "field_text", helper)
- runner.state["browser"].fresh.side_effect = [True, False, True, True]
+ runner.state["browser"].act.side_effect = [StalePage("Changed before input"), None]
with pytest.raises(StalePage):
runner.command("act", {"fingerprint": runner.state["page"]["fingerprint"]})
runner.state["decision"] = decision()
runner.command("act", {"fingerprint": runner.state["page"]["fingerprint"]})
assert helper.call_count == 1
- runner.state["browser"].act.assert_called_once()
+ assert runner.state["browser"].act.call_count == 2 # The first call rejects before any browser input.
assert runner.pending_text is None
def test_changed_field_context_does_not_reuse_generated_text(runner, monkeypatch):
helper = Mock(return_value=("book", {"model": "test", "latency_ms": 10}))
monkeypatch.setattr(loop, "field_text", helper)
- runner.state["browser"].fresh.side_effect = [True, False, True, True]
+ runner.state["browser"].act.side_effect = [StalePage("Changed before input"), None]
with pytest.raises(StalePage):
runner.command("act", {"fingerprint": runner.state["page"]["fingerprint"]})
runner.state["page"]["text"] = "Different page context"
@@ -227,44 +227,44 @@ def test_stale_observation_preserves_executed_action(runner):
runner.state["browser"].act.assert_called_once()
- "role,readonly,kind",
- [
- ("checkbox", False, "click"),
- ("radio", False, "click"),
- ("button", False, "click"),
- ("combobox", False, "fill"),
- ("textbox", False, "fill"),
- ("textbox", True, "click"),
- ],
-)
-def test_checkbox_is_not_a_text_field(monkeypatch, role, readonly, kind):
+def test_observation_is_one_atomic_browser_read(monkeypatch):
import jev_ultrafast.browser as browser
- def cdp(method, **kwargs):
- if method == "Runtime.evaluate":
- value = (
- [1, "url", 1]
- if kwargs["expression"] == browser.MARKER
- else {"url": "url", "title": "test", "w": 100, "h": 100, "scroll": {"y": 0, "height": 100}}
- )
- return {"result": {"value": value}}
- if method == "Accessibility.getFullAXTree":
- return {"nodes": [{"backendDOMNodeId": 1, "role": {"value": role}, "name": {"value": "Field"}}]}
- raise AssertionError(method)
+ p = page()
+ cdp = Mock(return_value={"result": {"value": p}})
+ monkeypatch.setattr(browser, "cdp", cdp)
+ actual = browser_operation({"operation": "observe", "session": "test", "screenshot": False})
+ assert actual["actions"] == p["actions"]
+ assert cdp.call_count == 1
+ assert cdp.call_args.args[0] == "Runtime.evaluate"
+
+
+def test_executor_rejects_a_stale_page_before_browser_input(monkeypatch):
+ import jev_ultrafast.browser as browser
+ b = browser.Browser.__new__(browser.Browser)
+ b.fresh = Mock(return_value=False)
+ operation = Mock()
+ monkeypatch.setattr(browser, "browser_operation", operation)
+ with pytest.raises(StalePage):
+ b.act(page()["actions"][0], page(), "book")
+ operation.assert_not_called()
+
+
[email protected]("response", [{"exceptionDetails": {}}, {"result": {}}])
+def test_interrupted_dropdown_mutation_cannot_be_retried_as_stale(monkeypatch, response):
+ import jev_ultrafast.browser as browser
+
+ # A navigation can destroy the evaluation result after the change event already fired.
+ if "exceptionDetails" in response:
+ response["exceptionDetails"] = {"text": "Execution context destroyed"}
+ cdp = Mock(return_value=response)
monkeypatch.setattr(browser, "cdp", cdp)
- p = browser_operation(
- {
- "operation": "observe",
- "session": "test",
- "screenshot": False,
- "layout": lambda *_: {
- 1: {"x": 0, "y": 0, "w": 20, "h": 20, "tag": "INPUT", "attrs": {"readonly": readonly}, "options": []}
- },
- }
- )
- assert p["actions"][0]["kind"] == kind
+ with pytest.raises(RuntimeError, match="Dropdown execution"):
+ browser_operation({"operation": "act", "session": "test", "action": {
+ "id": "e1", "kind": "select", "node": 1, "value": "Design",
+ }})
+ assert cdp.call_count == 1
def test_fingerprint_tracks_values_and_identity_not_screenshots():