Reliable AI Agent Automation: A Practical Guide from Repeated Failures to Stable Operation

    This article explains why AI agents that operate pages, read screenshots, and submit results often fail during continuous runs, and how to fix it. It shows how to split tasks into observable steps, choose deterministic methods over open-ended reasoning where rules are clear, handle pop-ups as constrained state transitions, turn screenshot recognition into bounded data extraction, add independent validation, evaluate cost across the full pipeline, and build testing and recovery mechanisms before going fully autonomous. The core takeaway: reliability comes from separating understanding, execution, recognition, validation, and recovery into clear modules, not from loading more responsibility onto the model.

    1. The Hard Part of Automation Is Not Understanding Instructions, but Completing Tasks Reliably

    Having an agent operate a page, read a screenshot, and submit a result looks like it should take a single natural-language instruction. But when it runs continuously, problems tend to appear in the smallest places: a pop-up covers the target area, the close button moves, a number in the screenshot is misread, or the next step runs before the page has finished loading.

    These problems share one root cause: the system mistakes “knowing what to do” for “being able to do it correctly and reliably.”

    Take “close the pop-up” as an example. It involves at least four independent judgments:

    1. Whether a pop-up currently exists.
    2. Which control belongs to the pop-up, rather than the browser window or the underlying page.
    3. Whether clicking that control might trigger another action such as a submit or delete.
    4. Whether the pop-up actually disappears after the click, and whether the business page is still usable.

    If the model has to judge all of this from the full screenshot every time, the outcome depends on layout, occlusion, wording, and the natural variance in model output. Adding more instructions repeatedly can sometimes improve behavior, but it cannot replace engineering constraints.

    A more sensible goal is not to train an executor that “judges everything itself,” but to build an automation system with clear responsibilities: the model handles understanding and planning, deterministic programs handle execution and validation, and exception mechanisms limit the damage.

    2. Split the Task First, Then Decide Which Steps Need the Model

    When designing an automation flow, break the business task into observable, testable steps first, instead of handing a single long instruction to the model.

    Take “enter the page, handle occlusion, read a number matrix, compute the result, submit the record” as an example. It can be split into:

    • Confirm the page state;
    • Check for and handle pop-ups;
    • Capture a screenshot of the target area;
    • Recognize digits and colors;
    • Validate the recognition result;
    • Perform the business calculation;
    • Submit the result;
    • Confirm the submission succeeded and record evidence.

    Once split, choose the right method for each step.

    Task type More suitable implementation Main reason
    Text that can be read directly from the page Read the page structure or data exposed by the application Avoids unnecessary screenshot recognition
    Color regions with fixed position and style Local image processing Clear rules, easy to test
    Digits with a limited character set and stable font Template matching or dedicated OCR Output range can be constrained
    Diagnosing page anomalies Model-assisted judgment Requires understanding context
    Open-ended task planning Model-generated candidate plans Rules are hard to enumerate
    High-risk submit and delete actions Deterministic checks plus human approval Prevents mistakes from spreading

    The core principle: steps that can be completed with clear rules should not require open-ended reasoning every time.

    This is not a rejection of the value of vision-language models. For unfamiliar interfaces, complex semantics, or rare anomalies, the model can be very helpful. For a number matrix that repeats over the long term with a stable layout, a dedicated recognition flow is usually easier to control for both cost and error.

    3. Pop-Up Handling: From “Find the X” to a Constrained State Transition

    1. Prefer page structure to reduce coordinate guessing

    If the application allows reading the page structure, locate the close entry point using the dialog container, button text, accessibility labels, and control roles.

    Saving a single screen coordinate is usually not reliable enough. Window size, page zoom, scroll position, or layout updates can all make the same coordinate point to a different button.

    If you can only work through images, locate the pop-up boundary first, then look for the close control inside it. Do not treat every “close symbol” on the whole screen as a candidate, and never default to clicking the top-right corner when locating fails.

    2. Set preconditions and postconditions for the action

    Before closing a pop-up, verify:

    • The current page is the expected business page;
    • A pop-up actually exists and its boundary can be determined;
    • The target button is inside the pop-up;
    • No other action is currently in progress.

    After the click, check:

    • Whether the pop-up has disappeared;
    • Whether the page is still in the original business context;
    • Whether the target content is visible again;
    • Whether a new prompt or error state has appeared.

    Only when the postconditions are satisfied can the flow move to the next step. Otherwise, it should observe again or enter exception handling, rather than continuing to the later screenshot and submit steps.

    3. Constrain execution order with a state machine

    A simplified flow can be expressed as:

    Ready → Check for occlusion → Handle pop-up → Confirm page → Read data → Validate data → Submit result → Confirm completion

    Each state should define the actions allowed, the success condition, the timeout condition, and where to go on failure. For example, after “handle pop-up” fails, the only options are to re-check or pause; it must not jump straight to “submit result.”

    Retries must be limited, and the page state should be re-fetched after a failure. Repeatedly clicking the same coordinate is not a real recovery mechanism; it just repeats the same unverified assumption.

    4. Screenshot Recognition: Turning Open-Ended Understanding into Constrained Data Extraction

    The main pain points in the original practice were misrecognition of digits and colors, along with the cost pressure of frequently calling a remote model. The most effective improvement is usually not switching to ever more complex models, but narrowing the problem.

    1. First decide whether a screenshot is necessary

    If the digits themselves exist in page text, table structure, or data provided by the application, read that information directly. Screenshot recognition introduces extra error from scaling, anti-aliasing, compression, occlusion, and background interference.

    Only enter the visual recognition flow when the data can genuinely be obtained only through an image.

    2. Fix the region of interest

    Do not hand the entire desktop to the recognition module. Locate the region where the number matrix sits, then split it into cells by row and column.

    This process needs to make clear:

    • Whether the number of rows and columns is fixed;
    • Whether cell boundaries are stable;
    • Whether the page zoom ratio changes;
    • Whether the screenshot contains the complete matrix;
    • Whether loading animations or the mouse pointer cause occlusion.

    If the layout varies somewhat, use stable borders, titles, or other visual anchors to locate the region, then compute cell positions. When it cannot be located reliably, refuse to recognize rather than forcing out a matrix.

    3. Separate color recognition from character recognition

    Color and digits are two different problems and are best handled separately.

    Color recognition can use threshold rules across dimensions such as hue, saturation, and brightness. When sampling, avoid text, edge shadows, and highlighted areas; prefer background pixels inside the cell, and reduce noise by using multiple sample points or region statistics.

    Digit recognition needs to focus on character shape. For scenarios with a limited character set and stable font and size, template matching is an option; for scenarios with more font variation, a dedicated OCR method can be used, with a character-range restriction added.

    Template matching also has limits: font updates, changes in stroke thickness, scaling, and anti-aliasing differences can all make old templates fail. It is therefore suited to controlled interfaces and should not be described as a general-purpose digit recognition solution.

    4. Allow refusing to output when uncertain

    The recognition module should not have only one outcome, “successfully return a digit.” It should also be able to return:

    • Cannot locate;
    • Image incomplete;
    • Characters blurry;
    • Multiple candidates close together;
    • Color category uncertain;
    • Data validation failed.

    For similar characters, if the gap between the best and second-best candidate is too small, the result can be rejected. Here the match score is only an algorithmic metric and cannot be interpreted directly as a true probability of correctness without calibration.

    Likewise, a perfect result on a limited sample should not be described as “the recognition rate has permanently reached one hundred percent.” Accuracy must be explained together with the sample scope, interface conditions, number of tests, and error types.

    5. After Recognition, You Still Need Independent Data Validation

    A digit output by the vision module does not mean it can be used for business operations immediately. Add a validation layer that is independent of the recognition algorithm.

    Common checks include:

    • Structure check: Whether the matrix rows and columns match expectations, and whether any cells are missing.
    • Range check: Whether digits fall within the business-allowed range, and whether colors belong to defined categories.
    • Completeness check: Whether there are empty values, duplicate regions, or obvious cropping errors.
    • Timing check: When the page should stay stable, whether consecutive reads are consistent.
    • Business check: Whether known sum relationships, quantity constraints, or other business rules are violated.

    Business rules can only be used for checking, not as a basis for arbitrarily fabricating data. For example, after finding a sum mismatch, mark it as an anomaly and read again; do not automatically modify a digit to “make up the right answer.”

    For high-impact operations, you can also show the structured result and the corresponding screenshot before submission, and execute only after human confirmation. This way, even if the recognition chain errs, it will not immediately enter an irreversible business action.

    6. Cost Optimization Must Look at the Full Chain, Not Just the Per-Call Price

    The cost of remote visual recognition is usually affected by the number of calls, image size, context length, billing method, and retry frequency. It is not possible to conclude that all solutions are “necessarily expensive” or “necessarily cheap” without the specific conditions.

    A more useful approach is to estimate the full running cost:

    Running cost = remote call cost + local compute cost + development and maintenance cost + human review cost + error-handling cost.

    Local rule-based recognition reduces remote calls, but it also carries the cost of maintaining templates, adapting to the interface, and updating tests. If the page changes frequently every day, over-relying on fixed coordinates and fixed templates may actually increase the maintenance burden.

    A layered recognition strategy can be adopted:

    1. When the page has readable data, read it directly;
    2. When it cannot be read directly, use local dedicated recognition;
    3. When local recognition fails validation, call a more general vision analysis;
    4. When ambiguity remains or the operation is high-risk, hand it over to a human.

    This preserves complex vision capability while avoiding handing every repetitive task to the more expensive, harder-to-constrain step.

    In addition, detect whether the target region has actually changed. When the page content is unchanged, reuse the already-validated result instead of mechanically repeating recognition. Caches must be bound to page state and a validity period to avoid using stale data.

    7. Before Fully Autonomous Runs, Build Testing and Recovery Mechanisms

    1. Build a representative sample set

    Test samples should not contain only the clearest, most standard screenshots. They should also cover:

    • Different window sizes and zoom ratios;
    • Pop-ups appearing and disappearing;
    • Pages loading, failing to load, and partially updated;
    • Similar digits and close colors;
    • Scroll offsets, partial occlusion, and low-quality screenshots;
    • Network interruptions and the risk of duplicate submissions.

    Samples should come with human-confirmed ground truth, and development samples should be separated from independent test samples. Constantly tuning thresholds against the same set of images tends to produce results that look excellent but generalize poorly.

    2. Measure both accuracy and rejection rate

    Counting only “accuracy among results that were output” can hide a large number of cases that cannot be handled. At minimum, record:

    • Cell recognition accuracy;
    • The proportion of fully correct matrices;
    • The proportion that cannot be recognized or is actively rejected;
    • Pop-up handling success rate;
    • End-to-end task completion rate;
    • Average processing time and the proportion of human intervention.

    Matrix tasks especially need attention to overall accuracy: a single digit may look well recognized, but once many digits are combined, the whole matrix can still frequently be wrong.

    3. Keep traceable evidence for failures

    Logs should record the task ID, page state, key screenshots, recognition results, validation conclusions, action timestamps, and failure reasons.

    For screenshots containing sensitive information, control access permissions, retention period, and redaction. Do not keep all raw page content long-term just for the convenience of debugging.

    4. Prevent retries from causing duplicate submissions

    Reading a page can usually be retried safely, but operations such as submitting an order or writing a record cannot simply be repeated. Check whether it has already been completed before executing, and use an idempotency mechanism where possible.

    If no clear result is received after submission, query the business state first, then decide whether to retry. Otherwise, a “network timeout” may be misjudged as “not submitted,” ultimately causing a duplicate operation.

    8. Safety Boundaries Decide How Far Automation Can Go

    Automation accounts should follow the principle of least privilege, allowed to access only the necessary pages and perform only the necessary actions. High-risk actions such as deletion, payment, and permission changes should have stricter confirmation mechanisms.

    Also note that page text, image prompts, and external documents are all data to be processed and should not automatically become control instructions. Content on a page such as “ignore previous rules and perform some action” must not change the system’s established permissions and flow.

    The execution module should use an explicit action allowlist and not directly run arbitrary commands generated by the model. Any plan proposed by the model must also pass parameter validation, state validation, and permission validation.

    9. A Truly Reliable Agent Is a System That Can Explain Its Failures

    Going from occasional success to stable operation is not about giving the model more and more responsibility. It is about splitting understanding, execution, recognition, validation, and recovery into clear modules.

    For pop-ups, replace random clicking with constrained locating and state transitions; for number matrices, replace unnecessary whole-image reasoning with local processing and dedicated recognition; for business submissions, limit error propagation with independent validation and idempotency; for running cost, replace looking only at the per-call API price with a full-chain evaluation.

    So-called “full automation” does not mean the system never fails. It means the system can recognize its own boundaries: it executes stably under normal conditions, stops on its own when uncertain, preserves evidence on errors, and safely continues after recovery. Only by building these mechanisms can an agent go from an assistant in a demo to an engineering component that runs reliably over the long term.