On this page

Every interactive family registers itself with an agent registry when it is mounted under an AgentProvider. An agent, or a test, then reads what is on screen and acts on it through the actions touch uses. The family sees details.source === "agent", so your handlers can treat agents differently, and the agent gets a status for every step.

Set up a registry

Create one registry for the app (or one per screen, as the example app does), provide it to a screen with a route key, and tell it which route is in front.

import { useLayoutEffect, useState, type ReactNode } from "react";
import { AgentProvider, createAgentRegistry } from "nitro-ui-sdk/agent";

export function AgentScreen({ route, focused, children }: { route: string; focused: boolean; children: ReactNode }) {
  const [registry] = useState(createAgentRegistry);

  useLayoutEffect(() => {
    registry.setForeground(focused ? route : null);
  }, [registry, route, focused]);

  return (
    <AgentProvider registry={registry} route={route}>
      {children}
    </AgentProvider>
  );
}

Only controls on the foreground route get refs. When the route leaves the foreground, its refs are dropped; when it returns, its controls get new refs.

Snapshot

registry.snapshot() lists every control on the foreground route:

registry.snapshot();
// [
//   { ref: "control.1.3", component: "Switch", role: "switch", name: "Wi-Fi",
//     scope: "network", value: true, state: { disabled: false, checked: true },
//     actions: [{ name: "setChecked", confirm: false }, { name: "toggle", confirm: false }] },
//   { ref: "control.1.4", component: "Button", role: "button", name: "Forget network",
//     scope: "network", state: { disabled: false, busy: false },
//     actions: [{ name: "press", confirm: true }] },
// ]
Field Meaning
ref The handle for act. Valid until the control unmounts, rebinds or leaves the foreground.
component, role, name What it is and its accessible name (usually the label prop, or title / item label on families such as Sheet and Tabs).
scope The innermost AgentScope id, or the route.
value, range, text, options The current value, a slider’s range, visible text and a picker’s options.
state disabled, selected, checked, busy where they apply.
actions Action names, and whether each needs a person’s confirmation. Disabled and busy controls list none.

Query

registry.query({ within, role, name, text }) filters the snapshot. name and text match case-insensitively and also match option names; within matches a route or any enclosing scope.

registry.query({ role: "button", name: "forget" });
registry.query({ within: "network" });
registry.query({ text: "Berlin" }); // finds a Select whose options include Berlin

Act

registry.act({ steps }) runs steps in order and stops at the first one that is not accepted. It returns one result per step it ran. Always pass refs returned by snapshot() or query() rather than hard-coding generated ref strings:

const [wifi] = registry.query({ role: "switch", name: "wi-fi" });
const [forget] = registry.query({ role: "button", name: "forget" });

if (wifi && forget) {
  const results = await registry.act({
    steps: [
      { ref: wifi.ref, action: "setChecked", args: false },
      { ref: forget.ref, action: "press" },
    ],
  });

  const [wifiResult, forgetResult] = results;
  if (wifiResult?.status !== "accepted") {
    // Step 1 did not succeed (for example "refused" or "disabled"), so step 2 was skipped
    // and `forgetResult` is undefined.
  } else if (forgetResult?.status === "accepted") {
    // The person approved the prompt and the button accepted and dispatched `onPress`.
    // If `onPress` starts async work (such as a payment or network request), `accepted`
    // only means the handler was dispatched—check a later snapshot or app state to verify
    // that the async work completed without rejecting.
  } else {
    // `forgetResult?.status` tells you why step 2 did not run or succeed:
    // - "cancelled": the person declined the confirmation prompt
    // - "disabled" / "refused" / "unavailable" / "failed": even after approval, the button
    //   became disabled/busy, its handler refused the action, the action disappeared, or it threw
    // - "stale-ref": the button unmounted or left the foreground while waiting
    // - "confirmation-required": no confirmation handler is set or another prompt is open
  }
}
Status Meaning
accepted The control accepted and dispatched the action (or the value already matched). For synchronous controlled changes, the owner committed the new value; for async handlers such as a button’s onPress returning a promise, accepted reports dispatch only—not that the async work completed or succeeded.
requested A custom action returned "requested" directly without settling via useSettleChange().
disabled The control is disabled or busy.
refused A handler declined it, or a controlled owner kept the old value.
unavailable The control has no such action, or the action is not allowed.
stale-ref The ref no longer points at a mounted control in front. Take a new snapshot.
invalid-step, invalid-arguments The step or its args failed validation.
confirmation-required, cancelled No confirmation handler is configured, another confirmation is already pending, or the person declined it.
failed The action threw.

Arguments are validated at runtime by each action’s guard (action(accepts, run)), because agents do not run the type checker.

Scopes

AgentScope groups controls so an agent can query within them, and marks whole regions as secret or hidden from agents.

import { AgentScope } from "nitro-ui-sdk/agent";
import { Button } from "nitro-ui-sdk/button";
import { TextField } from "nitro-ui-sdk/text-field";

<AgentScope id="billing">
  <AgentScope id="card" secret>
    <TextField.Root label="Card number" />
    <TextField.Root label="CVC" />
  </AgentScope>
</AgentScope>;

<AgentScope id="debug" discoverable={false}>
  <Button.Root label="Reset cache" onPress={() => {}} />
</AgentScope>;

Secrets are redacted

A secret control (SecureField, or anything inside a secret scope) reports value: "[redacted]", no text, range or options, and only disabled and busy in its state. The only action an agent may run on it is focus. Queries never match its hidden text.

Destructive actions need a person

Mark the final delete, pay or send action with a localized confirm. When an agent runs it, the registry shows a native confirmation that only a person can approve; the action runs only if they do.

<Button.Root
  label="Delete account"
  confirm={{ message: "Delete this account?", approveLabel: "Delete", cancelLabel: "Cancel" }}
  onPress={() => deleteAccount()}
/>

The snapshot lists the action with confirm: true. While a confirmation is open, other steps return confirmation-required. If the control unmounts or leaves the foreground before the person answers, the step returns stale-ref and nothing runs. Touch presses never ask: the person is already the one pressing.

Presentations

Sheets, dialogs and other presentations cover the screen behind them. Wrap their content in AgentPresentation so their controls register in the foreground while the covered route is suspended; the kit’s presenting families (Dialog, Sheet, Menu, Select and DatePicker today) do this for you.

Registering a custom control

Custom controls register with useAgentControl. Describe the control and its actions; read the latest props inside run, which the registry calls with the "agent" source.

import { action, noArgs, useAgentControl } from "nitro-ui-sdk/agent";

function useFavoriteAgent(id: string, favorite: boolean, toggle: (source: "agent") => "accepted" | "refused") {
  useAgentControl(id, {
    component: "FavoriteButton",
    role: "button",
    name: favorite ? "Remove from favorites" : "Add to favorites",
    state: { selected: favorite },
    actions: { toggle: action(noArgs, (_, source) => toggle(source)) },
  });
}

The first argument is the control’s identity: change it when a reused native cell binds a different record, so old refs go stale.

Testing the contract

nitro-ui-sdk/testing gives a registry and a driver for unit tests, with an injectable confirmation. See Testing.