Agent Applications

Reliable Browser Agents: Locators, Verification, and Recovery

Build reliable browser agents with meaningful locators, current-state checks, explicit postconditions, and recovery when a click may already have succeeded.

· · 8 min read

Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.

A reliable browser agent must establish three things separately: it selected the intended control, the browser performed the interaction, and the application reached the intended business state. A successful click proves only part of that chain. A page can accept an interaction while submitting the wrong record, reporting an intermediate state, or losing the response after committing a change.

This guide develops a hypothetical appointment-rescheduling agent. The workflow and recovery rules are proposed designs, not a tested automation implementation or a claim about a particular scheduling product.

Model the browser as a changing observation surface

A browser screenshot or DOM snapshot describes a moment, not a durable transaction. Between observation and action, a list can reorder, a component can rerender, a session can expire, or another user can modify the underlying appointment. The agent needs to carry task identity across these changes rather than assume that the same screen position still represents the same record.

For this proposed workflow, maintain a small execution record outside the page:

  • The authenticated account and permitted application origin.
  • The exact appointment identifier and currently observed revision, when exposed.
  • The requested new time, including timezone and interpretation of ambiguous dates.
  • The current workflow phase and any pending mutation outcome.
  • The evidence supporting the latest state and the remaining deadline.

Keep credentials out of model-visible page summaries. Treat page text as evidence about the application, not permission to change the task. An instruction embedded in an appointment description cannot authorize a different action; the broader boundary is discussed in prompt-injection defenses.

Prefer locators that preserve meaning

Playwright recommends user-facing attributes and explicit contracts, such as roles, labels, and test identifiers. Its locators resolve the current DOM element when used, rather than permanently holding the element found during an earlier action. That helps with rerendering, but it does not establish that a newly matching element still represents the intended business object. Playwright locator documentation.

In the hypothetical scheduler, first identify the appointment detail region by its record identity, then locate the reschedule control inside that region. A page-wide search for “Change” is too broad when several appointments expose identical buttons. If the application provides a stable automation identifier associated with the appointment record, prefer that explicit contract over a generated CSS class.

A selector can be technically unique and semantically wrong. For example, the first row is unique even after sorting changes which appointment appears there. Require the selected region to display the expected appointment identifier, attendee, and current time before progressing to a mutation.

When a locator matches several controls, treat ambiguity as useful failure information. Do not automatically take the first result to keep the run moving. Narrow the context, inspect the current page, or ask for clarification when the underlying task itself is ambiguous.

Separate actionability from business preconditions

Playwright performs actionability checks before interactions and waits until the required conditions hold or a timeout occurs. For a click, these include checks such as visibility, stability, receiving events, and being enabled. Forcing an interaction can bypass some checks; it should not become a generic response to an unexpected overlay. Playwright auto-waiting.

Those browser conditions differ from application preconditions. An enabled “Confirm” button might still apply to an appointment in the wrong account. A visible time slot might have become unavailable since it was displayed. A button behind a security dialog should not be clicked merely because a lower-level API can force the event.

For the proposed workflow, check three layers before confirmation:

Layer Proposed condition Failure response
Browser The intended control is actionable Wait within the shared deadline or inspect the obstruction
Task Appointment and selected time match the request Reobserve and correct the draft
Authority The current actor may make this specific change Stop or obtain legitimate authorization

Evaluate these conditions immediately before the consequential action. A previous successful login is not an indefinitely valid authorization decision, especially after navigation or account switching.

Recover stale observations without blindly repeating actions

Selenium documents stale element references as references that can no longer access the previously located element. DOM changes, navigation, and frame or window context changes can require different recovery steps. Re-finding an element in the wrong context does not solve a context mismatch, and a matching locator can identify a different element after the page changes. Selenium common error guidance.

An agent should therefore classify the failure before retrying. If a read-only details panel rerenders, discard the old observation, locate the appointment again, and validate its identity. If a navigation changed the active page, first establish the expected origin and document. If confirmation might already have been submitted, move into outcome reconciliation instead of repeating the click.

