From Repeated Pitfalls to Stable Delivery: Agent Automation in Practice
Reliable agent automation is less about making an agent more obedient and more about completing repetitive work correctly, stably, and recoverably. This article explains how to split understanding and planning from deterministic execution, define acceptance criteria for a seven-step collection and calculation workflow, and design browser control, screenshots, image-to-matrix recognition, rule calculation, checkpoints, retries, and reporting so failures stay visible instead of becoming polished but wrong results.
1. The real problem is not making the agent “more obedient”
Logging into a business website every day, searching for target data, capturing hundreds of trend charts, and then recognizing, labeling, and calculating each image is typical repetitive work. It looks well suited to an agent, but the hard part in practice is rarely “whether a script can be generated.” It is whether the work can run continuously, correctly, and recoverably.
Pop-ups may cover controls. Login sessions may expire. Charts may not have finished loading. Screenshot dimensions may change. A model may also confuse visually similar symbols. Worse, if an error is not caught early, it can propagate through later steps and produce a report that is well formatted but factually wrong.
An automation design should therefore do more than reduce clicks. It should meet four requirements at the same time:
- Correctness: Collection targets, recognition results, and calculation logic all have explicit evidence for validation.
- Stability: Normal tasks finish as expected, and abnormal cases do not loop forever.
- Traceability: Every result can be traced back to the original screenshot, recognition record, and rule version.
- Recoverability: After a partial failure, work can resume from a suitable checkpoint instead of starting over.
The core idea is to let the agent handle understanding, planning, and assisted development, while deterministic programs handle stable execution and precise calculation. The two are not substitutes; they have different roles.
2. Break the work into seven steps, then define acceptance criteria
The business flow can be organized as:
Log in to the website → search precisely → capture a baseline screenshot → capture numbered screenshots → convert them into numeric matrices → apply algorithm rules → aggregate statistics.
“Baseline screenshot” and “numbered screenshot” should follow the actual business definition. The former preserves the overall trend or a positioning reference. The latter records a specific object of analysis. Similar filenames alone are not enough to infer a relationship between the two types of images.
Each step needs explicit inputs, outputs, and acceptance criteria.
| Step | Main inputs | Main outputs | Key acceptance criteria |
|---|---|---|---|
| Login | Authorized credentials, entry point | Valid session | A logged-in indicator appears |
| Search | Query conditions, target identifiers | Target page | Page identifiers match the query |
| Baseline screenshot | Target page, capture region | Baseline image | Content is complete and loading has finished |
| Numbered screenshot | Object identifier, capture region | Object image | Identifier matches and the region is correct |
| Matrix recognition | Image, layout configuration | Structured matrix | Row and column counts and values meet constraints |
| Rule calculation | Matrix, rule version | Individual result | Inputs are valid and the calculation is reproducible |
| Aggregation | Verified results | Summary report | Counts are reconciled and exceptions are listed separately |
This breakdown avoids a common mistake: treating “the program did not throw an error” as “the business task was done correctly.” A page can open normally but show the wrong object. A screenshot can be saved successfully but capture a placeholder that is still loading.
3. Browser automation: judge state instead of waiting mechanically
1. Treat login as a state transition
A reliable login is not simply “fill in the account, fill in the password, and click the button.” It means recognizing and handling page state:
Not logged in → submit authentication → wait for the result → logged in, or enter a state that requires human handling.
After submission, check for a clear sign of successful login rather than waiting a fixed number of seconds and continuing. If the session expires, stop the current collection or enter a controlled re-login flow. Do not screenshot a login page as if it were a business page.
When captchas, multi-factor authentication, or other security checks are involved, use authentication methods the site allows, and have a person complete them when necessary. Bypassing security controls must not be treated as part of the automation.
Credentials should not be written directly into scripts, logs, or prompts. Read them from controlled configuration and restrict access.
2. Prefer stable features when locating controls
Clicking by screen coordinates is highly sensitive to window size, zoom, and layout changes. A more reasonable order is:
- Use an explicit, stable control identifier.
- Use semantic information such as labels and accessible names.
- Combine multiple conditions inside a specified container.
- Consider image matching or coordinates only when no other method is available.
After a search is submitted, also verify the identifier, date, or query conditions shown on the result page. That catches cases where the input did not take effect or old results were not refreshed.
3. Do not turn pop-up handling into “close every button you see”
A pop-up may be an advertisement, or it may be a permission prompt, a business warning, or an authentication requirement. Automation should handle only pop-up types that have already been confirmed, and it should recheck the page state after closing them.
For an unknown pop-up, the safer behavior is to save a screenshot, record the context, and pause the task. Blind clicks may close the page or trigger an irreversible action.
4. Wait for business signals
“The page opened” does not mean “the chart is ready to capture.” Checks can include:
- Whether the loading indicator has disappeared.
- Whether the target container is visible.
- Whether the chart region has a reasonable size.
- Whether the object identifier on the page is correct.
- Whether the target region stops changing noticeably during continuous observation.
Image stability is only a supporting signal. A blank image that never changes can also look stable. Content and page state must be judged together.
4. Screenshot capture: secure input quality before discussing recognition
The reliability of image recognition depends heavily on whether capture is disciplined.
First, fix the window size, page zoom, and capture region as much as possible. If the business allows it, capture the target chart directly instead of taking a full-page screenshot and then guessing where the chart is.
Second, give every screenshot a clear identity. Each image should be associated with a task identifier, object identifier, capture time, query conditions, screenshot type, and capture status. Do not rely on a later model to infer this information from the filename.
Third, perform basic quality checks during capture:
- Whether the image width and height match expectations.
- Whether the chart region is blank.
- Whether there is obvious cropping.
- Whether required titles or identifiers are present.
- Whether the image is an abnormal duplicate of the previous screenshot.
Duplicate screenshots can be detected with image digests or content similarity, but identical images should not automatically be treated as errors. Some objects may genuinely have the same trend chart, so business identifiers are also required.
5. Image-to-matrix conversion: match the method to the structure of the problem
1. Do not give every recognition task to a vision-language model
Vision-language models are useful for understanding complex scenes, explaining meaning, and tolerating some layout variation. On rule-based charts, however, asking them to emit an exact matrix directly can produce omissions, misalignment, or symbol confusion.
The question is not simply whether the model is “strong enough.” It is whether the task suits probabilistic generation. For charts with a fixed layout, a limited set of colors, and clear cell meanings, deterministic image processing is often easier to verify.
If a target color itself corresponds to a category, recognize the color category first and then map it to a number by rule. If the digits inside a cell have independent meaning, character recognition or template matching is still required. Color alone cannot infer the value.
2. Build an interpretable recognition pipeline
A common pipeline is:
Crop the image → correct size and position → locate the grid → sample cells → classify features → map values → validate structure.
Grid location can use lines, boundaries, or a known layout. Sampling should not read only a single pixel, because borders, anti-aliasing, and compression noise can change local color. A more robust approach is to select a valid region inside the cell and then measure the color distribution or extract stable features.
Color classification should not require exact color equality. Use a tolerance range or a distance threshold. Thresholds must be validated on real samples; they should not be set arbitrarily and then treated as universal.
Cells that cannot be classified reliably should remain “unknown” rather than being forced to the nearest value. Unknown values increase review work, but they keep errors from being hidden.
3. Do not promise an unverified 100 percent recognition rate
Recognition on a fixed layout can be very stable, but page themes, fonts, zoom, compression, and chart versions can all change. Perfect results on one sample set do not mean every future input will be correct.
Validation should cover different times, different objects, and common abnormal cases. Measure cell accuracy, the share of images that are entirely correct, and whether errors can be caught by validation checks.
When later algorithms depend strictly on the matrix, whole-image correctness matters especially. A few wrong cells among many can change the final conclusion.
6. “Training the agent” should mean fixing engineering constraints
Repeated correction in a conversation usually does not change model parameters, and it does not guarantee that future tasks will follow the same requirements. Lost context, conflicting instructions, and unclear rules can all bring old errors back.
Improvements that actually accumulate should live in engineering assets:
- Write business requirements as explicit specifications.
- Package stable steps as testable functions.
- Turn historical errors into regression cases.
- Put the rule dictionary under version control.
- Make prohibited actions and stop conditions execution constraints.
For example, “do not misread rows and columns next time” is not an effective acceptance mechanism. “The matrix row and column counts must match the layout configuration; otherwise refuse to calculate” is an executable rule.
Questions such as “does a blank cell count as zero or as missing,” “are boundary values included in an interval,” and “how should duplicate screenshots be handled” also need explicit agreements in advance. When there is no agreement, ask the business owner to confirm it. Do not let the model fill in the gap on its own.
After every script change, run historical successful cases and failure cases first. Confirm that no new problem was introduced before starting a batch job.
7. The algorithm dictionary: keep rule calculation separate from recognition
The recognition module only converts images into structured data. The calculation module accepts only validated data and applies a clearly versioned set of rules.
A rule dictionary should at least record:
- Rule identifier and version.
- Input structure and allowed values.
- Calculation steps.
- How missing values are handled.
- Boundary conditions.
- Output meaning.
- Corresponding test cases.
The overall control logic can be expressed in neutral pseudocode:
for each task:if target page validation fails:record a collection exceptionskip the current taskimage = capture and check screenshot()matrix = recognize image(image, layout configuration)if the matrix structure is invalid or unconfirmed cells exist:save evidence and enter the review queueskip calculationresult = calculate with the specified rule version(matrix)save the result and its source informationaggregate verified resultsoutput failures and items pending review separately
The principle is simple: invalid input does not enter calculation, and unfinished work is not presented as a successful result.
8. Long runs need checkpoints, limited retries, and idempotent design
Batch processing of hundreds of images should not depend on one long conversation running from start to finish. Split the work into units that can be resumed independently, and persist their state.
Typical states include pending, capture complete, recognition complete, calculation complete, pending review, and failed. After a restart, use state to decide what still needs to be done instead of reprocessing all data.
Retries should also be classified:
- Temporary network failures can be retried a limited number of times.
- Page-load timeouts can be handled by reopening and validating the page.
- An expired login should enter the authentication flow.
- A changed chart layout should stop automatic recognition.
- An undefined rule should be sent for business confirmation.
Idempotency means that running the same task again should not create duplicate reports or double-count results. Task identifier, object identifier, data time range, and rule version can define result identity. The policy for overwrite, append, or reject-on-duplicate should be explicit.
Also follow the target website’s access rules and the scope of authorization. Use a reasonable request rate, and avoid high-concurrency requests that interfere with normal service.
9. Summary reports must show both results and quality
A final report should not contain only analytical conclusions. It should also state whether the data is complete, which objects were not processed, and which results need review.
It should include:
- Planned task count and actual completed count.
- Number of capture failures.
- Number of recognition exceptions.
- Number of items pending human review.
- The statistical basis for valid results.
- The rule version used.
- Traceability links to original images and logs.
Cost assessment should cover the whole pipeline, not only model-call fees. Page access time, storage, script maintenance, human review, and failed reruns are all real costs of automation.
For fixed charts, local deterministic processing can come first. Complex or low-confidence samples can then go to model-assisted analysis or human review. This layered approach is usually easier to control for cost and risk than “send every screenshot to a model,” but the actual benefit still has to be measured on the real task.
10. Move from small-batch validation to unattended operation
Rollout should proceed in three stages.
In the first stage, choose a small number of representative objects. Validate the full chain of login, capture, recognition, and calculation, and manually check every result.
In the second stage, widen the sample set. Introduce abnormal pages, layout changes, and authentication failures, and validate stop conditions, checkpoints, and recovery logic.
In the third stage, gradually increase batch size within the authorized scope, and add scheduled execution, logging, and alerting. Only when exceptions can be detected reliably is it appropriate to reduce human attention.
The sign of mature agent automation is not how many actions a demo completes. It is whether boundaries stay clear when conditions change: correct tasks continue, uncertain tasks go to review, and dangerous or unauthorized operations stop in time.
Turning “make the model remember the lesson” into “give the system constraints,” and turning “it looks finished” into “it has been verified,” is what converts repetitive labor from a manual burden into an engineering process that can keep running.
