Computer-Use and Browser Agents › The control loop
Language AI HandbookAll chapters The application yields a fresh observation on each control round, gets a proposal, validates it and records the result. Consequential operations are separately bounded by a trusted grant supplied outside the view. Here the grant can allow a set of task IDs to be marked done and a different set to be archived. The caller constructs that grant from a known authorization decision. The policy cannot expand it through a proposal or page content.
If a click comes from an older epoch, return a stale outcome. For a current proposal, require the action type and element reference to match the local schema. Reject disabled controls. Resolve the operation and target through the current trusted map and check the applicable write grant before mutating a task. A successful click, including a view change, invalidates the old map.
PythonIn [17]Expand
@dataclass(frozen=True)
class Grant:
done: frozenset[int] = frozenset()
archive: frozenset[int] = frozenset()
def execute(app, action, grant):
"""Apply recognized operations via the current runtime-owned map."""
if not isinstance(action, Action) or type(action.epoch) is not int:
return "invalid"
if action.epoch != app.epoch:
return "stale"
if action.kind == "reobserve" and action.element_id is None:
return "observe"
if (
action.kind != "click"
or type(action.element_id) is not int
or action.element_id not in app.controls
):
return "invalid"
op, task, enabled = app.controls[action.element_id]
if not enabled:
return "disabled"
if op in {"ask_archive", "archive"} and task not in grant.archive:
return "denied"
if op == "done" and task not in grant.done:
return "denied"
if op == "open":
app.selected = task
app.page = "detail"
elif op == "back":
app.selected = None
app.page = "tasks"
elif op == "ask_archive":
app.page = "confirm"
elif op == "cancel":
app.page = "detail"
elif op == "archive":
app.tasks[task] = "archived"
app.selected = None
app.page = "tasks"
elif op == "done":
app.tasks[task] = "done"
# Any accepted click invalidates the entire previous action map.
app.epoch += 1
app.controls = {}
return opThe episode ends when its trusted success predicate holds, a policy abstains, a write is denied, or a budget is reached. It passes the outcome history to the policy so the next observation can be interpreted against the prior result. Budgets count proposals across an episode. A call that observes no change is still work for the UI, policy and wrapper.
PythonIn [18]Expand
def run_episode(app, policy, grant, predicate, budget=12, max_recoveries=2):
outcomes = []
recoveries_remaining = max_recoveries
for _ in range(budget):
if predicate(app):
break
obs = render(app)
action = policy(obs, tuple(outcomes))
if action is None:
break
outcome = execute(app, action, grant)
outcomes.append(outcome)
if outcome == "denied":
break
if outcome in {"stale", "invalid", "disabled", "observe"}:
if recoveries_remaining == 0:
break
recoveries_remaining -= 1
return predicate(app), tuple(outcomes)Archive task 2 by choosing its row, opening the confirmation and selecting the action supported by the current view. Confirm the task’s stored status through the outcome predicate. A click on Cancel can also succeed as an interaction. It does not reach the requested task state.
PythonIn [19]Expand
def archive_policy(obs, history):
if obs.page == "tasks":
return choose(obs, "Open task 2")
if obs.page == "detail":
return choose(obs, "Archive")
return choose(obs, "Archive task", "Confirm archive")
archive_two = Grant(archive=frozenset({2}))
archived_two = lambda app: app.tasks[2] == "archived"
success, outcomes = run_episode(
MockApp(), archive_policy, archive_two, archived_two
)ConsoleOut [20]Expand
Canonical task complete: True | outcomes: ('open', 'ask_archive', 'archive')Give the policy enough context to refuse
Role filtering is a convenient first pass. It is possible to rank candidates after discarding controls that cannot support the requested interaction. The exact domain still matters. An HTML input can be readonly, a field can be present but covered, or a web component can expose a button role on a visual surface that responds to keyboard interaction differently. A role is a candidate feature. The runtime still needs to validate what it can execute now.
For a task list, preserve record anchors such as a row key or the task title and its surrounding region. A common UI shows both a “Mark done” button in a floating toolbar and a similarly named button in a task detail panel. If a policy only receives button labels, either could be selected. Include the relationship “this control belongs to task 2,” when the adapter can verify it, rather than relying on reading order. The toy embeds task numbers in the open-row labels. The dispatcher holds the actual target task ID.
A score threshold handles weak matches. It does not handle ties without a separate outcome rule, and a high score does not prevent a false match. A case-folded bag-of-terms scorer treats a repeated word as one term. It can put “Archive task 2,” “Task 2 archive” and “Do not archive task 2” closer than an application wants. Restrict the toy to labels whose meaning is represented by its small vocabulary. Use ambiguity and unknown wording as distinct checks in policy evaluation.
For a more complex system, record the difference between candidate recall and final grounding accuracy. Candidate recall asks if at least one identifiable correct control was available in the returned candidate set. Final accuracy asks if the policy selected the correct one under the intended setting. The second metric cannot tell you by itself whether a matcher missed the correct item or a ranker ignored it. A two-stage search can help recall and then rerank, but compare its latency, output consistency and failure distribution against a simpler condition.
The fixture’s three archive phases make different assertions. The list view needs the exact row. The detail view needs the archive affordance for that row. The confirmation needs the intended effect in the current dialog. Each step can have the expected textual label and still be wrong if it belongs to another target. Check whether the selected record was preserved across view changes, and distinguish that validation from matching the text on a newly rendered button.
Define the boundary around a proposed action
It helps to name the moments in the runtime explicitly. First comes parsing, which reads input under the action schema. Then comes validation, which checks current reference, supported affordance and scope. Execution changes state only for accepted operations. Verification reads a trusted postcondition when the result matters. A runtime can emit different outcomes for each boundary. The categories are valuable even though the operations happen immediately in the local fixture.
| Decision | Example failure | Evidence to collect |
|---|---|---|
| Parse | Element reference has the wrong type | Schema failure category |
| Resolve | Current view no longer contains the intended control | View/epoch and target lookup result |
| Authorize | The operation targets a different task than the grant | Outcome and task-bound authority provenance |
| Execute | A control interaction failed on the local app | Operation result and whether an effect is known |
| Verify | The accepted interaction did not reach the goal | Before/after record state and task predicate |
The runtime should not substitute a nearby target on an invalid reference. That would convert an invalid-action count into a real action on an unintended record and deprive the policy of the reason to recover. Likewise, treat the operation chosen by a human-visible confirmation button and the authorization supplied by the application as different fields. The confirmation display does not reveal the exact terms under which the user approved a write.
A grant in the toy is passed as an immutable object by the trusted application. It allows record-level operation decisions. A system with multiple simultaneous actors may need grants that also bind account, resource version, or a time window. Verify the grant at the action boundary, not just when a long-running task begins. If the current user or target changes during the run, establish what consequences previously accepted actions had and which future actions are still allowed.
Demonstrate guard ordering with harmless local state
The following local trace starts with task 2 already completed and checks the enabled-state rejection. A second proposal tries to reuse an old view reference after rendering again. Unlike a missing-reference check, the epoch check catches the reusable integer even if the current map still contains the same numeric ID. Both checks run against an in-memory object.
PythonIn [21]Expand
def guard_probe():
local = MockApp()
local.tasks[2] = "done"
view = render(local)
open_task = choose(view, "Open task 2")
opened = execute(local, open_task, Grant())
detail = render(local)
done = next(e for e in detail.elements if e.name == "Mark done")
disabled = execute(
local,
Action(detail.epoch, "click", done.id),
Grant(done=frozenset({2})),
)
stale = execute(local, open_task, Grant())
return opened, disabled, stale, local.tasks[2]ConsoleOut [22]Expand
Open, disabled, stale, final: ('open', 'disabled', 'stale', 'done')The outcome is open, disabled, stale and done. The attempted action on a disabled control did not change the task. The stale reference never reaches the current map lookup. This matters because accepting a guessed epoch with an old reference can yield an action with a valid current index and a different meaning. The mock cannot guarantee that a caller chose an ID for the reason it claims. It can validate the reference and enforce the resulting operation under trusted permissions.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!