◉ANTIGRAVITY LABJP
Articles/Agents & Manager
◈ Agents & Manager/2026-04-23Advanced

Designing Antigravity Browser Agents That Don't Go Flaky — Taming DOM Drift and Timing

A browser-agent task that passed yesterday trips today, then succeeds on retry, then fails again. Here's how I've been breaking down the causes of flaky Antigravity browser agents in production and addressing them at the design level.

Antigravity422Browser AgentFlakinessE2EOperations14

One morning I opened the log and last night's task was red. I re-ran it with the same prompt and it passed, as if nothing had happened. I've closed that tab with "probably a fluke" more times than I'd like to admit.

When you start running browser agents in production, the first wall you hit is: "it passed yesterday and it's failing today." Antigravity is getting smarter, but the counterpart is the live web, and the web doesn't care about your plans. In both my own apps and a couple of automation gigs I help with, this flakiness has pushed me to the edge more than once.

This article walks through concrete tactics for designing Antigravity browser agents as if they will fail — and making sure that when they do, nothing important breaks. The specifics vary by project, but the mental model translates to other agent frameworks too.

Sort the Kind of Flakiness First

First, understand that "flaky" tasks usually come from three distinct root causes. Bundling them together and "just adding retries" papers over the symptoms.

  • DOM structure drift: A/B tests or small redesigns ship on the target site, and yesterday's selectors no longer match today's markup
  • Async loading timing: the page is painted, but the element the agent needs hasn't been injected by JavaScript yet
  • Network / session jitter: an expired auth token, a CDN edge serving stale content, or bot detection changing what you see

Early on, my bots treated these as one bucket called "it broke." Once I forced the logging to be useful, the split in my own small sample landed around 40% DOM drift, 40% async timing, 20% network jitter. That ratio moves a lot with the sites you automate, so yours will differ — which is exactly why it's worth counting. Treatment priority changes depending on the split, so classification must be instrumented from day one.

At minimum, capture the pre-failure DOM snapshot, the failing step's prompt, and the round-trip timing of the failing call. Put them in your own log pipeline, not just Antigravity's. A week later you can actually draw a bar chart and pick the right thing to fix next.

Don't Hand Selectors Off to the Agent

DOM drift is the biggest source of flakiness. Antigravity's browser agent is pretty good at re-inferring an element from the surrounding context when a class name changes. But whether that re-inference succeeds is up to the target site. A concrete case I hit: after an e-commerce site dropped a limited-time promo button next to "Add to cart," the agent started clicking the wrong button on a noticeable share of runs.

My safer approach is to specify a semantic anchor in natural language, not a selector directly, using domain vocabulary:

On the product detail page that's currently open, click the button that
semantically means "add this item to the cart."
Do NOT click limited-time campaign buttons or coupon-acquisition buttons.
If ambiguous, prefer the button whose visible text exactly matches one of:
"Add to cart", "ADD TO CART", "カートに入れる".

Two design choices matter. First, the developer enumerates the candidate texts. Second, you explicitly list what not to click. A short negative list cuts accidental clicks on A/B-inserted buttons dramatically.

For stricter workloads, I also ask the agent to capture a screenshot of the target element and its ±100px neighborhood before clicking. That residue is a lifeline when something looks off days later.

Wait on State, Not on Time

Next up: async loading. Early on I leaned on fixed sleeps equivalent to time.sleep(2). They pass the day you write them and fall apart the first slow-network day.

For Antigravity, I write state-based wait conditions instead of timed waits:

After submitting the login form, wait until ALL of the following hold:
- The URL path is either /dashboard or /home
- The page contains a text node containing "Welcome, " or "ようこそ、"
- There are zero elements with aria-busy="true" on the page
 
Wait at most 20 seconds. If the condition is not met, raise an error and exit.
If spinners are still present at timeout, attach a screenshot.

By dropping fixed sleeps, the agent moves fast on fast networks and patiently on slow ones. The critical part: don't wait on a single condition, AND multiple conditions together. URL-change alone gets fooled by SPA partial routes. Text-presence alone misses diff rendering. Only the conjunction reliably says "we've actually reached the next screen."

Waits need maintenance because targets redesign. I keep them in a separate file (waits.yaml-ish) that the task prompts reference. When the site changes, the place to edit is obvious, and review stays easy.

Retry Smart, Not Blind

No matter how carefully you write them, browser-agent tasks will never be zero-flake. You need a retry strategy, but blind retries expand the damage. I pair every retry with idempotency.

The rules I run:

  • Retry only steps that are side-effect-free or idempotent.
  • Steps with side effects (payments, form submissions, outbound emails) must notify a human on first failure before any re-attempt.
  • Retry intervals use exponential backoff (1s → 3s → 10s).
  • After three consecutive failures in a day for the same task, stop retrying that task for the day.

The last one looks conservative but matters. When the target site is briefly broken, blind retries nudge the site's bot detection into labeling you. Cutting off at three keeps your IP reputation alive.