Use a generation identifier for observations in the controller. An action proposal derived from generation 12 should not execute after the controller has replaced the relevant page state with generation 13. This is an illustrative safeguard against stale planning; it does not eliminate the smaller race between the final observation and server execution. Sensitive applications need server-side version checks where available.

Verify completion with correlated evidence

Playwright can observe network traffic and wait for a matching response. Its documentation registers the response wait before the triggering interaction, avoiding a race in which the response arrives before the listener is installed. Playwright network guidance.

In an application you control, correlate the observed request or response with the appointment identifier and operation identity. A generic successful response from the same domain is insufficient: an unrelated background refresh can occur during confirmation. Inspect the documented response semantics; acceptance into a queue differs from completed rescheduling.

Then verify the user-visible state against the authoritative outcome. A useful postcondition for this scenario is that appointment A now has the requested start time and timezone, retains the intended attendees, and has a confirmed revision or confirmation identifier. A temporary toast is supporting evidence rather than the complete success contract.

For third-party applications without a supported status API, reopen the relevant record using a read-only path and compare its details. If the available evidence remains inconclusive, report an unknown outcome and stop further mutations. Confidence generated by the model cannot substitute for missing application evidence.

Walk through a lost-response rescheduling attempt

Assume a hypothetical user authorizes moving appointment A from Tuesday morning to Wednesday at 14:00 in the account's stated timezone. The agent opens A, validates its current details, selects the requested slot, and shows the pending change before confirmation when the workflow requires review.

The controller records that the confirmation attempt is starting. The click occurs, but the browser disconnects before the result becomes visible. There are now several possibilities: the request never reached the server, the server rejected it, or the server committed the change and the response was lost.

After reconnecting, the controller does not resume from “click Confirm.” It resumes from “reconcile appointment A.” It opens the record through a read-only route. If A shows the requested time and an appropriate confirmation, it records success without another submission. If A is unchanged and the service provides a definitive operation-failed result, it can reconsider an authorized retry within the deadline.

If A has moved to a different time, the agent records a conflict and stops. Another actor might have changed it, or the earlier interaction might have targeted the wrong slot. Repeating the original click would hide the conflict rather than resolve it. Where the backend supports them, stable action identities and idempotency make this recovery substantially easier to implement.

Preserve diagnostic evidence and test adverse schedules

Playwright's Trace Viewer presents action history with associated snapshots and diagnostic information, including network activity. Such records can help explain what the browser observed and attempted, although they should not be mistaken for proof of a business transaction's final state. Playwright Trace Viewer.

For this proposed agent, retain a redacted sequence of task identity checks, observation generations, locator decisions, interaction attempts, and postcondition results. Link browser evidence to the application operation record when possible. Restrict access to traces because screenshots, page content, and requests can contain personal or authentication information.

Evaluate adverse schedules deliberately: reorder the appointment list, insert a similarly named record, expire the session before confirmation, rerender the dialog, remove a slot, delay the response, and disconnect immediately after submission. Assert both the final answer and the actual changed record. A fluent completion message with the wrong appointment modified is a failure even if the UI automation encountered no exception.

Frequently asked questions

Are screenshots enough for browser agents?

They can establish visible context, especially when semantic DOM information is unavailable. They generally cannot prove which backend record changed or whether a transaction committed. Combine visual evidence with record identity and an explicit completion check.

Should a browser agent retry every failed click?

No. Reobserving after a failed read interaction is different from repeating a potentially committed mutation. Classify the action and investigate uncertain outcomes before allowing another attempt.

Is an official API always preferable to browser automation?

A supported API often offers clearer identifiers and result contracts, but it may not cover the required task or permissions. Choose the interface whose authority, evidence, and recovery behavior meet the task's needs; keep the same outcome checks whichever interface performs the action.

Source reference list

Browser Agents
Browser Automation
Agent Reliability
Playwright