LevelUpWith

Explore / Browser & Desktop Agents: Computer Use in Production / Lesson 2

Lesson 2: Anatomy of the Screenshot-Action Loop

See how every computer-use system runs the same loop: the model sees a screenshot, proposes mouse and keyboard actions, your harness runs them in an environment you control, and a new screenshot goes back. Learn why the harness, not the model, owns execution, safety and stopping.

Free to read, no account needed. Part of Browser & Desktop Agents: Computer Use in Production.

By the end of this level you'll be able to

  • Draw the loop and mark which parts the model controls and which your code controls
  • Build a minimal harness that takes screenshots, logs proposed actions and stops at a step limit
  • Explain why a computer-use model never touches the machine directly, and what that means for sandboxing

The one loop behind every computer-use agent

You have built a tool-calling agent. The model asks for get_weather(city), your code runs it, and you send the result back. A computer-use agent works the same way. The difference is that the only tool is the screen itself.

Anthropic, OpenAI and Google all describe the same cycle in their docs:

  1. Observe. Your code takes a screenshot and sends it to the model, together with the goal and the history so far.
  2. Propose. The model replies with one or more actions, such as "click at (412, 230)", "type hello" or "press Enter". It can also say it has finished.
  3. Execute. Your harness checks each action and then runs it in a browser or desktop that you control.
  4. Repeat. A new screenshot goes back to the model, and the cycle continues until the model finishes or your code stops it.

A good analogy is a remote pair-programming session where your colleague can only see your screen share and tell you what to click. You hold the mouse, so you can refuse an instruction, or decide that 40 minutes is long enough and end the call.

          ┌────────────── MODEL CONTROLS ──────────────┐
          │  reads screenshot + goal → proposes action  │
          └──────────────▲──────────────────┬──────────┘
               screenshot │                  │ action (JSON)
          ┌──────────────┴──────────────────▼──────────┐
          │ YOUR HARNESS CONTROLS: validate, execute,   │
          │ log, screenshot, count steps, decide to stop│
          └──────────────┬──────────────────▲──────────┘
                         ▼ mouse/keys        │ pixels
                  [ sandboxed browser / VM ]

The model controls one thing: what it suggests next. Everything else in that diagram is your code. That includes which actions exist at all, whether a suggestion actually runs, what the environment can reach, how many steps a run may take, and what gets recorded.

Why the model never touches the machine

Anthropic's docs say it directly: the model "doesn't directly connect" to the environment. Your application receives the request, turns it into a real action, captures the result and sends it back. OpenAI and Google describe the same split: the model returns a call, and your client-side code carries it out. A suggestion only becomes a click if your harness makes it one.

This has three consequences:

  • Safety lives in your code. Text on a web page can talk the model into suggesting something harmful. Your harness is the last checkpoint before that suggestion runs.
  • Sandboxing is your job. Whatever the browser can reach, the agent can reach. The vendors recommend a dedicated VM or container with minimal privileges, limited network access, and no sensitive credentials. Your earlier sandboxes course covers how to build one. The point here is that the loop runs inside it.
  • Stopping is your job. The model can say "done", but it can't force a runaway loop to end. Anthropic's example loop has a maximum-iteration cap for exactly this reason: an endless loop runs up API costs.

Walkthrough: a minimal harness

Below is a minimal harness written with Playwright for Python. The model is replaced by a stub that plays back a fixed script. That keeps the loop easy to see and costs no API credits. Later levels swap in real vendor models.

# pip install playwright && playwright install chromium
import json
from playwright.sync_api import sync_playwright

MAX_STEPS = 15                                   # hard stop, owned by YOU
VIEWPORT = {"width": 1280, "height": 800}      # fixed size so coordinates stay meaningful
ALLOWED = {"click", "type", "key", "scroll", "wait", "done"}  # action allow-list

def propose(screenshot_png: bytes, goal: str, history: list) -> dict:
    """Stand-in for the model: screenshot in, ONE action out."""
    script = [
        {"type": "click", "x": 640, "y": 300},
        {"type": "scroll", "dy": 400},
        {"type": "done", "summary": "Finished scripted demo"},
    ]
    return script[len(history)] if len(history) < len(script) else {"type": "done"}