What a Failure Record Looks Like, and How to Sort It

Writing "save a DOM snapshot on failure" is easy. Where I actually stall is in reading what I saved. Here is the order in which I read a failed run.

First, turn one failure into one record. A daily JSON Lines file is enough; you don't need a database.

{
  "task": "cart-add",
  "ts": "2026-10-17T21:04:12+09:00",
  "step": "click-add-to-cart",
  "status": "fail",
  "error": "timeout waiting for condition: spinner==0",
  "waited_ms": 20000,
  "url_before": "https://shop.example.com/item/123",
  "url_after": "https://shop.example.com/item/123",
  "dom_hash_prev_success": "a91f3c",
  "dom_hash_now": "77be02",
  "http_status_last": 200,
  "rtt_ms_p50": 380
}

I read it in three passes:

  1. Look at http_status_last and rtt_ms_p50 to rule out network and session problems first. A 401, 403 or 429 in there usually settles the question.
  2. Compare dom_hash_prev_success with dom_hash_now. Hash only an outline of the key elements; if it differs from the last success, suspect DOM drift.
  3. If neither fits and waited_ms ran to the limit, the wait condition no longer matches reality — the async-timing bucket.

Ruling out the network first is deliberate. Rewriting semantic anchors does nothing when the real cause is an expired token.

Those three passes translate directly into a script. This minimal example reads a day's JSON Lines and counts failures by cause:

// classify.mjs — count failure records by cause (Node.js 20+)
import { readFileSync } from "node:fs";
 
const lines = readFileSync(process.argv[2], "utf8").trim().split("\n");
const counts = { network: 0, dom: 0, timing: 0, unknown: 0 };
 
for (const line of lines) {
  const r = JSON.parse(line);
  if (r.status !== "fail") continue;
  if ([401, 403, 429].includes(r.http_status_last) || r.rtt_ms_p50 > 3000) {
    counts.network++;
  } else if (r.dom_hash_prev_success && r.dom_hash_prev_success !== r.dom_hash_now) {
    counts.dom++;
  } else if (r.waited_ms >= 20000) {
    counts.timing++;
  } else {
    counts.unknown++;
  }
}
console.log(counts);

While unknown stays large, you're not recording enough. Add fields before you add theories.

Here is where I look first for each symptom:

SymptomLikely causeLook here firstWhat usually helps
Clicks the wrong buttonDOM driftThe pre-click screenshot of the target elementEnumerate candidate texts and list what not to click
Times out without finding the elementAsync timingWhich wait condition never became trueDrop fixed sleeps; AND several state conditions
Fails in the morning, passes at nightNetwork / sessionHTTP status and round-trip timeRefresh the token before the run starts
Works, then suddenly never again after repeated failuresBot detectionRetry count and spacing just before the lockoutGive up after three failures and wait until tomorrow

The "fails in the morning" row is one I caused myself by misreading a token's expiry. I blamed the site, rewrote the wait conditions again and again, and burned half a day. The answer was sitting in one line of the log; I only noticed after everything else had been ruled out.

None of this is specific to Antigravity. Playwright's documentation, for example, describes auto-waiting — checking that an element is actionable before acting on it — and discourages relying on networkidle. A quiet network is not the same as a usable page. "Wait on state" is that same line, moved into an agent prompt.

Test Your Wait Conditions Before They Go Live

After I moved to state-based waits, I made a different mistake. I tightened a condition and, in the process, required text that never appears on the real page. The task waited the full 20 seconds and then failed, every time, and I left it that way for about a week. In trying to reduce flakiness, I had built a task that fails reliably.

Since then I check every wait condition against a saved HTML dump before it ships. Keep one dump from a good day and one from a bad day, and you can see in seconds, without a browser or an agent, whether the condition passes when it should and fails when it should.

First, pull the wait conditions out into waits.yaml:

login-submit:
  max_wait_ms: 20000
  url_path_any: ["/dashboard", "/home"]
  text_any: ["ようこそ、", "Welcome, "]
  busy_count: 0

Then a minimal script that runs those conditions against a dump. No dependencies; it only looks at the URL, the text, and aria-busy.

// check-waits.mjs — check whether wait conditions hold for a saved HTML dump (Node.js 20+)
// usage: node check-waits.mjs <step> <dump.html> <url-at-dump-time>
import { readFileSync } from "node:fs";
 
const [step, dumpPath, url] = process.argv.slice(2);
const html = readFileSync(dumpPath, "utf8");
const yaml = readFileSync("waits.yaml", "utf8");
 
// A tiny dependency-free reader for waits.yaml (limited to the shape above)
const block = yaml.split(/^(?=\S)/m).find((b) => b.startsWith(`${step}:`));
if (!block) { console.error(`step not found: ${step}`); process.exit(2); }
const list = (key) => {
  const m = block.match(new RegExp(`${key}:\\s*\\[(.*)\\]`));
  return m ? [...m[1].matchAll(/"([^"]+)"/g)].map((x) => x[1]) : [];
};
const busy = Number((block.match(/busy_count:\s*(\d+)/) || [])[1] ?? 0);
 
