Computer-Use and Browser Agents
Learn how browser agents ground actions, reject stale references, enforce task-specific grants, and verify outcomes in a local fixture.
Language AI HandbookAll chapters Computer-Use and Browser Agents
Suppose a team has a task manager that only exposes a graphical interface. To archive a task, you open its row, choose Archive, and confirm on the next screen. You must identify the task, check that the chosen control still belongs to the current view, and verify the resulting task status. A click that returns without an error establishes much less than those three checks.
A computer-use agent chooses actions from observations of a desktop or browser. The runtime decides what to expose, which actions to accept and how to check the result. A screenshot can show a modal covering a button. A structured tree can expose the button’s role and name. An action wrapper can check both against the application’s current state. Those are different responsibilities, and they become more important as the action has greater consequences.
We start with observation and grounding. Then we build a local mock that makes stale action references and unauthorized writes fail explicitly. A small harness tests two interface variants, a deliberately stale action, and a proposal outside the user’s authorized task. The fixtures have no network, external browser or credentials. The agent control loops chapter introduces the more general observe and act pattern.
What the agent sees
An observation is the subset of interface data that reaches the policy. The underlying environment usually has state the policy cannot see, such as whether a prior request committed on the server, which process owns a dialog, or how long a disabled control will remain unavailable. The wrapper can expose some of that state if the application knows it. Treat missing information as a limit of the observation when choosing the next action.
Pixels. A screenshot contains the geometry and styling that were captured. It can reveal controls drawn on canvas and changes such as an overlay, a moved window or an obscured button. Small fonts, cropping and resizing can remove text or position information. Screenshots can also include personal information outside the task. Crop only where the retained frame still contains the labels and visual context needed to distinguish permitted controls.
DOM and accessibility information. The DOM describes nodes and attributes. A browser accessibility tree exposes a semantic projection for assistive technology, including applicable roles, names and states. Presentation nodes can be omitted, and an accessible name may come from an associated label or a page-specified attribute. See the W3C’s Accessible Name and Description Computation. Absence from the tree does not prove absence on screen. The tree need not say which overlay covers a coordinate or whether the server will accept a change.
A combined observation. Attach structured names and roles to temporary element references and include relevant visual context when layout matters. WebArena describes screenshot, HTML and accessibility-tree representations for its web environment. OSWorld presents screenshots and accessibility information for desktop tasks. Their findings apply to the particular environments and enabled interfaces they evaluate. An application still needs to decide what kind of observation supports its own task.
Three invented counts show the budgeting question. Assume a 1,024-by-768 image is represented by one context unit per 16-by-16 uniform patch, with no extra units and no padding because both dimensions divide by 16. That gives 64 times 48, or 3,072 units. The two text counts are assumed values of 12,000 for a DOM serialization and 320 for a pruned tree. They are comparisons under one hypothetical accounting scheme. An actual tokenizer or vision processor can use different patching, resizing and overhead policies.
PythonIn [3]Expand
SCREENSHOT_WIDTH, SCREENSHOT_HEIGHT = 1024, 768
PATCH_WIDTH = 16
patches = (SCREENSHOT_WIDTH // PATCH_WIDTH) * (SCREENSHOT_HEIGHT // PATCH_WIDTH)
CHANNELS = ("Screenshot", "Full DOM", "Pruned tree")
UNIT_BUDGET = (patches, 12_000, 320)VisualizationOut [4]Expand

For a real run, record the width and height sent, any crops, the model and the actual usage of each input channel. If vision and text have different billing or context semantics, report them separately. Measure the outcome effect of dropping context as well. A shorter tree has no value if pruning removed the parent label needed to locate the right control.
Observation shape and memory
Longer tasks need a record of prior attempts. Keep the current observation, last accepted or rejected action, and any verified state changes needed for the task. Older observations can help diagnose a loop, but their element IDs cannot stand in for references minted by the current observation. Summaries should preserve uncertainty, such as “the request timed out, final state unknown,” so the next step does not mistake a guessed outcome for a confirmed change.
When reducing an observation, keep labels that distinguish similar controls. Two rows can contain identically named buttons. Dropping one row as a duplicate because the button name repeats discards identity you need for grounding. Include a row key, region name or neighboring label. A consistent record ID is more useful for checking a successful state change than an index that merely locates a position in last turn’s list.
Coordinates, viewport, and mapping
Coordinates only have meaning when their frame is known. Assume a screenshot covers the whole viewport, both origins are at the top left, and the image was resized without cropping or padding. A point at in a 1,024-by-768 model image maps to in a 1,280-by-960 viewport. The horizontal scale is , and the vertical scale is . Multiply each coordinate by its own scale. A resized crop additionally needs its offset. Device-pixel and CSS-pixel units need the correct conversion for the browser integration.
Validate the original range, then check the transformed point against the current view. Clamping an invalid proposal to an edge can turn it into an unintended click. A point in a bounding box can also hit a covering element. You can use a fresh hit test or a supported element action, then observe the resulting state. The visible text and the structured name are pieces of evidence. Neither gives a page control authority to perform a write.
Decide which view is authoritative for an action
The same application may supply a DOM representation, a visible raster and a typed record query. They have different failure modes. A DOM node can exist without being a hit target. A visually active-looking control can be disabled in the application. A typed query can identify the record but tell you nothing about which window has keyboard focus. Start from the operation and choose the source needed to support each check.
For a read-only task, visible text can sometimes answer the user’s question directly. For example, a dashboard card can show that a task is completed. That card may belong to a filtered list or a cached page. A trusted record query with the right identity is a stronger postcondition when available. The view is still useful for interpreting the task and for explaining why a proposed control was selected.
On an archive task, the question before acting is whether the intended control and target are current and authorized. Afterward, the question is whether the task now has archived status. A screenshot before the click can support the first condition and say nothing about the second. A successful execution report is evidence that the interaction was accepted. The application’s result is the evidence that the desired state changed.
| Observation source | What can be useful | What still needs to be checked |
|---|---|---|
| Screenshot or crop | Position, occlusion, visible text and layout | Capture time, coordinates, accessibility semantics and identity |
| Structured view | Roles, names, flags, parent regions and local references | Current view membership, visible hit target and applicable grants |
| Trusted application state | Record identity and verified fields | Access scope, source freshness and completeness for the desired outcome |
An interface rendered in a child frame or another app window adds a coordinate and authority boundary. Record which view produced a candidate. An element number without page, frame or session context is only a number. If a proposal was formed in one view and another brought a modal forward before execution, the runtime needs a way to reject the old target or refresh the view. In a multi-tab workflow, attach view identity even when the two tabs show similar titles.
Ground a relative coordinate explicitly
A crop discards part of the parent frame. Its coordinates can still be converted if the crop rectangle and resized image dimensions are known. Let be the point in the resized image, the image dimensions, the width and height the crop covered in its parent frame, and its top-left offset in the same parent units. The parent point is
where:
- is the candidate point in parent coordinates.
- is the proposal in resized-image coordinates.
- is the crop origin in the parent frame.
- are positive widths and heights.
The calculation assumes an axis-aligned crop with no padding and a known common origin convention. It does not support rotations or letterboxing. For a browser implementation, the parent coordinate could be a viewport coordinate or a device pixel. Record which one it is rather than relying on both numbers looking similar.
PythonIn [5]Expand
from math import isfinite
def map_crop_point(point, image_size, crop):
x_i, y_i = point
w_i, h_i = image_size
x_0, y_0, w_c, h_c = crop
if not all(isfinite(v) for v in (x_i, y_i, x_0, y_0, w_i, h_i, w_c, h_c)):
raise ValueError("Point, crop origin and dimensions must be finite")
if min(w_i, h_i, w_c, h_c) <= 0:
raise ValueError("All input and crop dimensions must be positive")
if not (0 <= x_i < w_i and 0 <= y_i < h_i):
raise ValueError("Point is outside the image")
parent = (x_0 + (x_i / w_i) * w_c, y_0 + (y_i / h_i) * h_c)
if not all(isfinite(v) for v in parent):
raise ValueError("Mapped point must be finite")
return parent
def rejected_point():
try:
map_crop_point((320, 10), (320, 180), (100, 80, 640, 360))
except ValueError as error:
return str(error)
raise AssertionError("An out-of-bounds point was accepted")ConsoleOut [6]Expand
(420.0, 260.0) Point is outside the image
The crop center maps to in the parent frame. The second point lies exactly at the excluded right edge of a half-open image domain. The code rejects it. It also rejects nonfinite inputs or a nonfinite result. In an integration, this geometric test is a prerequisite to checking the current hit target. It is not an authorization check and it makes no claim that the mapped point is actionable.
Evaluate observation choices separately from the policy
An implementation decision such as “provide only tree data” changes what information the model can use. To understand that effect, compare the same fixed policy and tasks under different representations. Retain the labels, page versions and available actions. If one variant prunes a needed label and the other includes it, the failure can be attributed more narrowly than when the model, browser and action surface all change together.
Define an expected target for a small set of states. Include pairs of controls with neighboring labels, a disabled button, a non-actionable container, a control behind a modal and a context that needs a safe clarification. If a policy abstains, score it separately or as correct only where abstention is the intended response. Reporting overall match rate without the abstention rule can hide a policy that refuses every challenging example.
Two comparable representations may need different budgets. The pruned tree is likely cheaper for a short task list when the record names and roles are available. A visually positioned canvas task may require pixels. This is why the relevant outcome is cost at an acceptable task and safety rate, rather than the number of context units taken by each representation in isolation. Record capture, preprocessing, model response, validation and UI outcome as separate timing components.
Past views can remain useful after their action references expire. In a viewer-facing log, keep a compact description of the proposal, the validation reason and any verified change. An observation snapshot with personally identifying information should have access and retention rules, even when it was captured for debugging. A separate summary of timing and outcome counts can often support aggregate evaluation without retaining complete screenshots.
Action spaces
An action space describes what the policy can propose. The runtime defines which proposals it can execute for a particular view and which operations the application has authorized. A small vocabulary makes faults easier to diagnose. The right vocabulary depends on the environment and its instrumentation.
- Coordinate input lets you point or scroll where the interface offers no structured element. Accuracy depends on a valid coordinate frame, current geometry and explicit bounds.
- Observation-indexed actions carry an element reference that the runtime resolves against a current view. The same integer can represent different elements in different views. Pair it with a view identity and check current availability.
- Task-level actions can use application features such as a vetted read or explicit archive request. Give state-changing actions a clear scope and outcome. If a structured interface can identify the exact record and return a verifiable result, it can remove ambiguity that a sequence of clicks would otherwise leave.
Action schema in code
The local fixture accepts only clicks on known controls and a request to re-observe. An epoch, meaning the runtime-generated version number of the current view, travels with the proposal. The policy receives display data separated from the runtime’s control map. The fixture uses Python annotations for readability and validates proposals again at execution time. A type annotation does not validate an object created by the caller.
PythonIn [7]Expand
from dataclasses import dataclass, field
from math import isclose
@dataclass(frozen=True)
class Action:
epoch: int
kind: str
element_id: int | None = NoneThe observation exposes roles, names, enabled state and simple boxes. The boxes illustrate viewport units. The mock takes only element actions and does not perform coordinate clicks, OCR or real hit tests. A frozen observation limits accidental mutation in this exercise. A remote policy would receive serialized data and a server would validate the parsed response at the boundary.
PythonIn [8]Expand
@dataclass(frozen=True)
class Element:
id: int
role: str
name: str
bbox: tuple[int, int, int, int]
enabled: bool = True
@dataclass(frozen=True)
class Observation:
epoch: int
page: str
elements: tuple[Element, ...]
text: str = ""
viewport: tuple[int, int] = (800, 600)Grounding: from intention to action
Grounding identifies a candidate control for an intended operation. Check which control types support the action before matching the description. Typing requires a field that accepts text. In this mock, clicks can target buttons and links. Other environments have additional roles and may support keyboard, pointer and semantic actions on different sets of elements.
An exact name can be ambiguous if the screen has more than one button with that name. Include the intended form, row or dialog when you need to distinguish it. When the observation is incomplete, request a more useful view or ask for clarification. In a state-changing task, an ambiguous match is a failure to choose a target. Choosing the first candidate silently changes which record a user’s request applies to.
Semantic fit, freshness and permission answer separate questions. A policy may correctly identify a label in an old snapshot, but the runtime must reject the old reference. It may also ground a current control accurately and still lack authorization for the record or effect. An exact string match can help with the first question only.
Doing it in code: a mock browser
The mock starts with three synthetic tasks. It provides a task list, a detail view, and an archive confirmation. Archive changes the mock’s record status without reaching any real application. In the reordered variant, confirmation wording and button order both differ from the canonical version.
PythonIn [9]Expand
@dataclass
class MockApp:
"""Local mock with no browser, credentials, network, or file actions."""
variant: str = "canonical"
page: str = "tasks"
tasks: dict[int, str] = field(
default_factory=lambda: {1: "open", 2: "open", 3: "done"}
)
selected: int | None = None
epoch: int = 0
controls: dict[int, tuple[str, int | None, bool]] = field(
default_factory=dict
)
TASK_NAMES = {1: "Review invoice", 2: "Submit expenses", 3: "Book travel"}Every render allocates a new epoch and rebuilds the action map. The map ties IDs to runtime operations, record IDs and enabled state. An accessible label is part of the observation passed to the policy. Execution resolves the element ID against the map, so a page string cannot choose the operation to execute.
PythonIn [10]Expand
def render(app):
"""Create fresh view-local IDs and a trusted action map for that view."""
app.epoch += 1
app.controls = {}
elements = []
def add(role, name, op, task=None, enabled=True):
i = len(elements)
elements.append(
Element(i, role, name, (80, 70 + 40 * i, 230, 32), enabled)
)
app.controls[i] = (op, task, enabled)
text = "Synthetic task list"
if app.page == "tasks":
for task, status in app.tasks.items():
if status != "archived":
add("link", f"Open task {task}", "open", task)
elif app.page == "detail":
task = app.selected
text = TASK_NAMES[task]
add("button", "Back", "back")
add("button", "Mark done", "done", task, app.tasks[task] == "open")
add("button", "Archive", "ask_archive", task)
elif app.page == "confirm":
task = app.selected
text = f"Confirm archive of task {task}"
if app.variant == "reordered":
add("button", "Confirm archive", "archive", task)
add("button", "Cancel", "cancel")
else:
add("button", "Cancel", "cancel")
add("button", "Archive task", "archive", task)
else:
raise ValueError(f"Unknown local page: {app.page}")
return Observation(app.epoch, app.page, tuple(elements), text)The following output shows the task list the policy receives. Numeric references are valid for that view only. If another render occurs before the proposed click, a later semantic match must use the new references even when the visible text is unchanged.
PythonIn [11]Expand
def serialize(obs):
lines = [
f"Local view {obs.page}, epoch {obs.epoch}, viewport {obs.viewport}",
obs.text,
]
lines.extend(
f"[{element.id}] {element.role}: {element.name}"
+ ("" if element.enabled else " (disabled)")
for element in obs.elements
)
return "\n".join(lines)
mock = MockApp()ConsoleOut [12]Expand
Local view tasks, epoch 1, viewport (800, 600) Synthetic task list [0] link: Open task 1 [1] link: Open task 2 [2] link: Open task 3
The grounding function
The local policy case-folds and splits names on whitespace. For target term set and candidate term set , the score is their intersection size divided by their union size when both sets are nonempty. Both are sets of words under this tokenizer. The value ranges from zero to one. An exact term-set match scores one. Word order, repetitions and negation are outside the representation, which is why the matcher is appropriate only for this narrow fixture.
The score orders enabled controls of a supported role. It applies a threshold of 0.5 and refuses ties for the best score. Refusal lets a policy add a qualifying label or surface the ambiguity. The example uses a fixed threshold for teaching. A real application can select a threshold on held-out controls and inspect both incorrect acceptance and incorrect rejection.
PythonIn [13]Expand
def _norm(value):
return " ".join(value.casefold().split())
def score_element(target, element):
a = set(_norm(target).split())
b = set(_norm(element.name).split())
return len(a & b) / len(a | b) if a and b else 0.0
def ground(action_kind, target, obs):
roles = {"click": {"button", "link"}}
scored = sorted(
[
(score_element(target, e), e)
for e in obs.elements
if e.enabled and e.role in roles.get(action_kind, set())
],
key=lambda pair: (-pair[0], pair[1].id),
)
if not scored or scored[0][0] < 0.5:
return None, scored
if len(scored) > 1 and isclose(scored[0][0], scored[1][0]):
return None, scored
return scored[0][1], scored
def choose(obs, *labels):
for label in labels:
element, _ = ground("click", label, obs)
if element is not None:
return Action(obs.epoch, "click", element.id)
return NonePythonIn [14]Expand
obs = render(MockApp())
best, scored_candidates = ground("click", "Open task 2", obs)ConsoleOut [15]Expand
Chosen: Open task 2
Scores: [('Open task 2', 1.0), ('Open task 1', 0.5), ('Open task 3', 0.5)]The exact Open task 2 label has all three requested terms. Other task labels share open and task but add a different third term. The intersection has two terms and the union four, giving each alternative 0.5. If the request drops the task number, all three controls tie and the policy selects no control.
VisualizationOut [16]Expand

Why categories first, then names
Filtering by role and enabled state narrows candidate ranking. The runtime still tests the selected element independently. It checks the actual operation and identity, because the role and name delivered to a policy are observation data. An inactive Mark done button stays disabled even if a stale observation showed it enabled.
The sorted scores can reveal whether the requested control was missing, suffered a lexical mismatch, or tied with another one. They do not establish that the operation will succeed or is authorized. If adding region context improves the observed match, the application should still assess final state after the operation.
The control loop
The application yields a fresh observation on each control round, gets a proposal, validates it and records the result. Consequential operations are separately bounded by a trusted grant supplied outside the view. Here the grant can allow a set of task IDs to be marked done and a different set to be archived. The caller constructs that grant from a known authorization decision. The policy cannot expand it through a proposal or page content.
If a click comes from an older epoch, return a stale outcome. For a current proposal, require the action type and element reference to match the local schema. Reject disabled controls. Resolve the operation and target through the current trusted map and check the applicable write grant before mutating a task. A successful click, including a view change, invalidates the old map.
PythonIn [17]Expand
@dataclass(frozen=True)
class Grant:
done: frozenset[int] = frozenset()
archive: frozenset[int] = frozenset()
def execute(app, action, grant):
"""Apply recognized operations via the current runtime-owned map."""
if not isinstance(action, Action) or type(action.epoch) is not int:
return "invalid"
if action.epoch != app.epoch:
return "stale"
if action.kind == "reobserve" and action.element_id is None:
return "observe"
if (
action.kind != "click"
or type(action.element_id) is not int
or action.element_id not in app.controls
):
return "invalid"
op, task, enabled = app.controls[action.element_id]
if not enabled:
return "disabled"
if op in {"ask_archive", "archive"} and task not in grant.archive:
return "denied"
if op == "done" and task not in grant.done:
return "denied"
if op == "open":
app.selected = task
app.page = "detail"
elif op == "back":
app.selected = None
app.page = "tasks"
elif op == "ask_archive":
app.page = "confirm"
elif op == "cancel":
app.page = "detail"
elif op == "archive":
app.tasks[task] = "archived"
app.selected = None
app.page = "tasks"
elif op == "done":
app.tasks[task] = "done"
# Any accepted click invalidates the entire previous action map.
app.epoch += 1
app.controls = {}
return opThe episode ends when its trusted success predicate holds, a policy abstains, a write is denied, or a budget is reached. It passes the outcome history to the policy so the next observation can be interpreted against the prior result. Budgets count proposals across an episode. A call that observes no change is still work for the UI, policy and wrapper.
PythonIn [18]Expand
def run_episode(app, policy, grant, predicate, budget=12, max_recoveries=2):
outcomes = []
recoveries_remaining = max_recoveries
for _ in range(budget):
if predicate(app):
break
obs = render(app)
action = policy(obs, tuple(outcomes))
if action is None:
break
outcome = execute(app, action, grant)
outcomes.append(outcome)
if outcome == "denied":
break
if outcome in {"stale", "invalid", "disabled", "observe"}:
if recoveries_remaining == 0:
break
recoveries_remaining -= 1
return predicate(app), tuple(outcomes)Archive task 2 by choosing its row, opening the confirmation and selecting the action supported by the current view. Confirm the task’s stored status through the outcome predicate. A click on Cancel can also succeed as an interaction. It does not reach the requested task state.
PythonIn [19]Expand
def archive_policy(obs, history):
if obs.page == "tasks":
return choose(obs, "Open task 2")
if obs.page == "detail":
return choose(obs, "Archive")
return choose(obs, "Archive task", "Confirm archive")
archive_two = Grant(archive=frozenset({2}))
archived_two = lambda app: app.tasks[2] == "archived"
success, outcomes = run_episode(
MockApp(), archive_policy, archive_two, archived_two
)ConsoleOut [20]Expand
Canonical task complete: True | outcomes: ('open', 'ask_archive', 'archive')Give the policy enough context to refuse
Role filtering is a convenient first pass. It is possible to rank candidates after discarding controls that cannot support the requested interaction. The exact domain still matters. An HTML input can be readonly, a field can be present but covered, or a web component can expose a button role on a visual surface that responds to keyboard interaction differently. A role is a candidate feature. The runtime still needs to validate what it can execute now.
For a task list, preserve record anchors such as a row key or the task title and its surrounding region. A common UI shows both a “Mark done” button in a floating toolbar and a similarly named button in a task detail panel. If a policy only receives button labels, either could be selected. Include the relationship “this control belongs to task 2,” when the adapter can verify it, rather than relying on reading order. The toy embeds task numbers in the open-row labels. The dispatcher holds the actual target task ID.
A score threshold handles weak matches. It does not handle ties without a separate outcome rule, and a high score does not prevent a false match. A case-folded bag-of-terms scorer treats a repeated word as one term. It can put “Archive task 2,” “Task 2 archive” and “Do not archive task 2” closer than an application wants. Restrict the toy to labels whose meaning is represented by its small vocabulary. Use ambiguity and unknown wording as distinct checks in policy evaluation.
For a more complex system, record the difference between candidate recall and final grounding accuracy. Candidate recall asks if at least one identifiable correct control was available in the returned candidate set. Final accuracy asks if the policy selected the correct one under the intended setting. The second metric cannot tell you by itself whether a matcher missed the correct item or a ranker ignored it. A two-stage search can help recall and then rerank, but compare its latency, output consistency and failure distribution against a simpler condition.
The fixture’s three archive phases make different assertions. The list view needs the exact row. The detail view needs the archive affordance for that row. The confirmation needs the intended effect in the current dialog. Each step can have the expected textual label and still be wrong if it belongs to another target. Check whether the selected record was preserved across view changes, and distinguish that validation from matching the text on a newly rendered button.
Define the boundary around a proposed action
It helps to name the moments in the runtime explicitly. First comes parsing, which reads input under the action schema. Then comes validation, which checks current reference, supported affordance and scope. Execution changes state only for accepted operations. Verification reads a trusted postcondition when the result matters. A runtime can emit different outcomes for each boundary. The categories are valuable even though the operations happen immediately in the local fixture.
| Decision | Example failure | Evidence to collect |
|---|---|---|
| Parse | Element reference has the wrong type | Schema failure category |
| Resolve | Current view no longer contains the intended control | View/epoch and target lookup result |
| Authorize | The operation targets a different task than the grant | Outcome and task-bound authority provenance |
| Execute | A control interaction failed on the local app | Operation result and whether an effect is known |
| Verify | The accepted interaction did not reach the goal | Before/after record state and task predicate |
The runtime should not substitute a nearby target on an invalid reference. That would convert an invalid-action count into a real action on an unintended record and deprive the policy of the reason to recover. Likewise, treat the operation chosen by a human-visible confirmation button and the authorization supplied by the application as different fields. The confirmation display does not reveal the exact terms under which the user approved a write.
A grant in the toy is passed as an immutable object by the trusted application. It allows record-level operation decisions. A system with multiple simultaneous actors may need grants that also bind account, resource version, or a time window. Verify the grant at the action boundary, not just when a long-running task begins. If the current user or target changes during the run, establish what consequences previously accepted actions had and which future actions are still allowed.
Demonstrate guard ordering with harmless local state
The following local trace starts with task 2 already completed and checks the enabled-state rejection. A second proposal tries to reuse an old view reference after rendering again. Unlike a missing-reference check, the epoch check catches the reusable integer even if the current map still contains the same numeric ID. Both checks run against an in-memory object.
PythonIn [21]Expand
def guard_probe():
local = MockApp()
local.tasks[2] = "done"
view = render(local)
open_task = choose(view, "Open task 2")
opened = execute(local, open_task, Grant())
detail = render(local)
done = next(e for e in detail.elements if e.name == "Mark done")
disabled = execute(
local,
Action(detail.epoch, "click", done.id),
Grant(done=frozenset({2})),
)
stale = execute(local, open_task, Grant())
return opened, disabled, stale, local.tasks[2]ConsoleOut [22]Expand
Open, disabled, stale, final: ('open', 'disabled', 'stale', 'done')The outcome is open, disabled, stale and done. The attempted action on a disabled control did not change the task. The stale reference never reaches the current map lookup. This matters because accepting a guessed epoch with an old reference can yield an action with a valid current index and a different meaning. The mock cannot guarantee that a caller chose an ID for the reason it claims. It can validate the reference and enforce the resulting operation under trusted permissions.
Recovery
Stale reference recovery changes both the observation and the action. On the next round the runtime builds a new map and the policy chooses again. Copying a discarded element ID onto a current request could point to a different control. A failed write with unknown commit state requires a different check: ask the application what happened before retrying. Repeating a possibly successful operation can produce a duplicate change.
The fixture exercises one controlled stale action. The first proposal carries the preceding epoch and is rejected before it changes state. After that recorded rejection, the policy grounds from the fresh observation. The trace records the rejection and eventual archive separately.
PythonIn [23]Expand
def stale_once(obs, history):
if not history:
return Action(obs.epoch - 1, "click", 0)
return archive_policy(obs, history)
success, outcomes = run_episode(
MockApp(), stale_once, archive_two, archived_two
)ConsoleOut [24]Expand
Recovered from stale reference: True | outcomes: ('stale', 'open', 'ask_archive', 'archive')A disabled control calls for checking its prerequisite. An invalid reference calls for a fresh view and new target search. An authorization denial calls for stopping or routing permission through the application’s control path. Recoveries are bounded because waiting and re-observing indefinitely can hide a failure and waste resources.
A navigation or transport error may leave an application mid-task. A safe read of current state can establish whether a side effect took place. If state is unavailable, preserve that uncertainty in the report and escalate according to the user’s policy. A navigation control that returns to the last view may help find context. It does not undo prior writes. Record actions and observed outcomes with enough context to reconstruct what happened while avoiding unnecessary capture of user data.
Evaluation on real interfaces
A benchmark should show what was counted as success and which parts of the environment it varied. WebArena uses evaluators tied to intent and resulting interface state for its simulated website tasks. OSWorld describes execution-based evaluation for its environment. Build the check around the user’s requested state rather than the model’s report that the goal was achieved.
Outcome evaluation inspects resulting state. For this mock, success requires task 2 to have state archived. Stronger predicates can check that other records retain their expected values and duplicate writes did not occur.
Trajectory evaluation checks how the state was reached. Count stale proposals, invalid references, denials and unexpected side effects. If a target was resolved but rejected for policy reasons, record that separately from grounding failure. An episode that reaches its final state through an unauthorized intermediate mutation still has a problem.
Robustness evaluation repeats the same task on versions with controlled changes. Vary labels and ordering separately when you want to isolate which change caused a failure. When a coverage fixture changes both together, it supports an observation about that combined variant. Compare fixture results with separately measured workloads. Passing two synthetic cases does not estimate success on the tasks a deployed client encounters.
Metrics that matter
Give every rate a unit and denominator. Task success divides completed tasks by attempted tasks under a stated budget and retry rule. A stale rate divides stale proposals by the eligible actions counted. Grounding accuracy needs verified intended targets and a clear treatment of abstention. A rate for allowed writes needs the relevant authorized operations as its denominator.
A model can succeed on one of several attempts. Report how many and whether the environment is reset between attempts. State whether later attempts benefit from feedback. Also keep latency by component, the number of human approvals, and any costs needed to interpret completion. Use the same workload and validation rule for each compared system.
Design the perturbations and the denominators together
Start with one frozen reference task and vary one factor at a time when the attribution matters. For example, compare a change in label wording at the same button position, and separately compare the same labels with the controls reordered. If both changes occur together, the experiment still answers whether the policy survives the combined variant. It cannot estimate the effects independently. The fixture below combines the changes so a label-aware policy has an authored resolution and a positional policy has a measurable failure.
Include a no-change control, such as the same interface rebuilt with fresh local element IDs. A policy should re-resolve current references even when the labels look identical. If an environment offers stable handles, specify what makes them stable and when the wrapper considers them invalid. For a warm restart test, the interesting signal can be whether the action is rejected after the environment has changed while the cached observation still exists.
For permission evaluation, construct paired cases that have the same visible state and action but different trusted grants. On one case the archive target is authorized. On the other it is not. A successful denial in the second case is the desired outcome, not a task failure to average away. Record both unauthorized change attempts and actual unauthorized effects. A system that correctly denies an attempt still gives you evidence about the policy’s proposal behavior.
The task metric gives an episode-level verdict, while the action metrics operate over a trajectory. A variant with one success after three actions and another with one failure after twelve actions cannot be pooled into a meaningful “13 good clicks” count. Separate rates by the event’s opportunity to occur, and show raw counts for small fixtures. Report the termination reason with the number of proposals processed.
| Test condition | Expected guard or behavior | Check at the end |
|---|---|---|
| Correct target on the current view | Resolve and accept permitted actions | Target task has the expected status |
| Reference from an earlier epoch | Reject and issue a fresh view before the next proposal | Earlier action made no change |
| Current reference for an already disabled control | Reject despite an otherwise appropriate task grant | Existing task status is preserved |
| Current archive on a different task | Deny a write outside the grant | No unauthorized record changed |
| Fixed position under a reordered dialog | Observe repeated wrong outcomes and enforce a budget | Archive remains incomplete |
| Scope-limited compound task | Resolve both permitted effects independently | Verify both target records |
Before evaluating a real model, pin the version and record the policy input. If the model or wrapper sees a user’s chosen notion of completion differently on two runs, the comparison is underspecified. The prompt can ask the policy for a stop action, but the environment must compute the official task outcome. For a compound task, record each required postcondition and any state that must remain unchanged. Otherwise a policy can finish only a subset and still look correct in a coarse success metric.
When a run ends, record the state known to the application. That matters independently of whether the agent emitted a final answer. A failed transport can hide a successful write, while a fluent message can falsely claim completion. When the environment supplies a reversible operation, test the actual replay or undo behavior separately. In this mock, archive changes one field and has no undo action. A broader wrapper would need a documented restoration operation before claiming reversal.
Measure time at the correct boundary
Latency has multiple causes. A busy view can make rendering and extraction slow. A long observation can take the model more time to process. A remote browser can add a transport round trip, and an accepted operation can wait on a backend. Record these components with monotonic timing and identify where the bounds apply. A step budget limits the number of model proposals. A deadline limits total elapsed time. The first does not guarantee the second if a single observation or action can hang.
For an end-to-end performance experiment, choose workload slices such as list lookup, form completion and a two-record update. Run multiple independent episodes with resettable state. Report the number of incomplete and denied episodes alongside their latencies, since measuring only fast successful runs can hide wasted time on failures. Report the policy version and environment version for every compared run. If operator assistance is required in one variant, record its time and decisions separately.
Choose how to count waiting. A model may ask the wrapper to re-observe instead of proposing a write. If you count those rounds in the episode budget, a slow-loading page consumes part of the same finite workload. If the adapter waits for a condition before reporting an observation, the task budget may remain unchanged, but elapsed time increases. Either policy can be suitable. The comparison must reveal which convention distributes the cost.
State identities and observation freshness
In the mock, rendering increments an epoch even if a screenshot or label list appears identical. That conservative choice makes a cached action reference unusable between responses. A real implementation might key an observation to a view, incremental document version or adapter-managed short-lived reference, depending on what it can trust. The returned status should indicate when a fresh observation is needed.
A check immediately before execution limits the use of known-old information. It does not ensure that the interface stays unchanged after the check. A real browser can react to timers, streaming data, other decisions by the user or backend writes. A local action map can give a truthful status about what it accepted and still leave the business result unknown. Where available, verify a record version at the mutation boundary and observe a source of state that reflects the actual outcome.
Watch the lifetime of cross-step conclusions. The agent may know it opened the correct task one step ago. If the page suddenly redirects to a search screen, that conclusion no longer establishes the current selection. A good trace shows whether the proposed record remained consistent across steps or relied on a stale implicit assumption. For an important write, record the verified current target near the operation rather than deriving it from old trace text alone.
A small harness
The label-based policy asks for one of two known confirmation labels. The position-based version chooses the second button in either view. The canonical view puts Archive second, while the reordered view puts Cancel second. Both use the same runtime grant and success predicate, so the difference is in target choice rather than write permission.
PythonIn [25]Expand
def positional_policy(obs, history):
if obs.page == "confirm":
return Action(obs.epoch, "click", 1)
return archive_policy(obs, history)PythonIn [26]Expand
def run_harness(policy):
results = {}
for variant in ("canonical", "reordered"):
ok, trace = run_episode(
MockApp(variant=variant), policy, archive_two, archived_two
)
results[variant] = {
"success": ok,
"actions": len(trace),
"invalid": trace.count("invalid"),
"stale": trace.count("stale"),
"disabled": trace.count("disabled"),
"denied": trace.count("denied"),
}
return resultsPythonIn [27]Expand
semantic_results = run_harness(archive_policy)
positional_results = run_harness(positional_policy)ConsoleOut [28]Expand
Semantic labels: {'canonical': {'success': True, 'actions': 3, 'invalid': 0, 'stale': 0, 'disabled': 0, 'denied': 0}, 'reordered': {'success': True, 'actions': 3, 'invalid': 0, 'stale': 0, 'disabled': 0, 'denied': 0}}
Fixed position: {'canonical': {'success': True, 'actions': 3, 'invalid': 0, 'stale': 0, 'disabled': 0, 'denied': 0}, 'reordered': {'success': False, 'actions': 12, 'invalid': 0, 'stale': 0, 'disabled': 0, 'denied': 0}}The fixed-position policy loops in the reordered fixture until the step limit. Its proposals can have valid IDs and current epochs yet fail to complete the task. Invalid and stale action counts alone cannot diagnose grounding. The label policy succeeds in both authored conditions. It recognizes two known labels. A larger test should add unseen variants and preserve task identity and success meaning.
PythonIn [29]Expand
import numpy as np
policy_names = ("Semantic labels", "Fixed position")
variant_names = ("Canonical view", "Reordered view")
OUTCOME_MATRIX = np.array(
[
[
int(results[variant]["success"])
for variant in ("canonical", "reordered")
]
for results in (semantic_results, positional_results)
]
)VisualizationOut [30]Expand

A separate check proposes Archive for the wrong task. The grant allows only task 2. Opening task 1 is an allowed read of the synthetic list. When the policy asks to archive it, execution returns a denial and task 1 stays open. This tests an authority boundary independently from whether the element was grounded correctly.
PythonIn [31]Expand
def wrong_target_policy(obs, history):
return choose(obs, "Open task 1" if obs.page == "tasks" else "Archive")
app = MockApp()
success, outcomes = run_episode(
app, wrong_target_policy, archive_two, archived_two
)ConsoleOut [32]Expand
Out-of-scope change complete: False | outcomes: ('open', 'denied')
Task 1 still open: TrueWorking example: reconciling a task list
A compound objective marks task 2 done and archives task 1. The grant carries each operation and record separately. After marking task 2 done, the policy reads the accepted outcome, returns to the task list, takes a new view of task 1 and confirms the archive. It uses the same runtime for both writes. The success predicate checks both final task states.
PythonIn [33]Expand
def compound_policy(obs, history):
if obs.page == "confirm":
return choose(obs, "Archive task", "Confirm archive")
if "done" not in history:
return choose(
obs, "Open task 2" if obs.page == "tasks" else "Mark done"
)
if obs.page == "tasks":
return choose(obs, "Open task 1")
if history[-1] == "done":
return choose(obs, "Back")
return choose(obs, "Archive")PythonIn [34]Expand
app = MockApp()
compound_grant = Grant(done=frozenset({2}), archive=frozenset({1}))
finished = lambda local: (
local.tasks[2] == "done" and local.tasks[1] == "archived"
)
success, outcomes = run_episode(app, compound_policy, compound_grant, finished)ConsoleOut [35]Expand
Compound goal complete: True | outcomes: ('open', 'done', 'back', 'open', 'ask_archive', 'archive')
Final local tasks: {1: 'archived', 2: 'done', 3: 'done'}A final result can describe each operation separately. If the first write succeeded and the archive was denied, report a partial outcome. A single failed label loses information about a completed write. A single done label can conceal an unmet part of the request. The fixture is sequential. An application that promises an atomic multi-record change needs transactional support or a specified compensation policy at its own boundary.
Key Parameters
Define the view and action schema, maximum steps and recoveries, matching threshold, and success predicate before comparing policies. The fixture sets a twelve-proposal episode budget and allows two recovery attempts after recoverable failures. The epoch checks freshness of the runtime’s local map. The grant names the task IDs and permitted operations. Confidence thresholds, page freshness and user authority are separate controls.
For real experiments, retain the environment version, viewport, input representation, policy version, tool settings and task fixture. Record the retry policy alongside success rates. A retrospective evaluation may require pinned browser and application versions, plus documented dependencies on external state. Where an environment cannot be frozen, report that variation rather than attributing every change to the policy.
The untrusted observation problem
The runtime can observe page text, accessible names and screenshots without treating them as changes to authority. In the mock, a label can have any text. The policy may propose a click because of that text. The dispatcher still checks its current reference and trusted operation and record permissions before changing state. The wrong-target experiment shows this independently from grounding.
A production application can put guards at multiple boundaries. Validate parsed actions against an allowlist for the task. Keep private data and credentials out of observations the policy does not need. Authorize consequential changes outside page content, binding approvals to the verified operation and target. Intercept activity that crosses a browser context or service boundary where the integration permits it and verify the destination through trusted state. Specify denial and escalation before deployment.
A page title, source label or confirmation string can provide semantic evidence. A trusted origin can still have untrusted user-supplied content. Observation formatting and provenance labels help the model interpret the input. A separate runtime rule decides if an operation is in scope. The mocked permission rule is narrow. A real integration needs isolation and authorization checks for the effects the browser can actually produce.
Keep attempt metrics separate from permission checks
A policy can be tested with fixed observations whose labels suggest an operation outside the caller’s grant. The test succeeds when the runtime denies that operation and the state remains unchanged. Render the same controlled label in both authorized and unauthorized cases so that the permission test does not also change grounding difficulty. If the app uses explicit human confirmation, test that its receipt names the exact effect and target and becomes stale when the relevant context changes.
The trusted grant in the notebook never comes from a rendered page. The display text and current control metadata still contribute to reasoning about what the policy intends to click. Keeping those data useful is compatible with keeping them untrusted for authority. A label can tell you which action is being offered. Separate controls determine whether the application can execute that action for the task.
For an integration with real third-party sites, publishing content, changing application permissions or sending private material can have consequences outside the browser. Define where authorization and data-handling decisions are made. For a permission check to support the actual action, identify the requested effect, the intended resource and its verified destination, and the principal on whose behalf the request is performed. The authority path can reject unknown or ambiguous destinations without relying on a page’s description of them.
Context boundaries also matter when a legitimate website contains content written by other users. The site’s identity can be trusted for routing under a particular integration without making every message inside it a trusted instruction. Observation provenance is useful for explaining the source of displayed information. Application authorization still needs its own verified state and policy.
Choose recovery behavior by outcome
The same apparent lack of progress can represent a disabled action, a stale reference, a state change that never happened, or a state change that happened but was not observed. One generic retry rule treats these cases alike. In practice each needs a separate branch based on trusted outcome evidence. Compare the last known state to a fresh verified state and only retry if the operation is safe to repeat under the intended extension of the task.
If a supervisory system pauses after a stale reference, the resume point may need both a fresh observation and the current grant. Resuming a previous planning message without verifying either can start the next step from assumptions that no longer hold. A human correction can also change the target. When that happens, recompute what counts as success before restarting the control loop.
Retaining a short local trajectory can show a recurring page pattern or alternating interactions. A repeat detector needs stable signals separate from the epoch because every fresh observation has a new version. In the fixed-position example, detail and confirmation views alternate after a Cancel result. The count limit is sufficient to terminate this toy. A production supervisor can compare semantic view identity, last permitted effect and elapsed time to decide whether to request help earlier.
Prepare a small benchmark record for every environment version
For a new version of the task manager, capture the application revision, the task fixture’s initial state, the expected target and effect, and the test permissions. Record the variant applied to each run. This allows a direct check of whether a failed episode faced a new representation or a different task. Keep the evaluation predicate separate from the policy so it can be maintained against application behavior without training the policy on its private test inputs.
A small fixture can be deterministic and still miss important cases. Examples include an archive control whose visible and accessible names disagree, a busy indicator covering the confirm button, or a repeated click after a slow request. Add cases for actual failure modes seen in authorized test environments rather than assuming that a single artificial robustness test predicts the production error mix. Report which cases use scripted inputs and which use model outputs.
If an experiment compares accessibility-only against hybrid observations, decide in advance how to handle records where one observation channel is missing. One option is to restrict the matched comparison to tasks with both channels and report their coverage. Another is to include missingness as part of the real workload and record when a system has to abstain. Those designs answer different questions. Describe the observation budget before presenting any aggregate score.
On-device, desktop and browser workflows can also differ in how application state is accessible after an action. A browser event might be observable through a DOM change. A desktop program could expose an output file in an approved local directory. A structured application interface could return a committed record ID with updated fields. Use a task-specific postcondition and document which artifact is trusted. A single generic screenshot match can confuse a transient animation, an optimistic update, and a durable commit.
Limitations and impact
The examples isolate three failure modes in a local deterministic fixture. A real interface can change between validation and execution, a screenshot and tree can be out of sync, and the meaning of a control can depend on external state. A runtime can reject stale references it observes. It cannot derive an application-wide atomicity guarantee from an epoch alone. Check postconditions after consequential actions and expose outcomes the application cannot verify.
The two variants use short scripted policies and a handful of controls. They cannot rank real computer-use systems. A benchmark for a deployed application needs diverse tasks, observed variants, controls for distribution drift, and a representation of actions that were declined or escalated. Isolate changes to attribute a gap to one factor. Compare measured latency and cost under that protocol.
A structured API can offer explicit record identifiers and typed results. A browser may still be the available surface for tasks in a legacy application. Select the interface that satisfies workload, permission and observability requirements. Through a browser, desktop wrapper or API, preserve the distinction among a proposed action, authorized execution, and verified outcome.
Summary
- Choose observations that preserve the context needed to identify actions, including current labels and relevant geometry.
- Resolve an action against the current view, validate its runtime effect and check write authority separately.
- Re-observe before re-grounding stale references. Check application state before retrying a write with uncertain outcome.
- Measure resulting task state alongside invalid, stale and denied proposals across controlled variants.
- Keep observed interface content separate from the permissions that govern the task.
Quiz
Check how observation coordinates, action references and verified outcomes fit together.
Computer-Use and Browser Agents
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!