def execute(page, action: dict) -> str:
    t = action["type"]
    if t == "click":
        x, y = int(action["x"]), int(action["y"])
        if not (0 <= x < VIEWPORT["width"] and 0 <= y < VIEWPORT["height"]):
            return "rejected: off-screen"          # never trust coordinates blindly
        page.mouse.click(x, y)                     # CSS pixels from the viewport's top-left
    elif t == "type":
        page.keyboard.type(action["text"])
    elif t == "key":
        page.keyboard.press(action["key"])         # e.g. "Enter"
    elif t == "scroll":
        page.mouse.wheel(0, int(action.get("dy", 400)))
    elif t == "wait":
        page.wait_for_timeout(1000 * min(float(action.get("seconds", 1)), 5))  # cap waits too
    return "ok"

def run(goal: str, start_url: str):
    history = []
    with sync_playwright() as p, open("run_log.jsonl", "w") as log:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page(viewport=VIEWPORT)
        page.goto(start_url)
        for step in range(MAX_STEPS):
            shot = page.screenshot()                       # 1. observe (PNG bytes)
            open(f"step_{step:02d}.png", "wb").write(shot)  # keep evidence for debugging
            action = propose(shot, goal, history)          # 2. propose
            if action.get("type") not in ALLOWED:
                result = "rejected: unknown action"
            elif action["type"] == "done":
                result = "stopped: model said done"
            else:
                try:
                    result = execute(page, action)         # 3. execute
                except Exception as e:                     # a failed action is data, not a crash
                    result = f"error: {e}"
            entry = {"step": step, "url": page.url, "action": action, "result": result}
            log.write(json.dumps(entry) + "\n")
            history.append(entry)
            if action.get("type") == "done":
                break
        else:
            print("stopped: step limit reached")           # 4. harness-owned stop
        browser.close()

run("Explore the page", "https://example.com")

A run writes a log like this:

{"step": 0, "url": "https://example.com/", "action": {"type": "click", "x": 640, "y": 300}, "result": "ok"}
{"step": 1, "url": "https://example.com/", "action": {"type": "scroll", "dy": 400}, "result": "ok"}
{"step": 2, "url": "https://example.com/", "action": {"type": "done", "summary": "Finished scripted demo"}, "result": "stopped: model said done"}

Gotcha: "ok" doesn't mean the action worked. It only means the click was sent. The click at (640, 300) may have landed on empty space. Only the next screenshot shows what happened. That is why the loop always returns fresh pixels instead of trusting the action call.

Gotcha: coordinate drift. The model picks coordinates from the image it was shown. If the viewport changes size, or the screenshot is scaled before it is sent, every click lands in the wrong place. Pin the viewport size and keep the screenshot at the same size.

Trade-off: step limits. A low cap such as 15 cuts runaway cost but kills long, legitimate tasks. Start low, look at your logs, and raise the cap for each task type. Don't set one global number and forget it.

Hands-on exercise

  1. Run the harness and open the step_*.png files. Did the click change anything on the page?
  2. Add {"type": "shell", "cmd": "rm -rf /"} to the stub's script. Confirm the harness logs rejected: unknown action and never runs it.
  3. Remove done from the script and make propose return a click every time. Confirm the run ends at MAX_STEPS.
  4. Add a domain_ok(page.url) check that stops the run if the page leaves example.com. Write one sentence on which layer of the diagram that check belongs to.

Key takeaways

  • Every computer-use system runs the same loop: screenshot → proposed action → harness executes → new screenshot.
  • The model only proposes. Your harness decides which actions exist, whether each one runs, and when the run stops.
  • The model never connects to the machine, so the sandbox, the network limits and the credentials you expose are all yours to design.
  • Always enforce a step limit in code. Don't rely on the model to stop.
  • Log every proposed action and keep every screenshot. That record is how you debug runs, and it is what later levels build replay and evaluation on.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, Anthropic's Computer-Use Toolset.

Create a free account →See the whole course

More like this