const path = new URL(url).pathname;
const checks = {
  url: list("url_path_any").some((p) => path === p || path.startsWith(p + "/")),
  text: list("text_any").some((t) => html.includes(t)),
  busy: (html.match(/aria-busy="true"/g) || []).length === busy,
};
console.log(checks);
process.exit(Object.values(checks).every(Boolean) ? 0 : 1);

Running it by hand: a good dump that sits on /dashboard, contains the welcome text and has no spinner returns all three as true and exits 0. The same page with aria-busy="true" still present gives busy: false and exits 1. If the URL is still /login, you get url: false. Whichever condition is dragging the result down shows up directly.

What I want from this is both directions: a condition that is not too strict and not too loose. If a good dump fails, it's too strict. If a bad dump passes, it's too loose — and that second case worries me more, because it's how a task "succeeds" and walks on into the next step.

One more thing worth writing down is how I build the hash that goes into dom_hash_prev_success. Hashing the whole page gives you a different value every time an ad or a timestamp changes. So I pick up only the kind and visible text of headings, buttons, inputs and links, and hash that.

// outline-hash.mjs — hash only the outline of key elements (Node.js 20+)
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
 
const html = readFileSync(process.argv[2], "utf8");
const pick = /<(h[1-3]|button|input|a)\b[^>]*>([^<]{0,40})/gi;
const outline = [...html.matchAll(pick)]
  .map((m) => `${m[1].toLowerCase()}:${m[2].trim()}`)
  .join("|");
console.log(createHash("sha1").update(outline).digest("hex").slice(0, 6));

On a few small HTML files I tried, changing only a button's class left the hash alone, while changing its label or the order of buttons produced a different value. It ignores cosmetic edits and catches the changes that affect the agent's decision — a granularity that suits my use. This is a regex-based shortcut, so deeply nested pages may slip through; if that happens, take the accessibility tree from a headless browser and hash it in the same shape.

Snapshot Prompts for Reproducibility

Another habit that pays off: snapshot the prompt and the result for every run. With Antigravity, identical prompts can exhibit small variations run-to-run — that's the nature of the model. Knowing exactly which prompt, which model, and which inputs produced a given result is what turns a multi-hour forensic from into a 15-minute one.

Per run, I store the following — in the same file as the failure record above, so I only have to look in one place:

  • The full final prompt that was sent (not the template — the rendered version)
  • The model and version
  • The URL and an outline of key elements on the input page (headings, key button/input text)
  • Pass/fail status, plus screenshot and HTML dump on failure

With this residue, when a task suddenly starts failing a week later, you can narrow hypotheses to two or three in minutes. Without it, you re-run the same prompt and pray for another failure to study. Time evaporates.

What You Can't Observe, You Can't Fix

This goes beyond browser agents, but don't skimp on observation. Track, per task, per day:

  • Success rate (successes / attempts)
  • Average steps per run
  • Average wall time per run
  • Failure cause distribution (selector miss, wait timeout, HTTP error, other)

A chart makes "flakiness is creeping up" visible before a user tells you. Gut feel lags, often by weeks. Even in a solo project, half a day spent wiring a tiny dashboard is among the highest-ROI time I know.

Design for "Breaks Painlessly," Not "Never Breaks"

Used well, Antigravity's browser agent quietly shoulders a lot of life admin. But you're dealing with a web that changes on its own schedule. Designing as if nothing will break is what burns you out.

What I stick to, both personally and when helping others: design for "breaks painlessly." Assume DOM drift will come and write semantic anchors. Wait on state, not clock. Separate retries by side-effect and idempotency. And always leave snapshots of what happened. With that bundle, flakiness becomes a background cost you can absorb rather than fight.

If browser agents are bleeding time for you today, start by auditing what gets captured on failure. Once the cause distribution is visible, the order of fixes chooses itself.

Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◈ Agents & Manager2026-04-27
Letting Antigravity Be Your Night-Shift Engineer: A Solo Dev Operating Model
How to operate Antigravity agents as the second engineer who works while you sleep. Task hand-off, scope boundaries, and a morning three-point check turned into a script — the model I have refined while running multiple products solo.
◈ Agents & Manager2026-11-19
Before an Agent Reads Your Issues: Splitting GitHub Actions Into a Reader Job and a Writer Job
Anyone can write an issue body. When an agent reads it inside GitHub Actions, split the workflow into a reader job with no write access and a writer job that never runs the agent, keep the body out of the shell, and check the agent's proposal with a small Python script. Working code included.
◈ Agents & Manager2026-11-14
The Agent PR I Approved Was Rewritten a Week Later: Counting Which Lines Survive 14 Days with git blame
Agent PRs often sail through review, yet the same lines get rewritten soon after merge. Here is a small script that uses git blame to count how many of a commit's added lines are still there 14 days later, the date-ordering trap that skewed my numbers, and how I decide where to look next.