From One Week of Pitfalls to a Maintainable Agent Workflow: An Engineering Guide
A practical guide to turning a repetitive trend-analysis workflow—login, search, screenshots, matrix recognition, rule calculation, and reporting—into a maintainable automated system. It explains a four-layer design, a seven-step pipeline, three common failure modes, and a pre-launch checklist that favors deterministic code, verifiable state, and models only as a fallback.
1. Background: Turn Repetitive Work into a Maintainable System
In a typical trend-analysis workflow, the daily job is highly fixed: sign in to a designated system, search for target objects by condition, capture a screenshot of the page root view, capture screenshots of local regions, map colors or numbers in those images into a matrix, compute results from an algorithm dictionary, and then aggregate statistics. Processing hundreds of images in a single day looks like little more than clicking and looking. In practice it continuously consumes attention and, under fatigue, produces missed items, mislabels, and inconsistent criteria.
This kind of work is a strong candidate for automation, but it is also easy to underestimate. The flow is fixed, yet the middle is full of dynamic pages, pop-up interference, delayed chart rendering, image ambiguity, multi-step dependencies, and exception fallbacks. Handing every step to an agent that decides freely feels flexible in the short term. Over time it becomes hard to reproduce, hard to test, and expensive to control. After a focused week of work, the lesson condensed into one sentence:
Rules first, models as a fallback; stateful flows with verifiable results; every correction becomes a regression case.
Core computation and page operations should be coded and made deterministic wherever possible. The agent handles scheduling, classification, suggestions, and exception fallback. Every result should be reviewable through a sample set, logs, and an evidence chain.
2. Overall Design: Do Not Let the Agent Own the Entire Job
A stable fully automated flow works better as four layers:
- Control layer: task queue, state machine, timeouts, retries, human intervention, and concurrency control.
- Execution layer: session persistence, page search, screenshots, region location, image recognition, and rule calculation.
- Data layer: root screenshots, cropped screenshots, recognized matrices, algorithm versions, aggregated results, and exception evidence.
- Observation layer: logs, metrics, alerts, replay samples, cost ceilings, and audit records.
The control layer must define the input, output, success condition, and failure condition of every step. Do not drive the whole pipeline with one long natural-language prompt. Split the flow into traceable state nodes, for example:
Initialize task-> Confirm login state-> Run search-> Wait until the chart is stable-> Capture root view-> Locate and crop subregions-> Recognize as a matrix-> Check recognition confidence-> Apply algorithm dictionary-> Aggregate and review exceptions-> Publish report
Each step should answer three questions: what evidence did it produce, how does it decide success, and on failure does it retry, skip, or enter human review? Only when those answers are clear does automation move from a demo script to a runnable system.
3. Engineering Breakdown of the Seven-Step Chain
1. Login and session: authorize first, then automate
Login is the first gate of an automated flow and one of the easiest steps to underestimate. Prefer an authorized account and a compliant access method. Inject credentials through a controlled secret-management mechanism, and do not store them in plaintext in logs or screenshots. After a successful login, persist a reusable session and add a probe that checks whether that session is still valid.
A few principles matter:
- Do not treat an open page as a valid login. Check a user identifier, a permission entry, or a business empty state.
- If a captcha, second factor, or risk-control prompt appears, pause the task and hand it to a person. Do not try to bypass it. That is a compliance and security boundary.
- Treat pop-ups as a rule table and a fallback chain. Handle known pop-ups by type. For an unknown pop-up, look in a small scope for a control that can be closed safely, then recheck the underlying page. If that fails repeatedly, save evidence and pause.
- Do not write “close the pop-up” as one very long natural-language prompt. It should be a maintainable policy: identify the type, locate the control, perform the action, verify the result, and record the exception.
A simplified state-machine sketch:
ensure_login(ctx):if has_valid_session(ctx):return OKopen_login_page()submit_authorized_credentials()if captcha_or_risk_control_detected():save_evidence()raise NeedManualReview("Manual authentication required")assert_logged_in()persist_session()handle_interference(page):for popup in known_popup_rules:if popup.visible(page):popup.close_and_verify(page)return HANDLEDif generic_close_is_safe(page):close_and_verify(page)return HANDLEDsave_screenshot_and_dom_snapshot()return UNKNOWN
The point of pop-up handling is not “find a close button.” It is “after closing, verify that the business page has recovered.” If the close action navigates away, invalidates the login, or shifts regions, treat it as a failure and do not continue.
2. Precise search: stable location, validated results
Common search failures are targeting the wrong input, results that do not match the keyword, and confused pagination. Prefer semantic location: label text, accessibility attributes, neighboring relationships, or stable business fields, rather than absolute coordinates that change easily.
Record the query conditions on every search and assert the basics: result count is in the expected range, the first item or title contains the keyword, an empty state is or is not present, and pagination is or is not required. If the result looks wrong, search again or enter review. Do not carry bad data into screenshots and calculation.
3. Root screenshot: control the rendering environment first
Screenshot quality decides later recognition stability. Fix the browser viewport size, zoom, and font environment, and wait until charts, legends, and values have finished rendering. On pages with heavy animation, wait for the animation to end or temporarily freeze motion. Mask or exclude dynamic areas such as clocks, ad slots, and random recommendations from the recognition region.
After the capture, store metadata: task id, a controlled summary of the page address, viewport size, capture time, chart identifier, and a page-state checksum. When something later goes wrong, you can tell whether the cause was a page change, render delay, or recognition logic.
4. Subregion screenshots: location must be verifiable
From the root view, crop charts, legends, value areas, or numbered regions. Location can come from page structure, known layout ratios, or template matching, but it needs checks: width and height are in a reasonable range, key edges are not cut off, the region contains the expected legend, and the image is not wildly different from the previous task of the same type.
Add a structural check to each crop, such as whether the target region has a border, header, scale, or color blocks. If the check fails, do not force recognition. Save the failure evidence and retry or send the item to human review.
5. Image to numeric matrix: do not assume every recognition needs a remote vision model
This is where cost and accuracy most easily run away. On structured charts, much of the information does not need a general vision model: fixed legend colors, regularly arranged cells, digits in a stable font, and clear coordinate regions can be handled by local image processing and rules.
Prefer local deterministic recognition, with the model behind it:
- Normalize the image: unify size, scale, and brightness, and crop irrelevant edges.
- Calibrate color: build a reference palette from a fixed legend and classify by nearest neighbor in a controlled color space.
- Match templates: match symbols, icons, and cell structures that repeat.
- Use text recognition as a fallback: apply general recognition only to text fields.
- Confidence and human review: if color distance, template score, or structural checks fall below a threshold, mark the sample as ambiguous.
A sketch:
reference_palette = load_palette()for cell in cells:rgb = median_sample(cell.image)label, distance = nearest_color(rgb, reference_palette)if distance > color_threshold:ambiguity = mark_for_review(cell)else:matrix[cell.row][cell.col] = label
If a vision-language model is still needed as a fallback, limit its use strictly: send only small ambiguous regions; require structured fields and a confidence score; cap call count and per-task cost; and pass model output through business rules and cross-checks before it can enter the final result. That reduces hallucination, latency, and cost swings.
Accuracy depends on page stability, sample coverage, and threshold tuning. Do not trust claims of perfect accuracy on a general scene. Build a fixed sample set and keep running regression checks.
6. Algorithm dictionary: separate rules from code, and keep versions traceable
The algorithm dictionary should not live in prompts or one-off scripts. Maintain it as its own configuration or code module. Every result should record the dictionary version, thresholds, recognition confidence, and exception handling. Pure calculation should be a unit-testable function: matrix in, result out, with no dependence on page state.
When business rules change, you update the dictionary version. When a result looks wrong, you can tell whether the cause was recognition, a rule, or missing data.
7. Aggregation: automatic results still need business checks
Aggregation is not a simple sum. Add basic quality checks: whether the record count is complete, whether the null ratio is abnormal, whether the result distribution is out of bounds, whether the result jumps relative to historical trend, and whether exception samples have entered the review queue. The report should include the result plus an evidence index and a failure list.
4. Three Frequent Pitfalls and What to Do About Them
Pitfall 1: Treating pop-ups and login failures as “the model is not smart enough”
Login, pop-ups, and expired sessions are page-state problems, not language-understanding problems. The fix is an explicit state machine, stable location, verification after close, failure evidence, and a human fallback. Any captcha, risk control, or permission exception should go to a person, not to a bypass attempt.
A mature failure chain looks like this:
- Save the current screenshot, a summary of page structure, the current step, and the task id.
- Decide whether this is a known pop-up, an expired session, a network error, or a page-structure change.
- Retry only steps that are idempotent and recoverable, and only a limited number of times.
- After repeated failure, pause the task and alert.
- Add the new sample to the regression set, then replay it after the fix.
Pitfall 2: Vision recognition that spends money first and reworks later
A general vision model fits open, fuzzy cases that are hard to enumerate. Batch structured charts care more about stability, explainability, and low cost. Solve most cells with local color thresholds, template matching, and structural checks, then send the small ambiguous remainder to the model. That is usually more controllable than calling a remote model on every image.
Cost control has four levers:
- Cache: reuse a recognition result when the image digest or region is the same.
- Downsample: recognize key regions instead of the full-page image.
- Limits: set a per-task cap on model calls and an alert threshold.
- Sampled review: manually sample high-risk, ambiguous, and periodic cases.
Pitfall 3: Correct, regress, correct again
This is the most hidden problem in putting an agent into production. Telling a model in natural language “do not get this wrong next time” does not create a stable system. Context changes, pages change, and without tests the same mistake returns.
Turn each correction into an engineering asset:
- Save the failing input: screenshot, page state, intermediate matrix, and expected output.
- Find the root cause: wrong location, insufficient wait, color-threshold drift, truncated region, a bad rule, or model hallucination.
- Fix code or configuration, not only the prompt.
- Add assertions and regression cases.
- Replay the fixed sample set and confirm no new problem was introduced.
- Record the version change and a rollback plan.
Teaching the model then becomes fixing the system. The agent can still schedule work and explain exceptions, but execution stays inside allowlisted actions, parameter checks, and regression tests.
5. A Main-Flow Sketch You Can Copy
def run_task(task):ctx = init_context(task.id)ensure_login(ctx)items = search_and_validate(ctx, task.query)results = []for item in items:wait_until_chart_ready(ctx, item)root_image = capture_root(ctx, item)regions = locate_regions(root_image)validate_regions(regions)crops = capture_regions(root_image, regions)matrix, confidence = recognize_matrix(crops)if confidence < ctx.threshold:enqueue_manual_review(item, root_image, crops, confidence)continueoutcome = apply_rules(matrix, ctx.rules_version)validate_outcome(outcome)save_artifacts(item, root_image, crops, matrix, outcome)results.append(outcome)summary = aggregate(results)verify_summary(summary)publish_report(summary, evidence_index=ctx.artifacts)
The sketch makes a few points explicit: screenshots, recognition, calculation, and aggregation have a clear data contract; low confidence goes to review; every step saves evidence; and the summary is checked again.
6. Pre-Launch Checklist
- Authorization and compliance: account permissions, access frequency, data retention, and privacy redaction stay inside the authorized scope and internal rules.
- Session management: credentials never land in plaintext logs; sessions can be detected as invalid; captchas and risk control go to a person.
- Page stability: fixed viewport, zoom, and fonts; wait for chart rendering; isolate dynamic regions.
- Location and assertions: search, crop regions, and button actions all have success checks. Execution without verification is not enough.
- Layered recognition: local deterministic recognition first; the model handles only ambiguous samples, with a call cap.
- Human review: low confidence, structural anomalies, quantity anomalies, and unknown pop-ups must enter a human queue.
- Idempotency and recovery: deduplicate by task id, write atomically, and resume from a checkpoint so the same output is not produced twice.
- Observability: record the task trace, step duration, failure reason, recognition confidence, model call count, and cost.
- Regression tests: keep a sample set that covers normal cases, empty data, occlusion, color boundaries, and missing regions.
- Version control: version the algorithm dictionary, recognition thresholds, page-location rules, and prompts, and keep a change log.
7. Closing
The key to making an agent a reliable automated worker is not giving it free rein. It is giving it an environment that can be verified, rolled back, and observed. Page operations belong to a state machine. Structured recognition belongs first to local rules. The model handles ambiguous cases and explains exceptions. Every pitfall becomes a regression case. A week of failures then stops being only a story and becomes an engineering asset you can reuse the next time you copy the flow.
