Skip to content

armgit / cua

Public Imported from GitHub
0

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

test(cua-driver): make jev-use timing phase-correct (#4052)

Kevin Rajan46a75b1b896d
diff --git a/libs/cua-driver/examples/jev-use/README.md b/libs/cua-driver/examples/jev-use/README.md
index c72a3184be..9729491e33 100644
--- a/libs/cua-driver/examples/jev-use/README.md
+++ b/libs/cua-driver/examples/jev-use/README.md
@@ -425,9 +425,16 @@ resets the fixture and prepares/navigates the browser; it is not side-effect-fre
The managed verifier bounds each child runner to 180 seconds. Provider SDKs may
retry network requests, so action and process limits do not guarantee a billing
-cap. `decision_ms` includes the browser snapshot as well as the provider call.
-Logs contain choices and timings, not a complete request, token-usage, or billing
-audit. The fixture tests integration rather than general agent capability.
+cap. `decision_ms` remains the backward-compatible aggregate from the start of
+the fresh semantic snapshot through validated provider choice. Step events also
+report `semantic_observe_ms`, `visual_observe_ms`,
+`candidate_build_ms`, and `provider_decision_ms`; `action_ms` remains
+separate and `total_step_ms` measures through the end of the action (or a
+reobserve decision). Lazy visual parsing is timed only when it actually runs.
+The small residual between the aggregate and named phases is local
+validation/bookkeeping, not another model or Driver call. Logs contain choices
+and timings, not a complete request, token-usage, or billing audit. The fixture
+tests integration rather than general agent capability.
## MCP, CLI, and perception boundaries
diff --git a/libs/cua-driver/examples/jev-use/python/run.py b/libs/cua-driver/examples/jev-use/python/run.py
index 9aae4e65ff..b31ba1ecf8 100644
--- a/libs/cua-driver/examples/jev-use/python/run.py
+++ b/libs/cua-driver/examples/jev-use/python/run.py
@@ -236,6 +236,7 @@ async def task_candidates_for_step(
*,
visual_mode: str = "auto",
visual_delivery: VisualDelivery = "background",
+ phase_timings: dict[str, float] | None = None,
) -> tuple[list[Candidate], TaskSources, dict[str, Any]]:
"""Build one step's sources and candidates, parsing visual regions only when useful.
@@ -246,6 +247,7 @@ async def task_candidates_for_step(
# Whether a control missing from the page structure can still be found
# through a capture-bound visual region; reported in the task state.
visual_path = capture_bound_click and visual_mode != "off"
+ candidate_build_started = time.perf_counter()
sources = fixture_sources(
snapshot,
None,
@@ -254,14 +256,32 @@ async def task_candidates_for_step(
visual_path=visual_path,
)
candidates = task.candidates(sources)
+ candidate_build_ms = (time.perf_counter() - candidate_build_started) * 1000
+ visual_observe_ms = 0.0
+
+ def record_phase_timings() -> None:
+ if phase_timings is not None:
+ phase_timings.update(
+ {
+ "visual_observe_ms": round(visual_observe_ms, 2),
+ "candidate_build_ms": round(candidate_build_ms, 2),
+ }
+ )
+
if visual_mode == "off":
+ record_phase_timings()
return candidates, sources, visual_status("skipped", reason="disabled")
if visual_mode == "auto" and has_executable_candidate(candidates):
+ record_phase_timings()
return candidates, sources, visual_status("skipped", reason="page_structure_candidate")
+
+ visual_started = time.perf_counter()
visual, record = await observe_visual(
driver, pid, window_id, available_tools, capture_bound_click
)
+ visual_observe_ms = (time.perf_counter() - visual_started) * 1000
if visual is not None:
+ candidate_build_started = time.perf_counter()
sources = fixture_sources(
snapshot,
visual,
@@ -270,6 +290,8 @@ async def task_candidates_for_step(
visual_path=visual_path,
)
candidates = task.candidates(sources)
+ candidate_build_ms += (time.perf_counter() - candidate_build_started) * 1000
+ record_phase_timings()
return candidates, sources, record
@@ -322,6 +344,24 @@ def write_event(log_path: Path | None, event: dict[str, Any]) -> None:
stream.write(line + "\n")
+def decision_timing_fields(
+ *,
+ decision_ms: float,
+ semantic_observe_ms: float,
+ visual_observe_ms: float,
+ candidate_build_ms: float,
+ provider_decision_ms: float,
+) -> dict[str, float]:
+ """Stable phase fields for one observe → decide boundary."""
+ return {
+ "decision_ms": decision_ms,
+ "semantic_observe_ms": semantic_observe_ms,
+ "visual_observe_ms": visual_observe_ms,
+ "candidate_build_ms": candidate_build_ms,
+ "provider_decision_ms": provider_decision_ms,
+ }
+
+
async def run(args: argparse.Namespace) -> str:
token = args.token or f"jev-{uuid.uuid4().hex[:10]}"
task: Task = FixtureFormTask(token, args.fixture_url, args.max_steps)
@@ -368,6 +408,7 @@ async def run(args: argparse.Namespace) -> str:
return current
started = time.perf_counter()
+ phase_started = time.perf_counter()
snapshot = await driver.call(
"get_browser_state",
{
@@ -376,6 +417,8 @@ async def run(args: argparse.Namespace) -> str:
"snapshot_format": "semantic_v2",
},
)
+ semantic_observe_ms = round((time.perf_counter() - phase_started) * 1000, 2)
+ candidate_phase: dict[str, float] = {}
candidates, sources, visual_record = await task_candidates_for_step(
driver,
task,
@@ -386,6 +429,7 @@ async def run(args: argparse.Namespace) -> str:
capture_bound_click,
visual_mode=args.visual_observation,
visual_delivery=visual_delivery,
+ phase_timings=candidate_phase,
)
if not candidates:
write_event(
@@ -395,6 +439,7 @@ async def run(args: argparse.Namespace) -> str:
return "abstained"
visual = sources.visual.observation if sources.visual is not None else None
+ provider_started = time.perf_counter()
if args.provider == "mock":
choice, confidence, probabilities = choose_mock_for_task(
task, sources, candidates, history
@@ -403,6 +448,9 @@ async def run(args: argparse.Namespace) -> str:
choice, confidence, probabilities = await asyncio.to_thread(
choose_live_for_task, task, sources, candidates, history
)
+ provider_decision_ms = round(
+ (time.perf_counter() - provider_started) * 1000, 2
+ )
if choice is None:
return "abstained"
candidate = validate_choice(
@@ -411,6 +459,13 @@ async def run(args: argparse.Namespace) -> str:
current_capture_id=visual.capture_id if visual else None,
)
decision_ms = round((time.perf_counter() - started) * 1000, 2)
+ timing = decision_timing_fields(
+ decision_ms=decision_ms,
+ semantic_observe_ms=semantic_observe_ms,
+ visual_observe_ms=candidate_phase.get("visual_observe_ms", 0.0),
+ candidate_build_ms=candidate_phase.get("candidate_build_ms", 0.0),
+ provider_decision_ms=provider_decision_ms,
+ )
if candidate.id == "reobserve":
event = {
@@ -419,8 +474,9 @@ async def run(args: argparse.Namespace) -> str:
"candidate": candidate.id,
"confidence": confidence,
"probabilities": probabilities,
- "decision_ms": decision_ms,
+ **timing,
"action_ms": 0.0,
+ "total_step_ms": round((time.perf_counter() - started) * 1000, 2),
"dry_run": args.dry_run,
"tool": None,
"visual": visual_record,
@@ -460,8 +516,9 @@ async def run(args: argparse.Namespace) -> str:
"candidate": candidate.id,
"confidence": confidence,
"probabilities": probabilities,
- "decision_ms": decision_ms,
+ **timing,
"action_ms": round((time.perf_counter() - action_started) * 1000, 2),
+ "total_step_ms": round((time.perf_counter() - started) * 1000, 2),
"dry_run": args.dry_run,
"tool": candidate.tool,
"delivery_mode": "background",
@@ -498,8 +555,9 @@ async def run(args: argparse.Namespace) -> str:
"candidate": candidate.id,
"confidence": confidence,
"probabilities": probabilities,
- "decision_ms": decision_ms,
+ **timing,
"action_ms": action_ms,
+ "total_step_ms": round((time.perf_counter() - started) * 1000, 2),
"dry_run": args.dry_run,
"tool": candidate.tool,
"delivery_mode": candidate.arguments.get("delivery_mode"),
diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_run_timing.py b/libs/cua-driver/examples/jev-use/python/tests/test_run_timing.py
new file mode 100644
index 0000000000..a2e179a2d0
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/tests/test_run_timing.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from run import decision_timing_fields
+
+
+class DecisionTimingTest(unittest.TestCase):
+ def test_step_timing_field_names_and_values_are_stable(self) -> None:
+ fields = decision_timing_fields(
+ decision_ms=14.5,
+ semantic_observe_ms=4.0,
+ visual_observe_ms=3.0,
+ candidate_build_ms=2.0,
+ provider_decision_ms=5.0,
+ )
+ self.assertEqual(
+ fields,
+ {
+ "decision_ms": 14.5,
+ "semantic_observe_ms": 4.0,
+ "visual_observe_ms": 3.0,
+ "candidate_build_ms": 2.0,
+ "provider_decision_ms": 5.0,
+ },
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/examples/jev-use/typescript/run.ts b/libs/cua-driver/examples/jev-use/typescript/run.ts
index 52e7d868b8..a567d791b5 100644
--- a/libs/cua-driver/examples/jev-use/typescript/run.ts
+++ b/libs/cua-driver/examples/jev-use/typescript/run.ts
@@ -174,6 +174,11 @@ export type VisualStatus = {
region_count?: number;
};
+export type CandidatePhaseTiming = {
+ visualObserveMs: number;
+ candidateBuildMs: number;
+};
+
/**
* Build the redacted per-step visual record written to the JSONL log. It never
* contains screenshots, screenshot references, region text, or secrets.
@@ -271,22 +276,37 @@ export async function taskCandidatesForStep(
captureBoundClick: boolean,
visualMode: VisualMode = 'auto',
visualDelivery: VisualDelivery = 'background'
-): Promise<{ candidates: Candidate[]; sources: TaskSources; status: VisualStatus }> {
+): Promise<{
+ candidates: Candidate[];
+ sources: TaskSources;
+ status: VisualStatus;
+ timing: CandidatePhaseTiming;
+}> {
// Whether a control missing from the page structure can still be found
// through a capture-bound visual region; reported in the task state.
const visualPath = captureBoundClick && visualMode !== 'off';
+ let candidateBuildStarted = performance.now();
let sources = fixtureSources(snapshot, undefined, captureBoundClick, visualDelivery, visualPath);
let candidates = task.candidates(sources);
+ let candidateBuildMs = performance.now() - candidateBuildStarted;
+ let visualObserveMs = 0;
if (visualMode === 'off') {
- return { candidates, sources, status: visualStatus('skipped', undefined, undefined, 'disabled') };
+ return {
+ candidates,
+ sources,
+ status: visualStatus('skipped', undefined, undefined, 'disabled'),
+ timing: { visualObserveMs, candidateBuildMs },
+ };
}
if (visualMode === 'auto' && hasExecutableCandidate(candidates)) {
return {
candidates,
sources,
status: visualStatus('skipped', undefined, undefined, 'page_structure_candidate'),
+ timing: { visualObserveMs, candidateBuildMs },
};
}
+ const visualStarted = performance.now();
const { visual, status } = await observeVisual(
driver,
pid,
@@ -294,11 +314,14 @@ export async function taskCandidatesForStep(
availableTools,
captureBoundClick
);
+ visualObserveMs = performance.now() - visualStarted;
if (visual) {
+ candidateBuildStarted = performance.now();
sources = fixtureSources(snapshot, visual, captureBoundClick, visualDelivery, visualPath);
candidates = task.candidates(sources);
+ candidateBuildMs += performance.now() - candidateBuildStarted;
}
- return { candidates, sources, status };
+ return { candidates, sources, status, timing: { visualObserveMs, candidateBuildMs } };
}
/** Build one step's fixture-task candidates; see taskCandidatesForStep. */
@@ -350,6 +373,22 @@ async function writeEvent(path: string | undefined, event: Record<string, unknow
if (path) await appendFile(path, `${line}\n`, 'utf8');
}
+export function decisionTimingFields(args: {
+ decisionMs: number;
+ semanticObserveMs: number;
+ visualObserveMs: number;
+ candidateBuildMs: number;
+ providerDecisionMs: number;
+}): Record<string, number> {
+ return {
+ decision_ms: args.decisionMs,
+ semantic_observe_ms: Math.round(args.semanticObserveMs * 100) / 100,
+ visual_observe_ms: Math.round(args.visualObserveMs * 100) / 100,
+ candidate_build_ms: Math.round(args.candidateBuildMs * 100) / 100,
+ provider_decision_ms: Math.round(args.providerDecisionMs * 100) / 100,
+ };
+}
+
async function run(args: Arguments): Promise<Outcome> {
const token = args.token ?? `jev-${randomUUID().replaceAll('-', '').slice(0, 10)}`;
const task: Task = new FixtureFormTask(token, args.fixtureUrl, args.maxSteps);
@@ -398,15 +437,18 @@ async function run(args: Arguments): Promise<Outcome> {
}
const decisionStarted = performance.now();
+ const semanticStarted = performance.now();
const snapshot = (await driver.call('get_browser_state', {
target_id: targetId,
tab_id: tabId,
snapshot_format: 'semantic_v2',
})) as BrowserSnapshot;
+ const semanticObserveMs = performance.now() - semanticStarted;
const {
candidates,
sources,
status: visualRecord,
+ timing: candidateTiming,
} = await taskCandidatesForStep(
driver,
task,
@@ -428,13 +470,22 @@ async function run(args: Arguments): Promise<Outcome> {
return 'abstained';
}
const visual = sources.visual?.observation;
+ const providerStarted = performance.now();
const answer =
args.provider === 'mock'
? chooseMockForTask(task, sources, candidates, history)
: await chooseLiveForTask(task, sources, candidates, history);
+ const providerDecisionMs = performance.now() - providerStarted;
if (!answer.choice) return 'abstained';
const candidate = validateChoice(answer.choice, candidates, visual?.captureId);
const decisionMs = Math.round((performance.now() - decisionStarted) * 100) / 100;
+ const timing = decisionTimingFields({
+ decisionMs,
+ semanticObserveMs,
+ visualObserveMs: candidateTiming.visualObserveMs,
+ candidateBuildMs: candidateTiming.candidateBuildMs,
+ providerDecisionMs,
+ });
if (candidate.id === 'reobserve') {
const event = {
@@ -443,8 +494,9 @@ async function run(args: Arguments): Promise<Outcome> {
candidate: candidate.id,
confidence: answer.confidence,
probabilities: answer.probabilities,
- decision_ms: decisionMs,
+ ...timing,
action_ms: 0,
+ total_step_ms: Math.round((performance.now() - decisionStarted) * 100) / 100,
dry_run: args.dryRun,
tool: null,
visual: visualRecord,
@@ -484,8 +536,9 @@ async function run(args: Arguments): Promise<Outcome> {
candidate: candidate.id,
confidence: answer.confidence,
probabilities: answer.probabilities,
- decision_ms: decisionMs,
+ ...timing,
action_ms: Math.round((performance.now() - actionStarted) * 100) / 100,
+ total_step_ms: Math.round((performance.now() - decisionStarted) * 100) / 100,
dry_run: args.dryRun,
tool: candidate.tool,
delivery_mode: 'background',
@@ -516,8 +569,9 @@ async function run(args: Arguments): Promise<Outcome> {
candidate: candidate.id,
confidence: answer.confidence,
probabilities: answer.probabilities,
- decision_ms: decisionMs,
+ ...timing,
action_ms: actionMs,
+ total_step_ms: Math.round((performance.now() - decisionStarted) * 100) / 100,
dry_run: args.dryRun,
tool: candidate.tool,
delivery_mode: candidate.arguments.delivery_mode ?? null,
diff --git a/libs/cua-driver/examples/jev-use/typescript/run_timing.test.ts b/libs/cua-driver/examples/jev-use/typescript/run_timing.test.ts
new file mode 100644
index 0000000000..83d0d0c15a
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/typescript/run_timing.test.ts
@@ -0,0 +1,23 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { decisionTimingFields } from './run.js';
+
+test('step timing field names and values are stable', () => {
+ assert.deepEqual(
+ decisionTimingFields({
+ decisionMs: 14.5,
+ semanticObserveMs: 4,
+ visualObserveMs: 3,
+ candidateBuildMs: 2,
+ providerDecisionMs: 5,
+ }),
+ {
+ decision_ms: 14.5,
+ semantic_observe_ms: 4,
+ visual_observe_ms: 3,
+ candidate_build_ms: 2,
+ provider_decision_ms: 5,
+ }
+ );
+});