Building a Screen-Operating AI Agent from Perception to Safety
Machine LearningModel answerLast updated
Design a multimodal agent that reads a desktop screen, plans multi-step tasks, drives the mouse and keyboard within a latency budget, and stays safe and measurable.
Scenario
You are asked to design an autonomous software agent that completes tasks on a desktop computer the way a person would: it looks at the screen and then moves the mouse and types on the keyboard. Example instructions include "Find and reserve a flight to Seattle on this airline site" and "Write a summary of today's meeting from the emails in my inbox."
What your design must cover
- Screen representation. How is the current screen presented to the model? Compare raw screenshots with structured sources such as the DOM or the OS accessibility tree, and say what you would actually use.
- Decision logic. Is a purely reactive policy enough, or do you need a planning component? Explain how the agent copes with tasks that take many steps.
- Action interface. How do the model's outputs (coordinates, element references, text) become real OS-level mouse and keyboard events?
- Robustness and safety. How does the agent cope with layout changes (for example responsive pages), slow or unpredictable environments, and how do you prevent harmful, irreversible actions such as deleting files or making payments?
Constraints
- Displays can be as large as 4K.
- Each inference step should finish in under about 500 ms so the experience feels fluid.
- The agent must handle multi-step flows (navigate to a site, fill in a form, submit).
Deliverables
- A high-level architecture, described in text or an ASCII diagram.
- A training plan, discussing imitation learning versus reinforcement learning and how they fit together.
- An evaluation plan for measuring real-world performance.
Hints
Hint 1
Do the arithmetic on a 4K frame: count the vision tokens it would produce and see what that does to your 500 ms budget before choosing a resolution.
Hint 2
Think about combining both inputs: a pruned list of interactive elements with IDs, plus a downscaled screenshot annotated with those IDs, and a fallback for apps that expose no accessibility data.
Hint 3
Compounding error is the core reason a flat policy fails on long tasks. Consider a slow planner at sub-goal boundaries, a small fast controller per step, and a verifier that detects stuck or looping behavior.
Hint 4
For safety, separate the model from the executor: put a policy layer between them that classifies actions by reversibility and requires confirmation or blocks the risky ones. Train and test in resettable sandboxes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and numbers
State assumptions first: a single-user desktop (Windows, macOS, or Linux) running web and native apps, tasks of roughly 5-50 steps, and a target of about 70% success on common workflows. The model may run in the cloud, or locally for privacy-sensitive users.
Token math. A 4K frame has about 8.3M pixels. With 14 px patches that is roughly 42k visual tokens, which cannot be processed within 500 ms. Downscaling to about 1280x720 and merging 2x2 patches gives around 1.2k tokens, which is feasible.
Latency budget per step (about 410 ms):
| Stage | Time |
|---|---|
| Screen capture | ~20 ms |
| Accessibility-tree extraction and pruning | ~40 ms |
| Prefill (~1.2k image + ~1.5k text tokens) | ~150 ms |
| Decode (~30 action tokens) | ~150 ms |
| Safety check | ~30 ms |
| Execution | ~20 ms |
The consequence is that the per-step model must be small (around 7B parameters, quantized). A larger model can be used for planning, but only at sub-goal boundaries where 1-3 s is acceptable.
2. Architecture
User task -> Planner (large VLM) -> sub-goals -> Controller (small VLM)
^ |
| action JSON
Verifier <- observation <- Executor <- Safety policy engine
^ |
+-- Perception <-- screenshot + a11y tree
(wait-for-stable) Audit log / replay store
Loop: perceive -> act -> gate -> execute -> verify. The verifier decides whether the sub-goal is complete, still in progress, or failed; failure triggers a replan.
3. Perception
| Screenshot | Accessibility tree / DOM | |
|---|---|---|
| Coverage | Universal (canvas, remote desktops, images) | Missing or wrong in many native, Electron, canvas apps |
| Semantics | Must be inferred | Explicit roles, names, states |
| Size | ~1.2k tokens after downscale | Raw DOM can be 10k-100k tokens |
| Grounding | Coordinates are imprecise | Exact bounding boxes |
| Visual state | Sees disabled buttons, modals, layout | Can be stale |
Recommendation: hybrid, "set-of-marks" style. Prune the tree to visible, interactive elements (typically 100-300), assign IDs, draw numbered boxes on the downscaled screenshot, and also give a compact text list such as [17] button "Search flights" (enabled). The model reasons visually but acts on exact targets. When the tree is empty or untrustworthy, run a fast UI parser (OCR plus an element/icon detector, ~30 ms) to synthesize the marks.
4. Decision making
A purely reactive policy breaks on long tasks: errors compound (95% per-step accuracy gives only ~21% over 30 steps), context grows unboundedly, and it cannot tell it is looping. Use a hierarchy:
- Planner: breaks the task into sub-goals ("open airline site -> set destination and dates -> choose flight -> stop before payment and confirm"), and keeps a scratchpad of extracted facts (prices, email content).
- Controller: sees the current sub-goal, current observation, the last 3-5 actions as text, and at most the previous screenshot. Bounded context keeps latency stable.
- Verifier: checks postconditions ("date field shows Jun 12"), detects no-op actions via screen diff, and detects loops. After repeated failure it escalates so the planner can backtrack or choose another route.
5. Action space and OS mapping
The controller emits structured actions, for example click(id), click(x, y) in normalized [0,1] coordinates, type(text), key(combo), scroll, drag, wait, ask_user(question), and done(result).
- Element IDs resolve to the bounding-box center; they survive layout shifts best.
- Normalized coordinates are converted to physical pixels, handling DPI scaling and multi-monitor offsets.
- Two-stage grounding for 4K: predict coarsely on the downscaled frame, then crop a ~512x512 native-resolution patch around the point and refine. Small targets get precision without full-resolution cost.
- Inject input with OS APIs (SendInput, CGEvent, uinput/xdotool).
- After each action, wait for stability (pixel diff settles, network idle, focus change) instead of fixed sleeps.
6. Training
- Grounding pretraining. Render many pages at varied resolutions, zoom levels, and themes. The DOM yields free (screenshot, description, box) labels; add native apps via accessibility APIs plus OCR/captioning data.
- Imitation learning (SFT). Human demonstrations aligned to element IDs, plus synthetic trajectories where a strong agent attempts LLM-generated tasks and only programmatically verified successes are kept. Add brief rationales; train the planner on task-to-sub-goal data.
- Recovery data (DAgger-style). Run the policy, let it drift, and label correct recovery actions. Pure behavior cloning never sees its own mistakes.
- Online RL. Thousands of snapshot-resettable VMs with verifiable rewards (file saved correctly, mock database contains the booking). Reward = success - lambda x steps - large penalty for safety violations, optimized with PPO/GRPO-style methods, then distilled into the small controller.
Trade-off: imitation is stable and cheap but capped by demo quality; RL exceeds it but needs reliable verifiers and a good sandbox, and risks reward hacking.
7. Robustness and safety
Robustness
- Target elements by role and name rather than absolute position; re-observe after every action.
- Augment training with layout, theme, language, and popup variation (cookie banners, update dialogs).
- Use the verifier plus bounded retries, then backtrack or ask the user.
Safety
- A policy engine sits between model and executor, independent of the model so it cannot be talked out of its rules.
- Classify actions by reversibility and blast radius: read-only actions pass; reversible edits are allowed and logged; irreversible ones (delete, send, pay, change permissions) need explicit user confirmation or are blocked.
- Use allowlists of apps and domains, run in a sandbox or separate user session where possible, and prefer moving files to trash over deletion.
- Defend against prompt injection: treat on-screen text as data, never as instructions, and flag content that tries to redirect the task.
- Keep full audit logs and replayable traces; add a visible kill switch.
8. Evaluation
- Offline: grounding accuracy (click lands inside the correct box), single-step action accuracy on held-out apps and resolutions.
- Sandbox benchmarks: end-to-end task success on resettable environments with programmatic checkers, broken down by task length and app type; also steps-to-completion and recovery rate.
- Safety: red-team suites with destructive prompts and injected pages; track the rate of unauthorized irreversible actions (target near zero) and the false-confirmation rate (user annoyance).
- Latency: p50/p95 per-step time at 1080p and 4K.
- Online: staged rollout with shadow mode, then opt-in users; monitor success, abandonment, user takeovers, and confirmation acceptance.
Common mistakes
- Feeding full-resolution 4K frames or the raw DOM into the model and ignoring latency.
- Relying on a flat reactive policy for long tasks.
- Using only behavior cloning, with no recovery data.
- Enforcing safety through the prompt alone instead of an external policy layer.
- Evaluating only on static benchmarks and never on perturbed, non-deterministic environments.