Task UI Automation API

UI selectors, device accessibility, SDK trees, gestures, keyboard state, and screenshots.

Use ansight.ui, ansight.keyboard, and ansight.screenshots for visible interaction and evidence on the task’s enforced session. See the host method index for every signature. Await calls serially and use a named expect to establish the task’s outcome.

Availability

APISDK modeDevice modeProvider requirement
ansight.ui.find, waitFor, assert, and input actionsYesYesAn available UI capture/input provider; individual gestures depend on the device
ansight.ui.getLiveVisualTreeYesDevice accessibility onlyDevice hierarchy first; SDK framework/native trees are a fallback in SDK mode
ansight.ui.getLiveNavigationStructureCompatible SDK toolUnavailableRegistered framework navigation tool
ansight.ui.getVisualTreeSnapshot, searchVisualTreeYesYesRetained trees in this session
ansight.keyboard.open, isOpenYesYesFresh device accessibility that reports the system keyboard
ansight.keyboard.dismissCompatible SDK toolUnavailable when the keyboard is openFresh keyboard evidence and the Write-enabled ui.dismiss_keyboard app tool
ansight.keyboard.pressYesYesEnter input via ADB, Simulator HID, or Appium/XCUITest
ansight.keyboard.submitCompatible SDK toolUnavailableWrite-enabled ui.submit_keyboard and a focused editor with a submit action
ansight.screenshots.take, capture, getFrameYesYesLive capture for take; a retained frame for getFrame
ansight.screenshots.assertYesUnavailableSupported live screenshot comparison provider
ansight.screenshots.compareYesYesRetained actual frame and a retained frame or workspace reference image
ansight.screenshots.evaluateYesYesRetained actual frame, criteria, and access to the configured AI provider; reference image is optional
app.ui and framework suitesRegistered SDK toolsUnavailableSee App Tool API

Both platforms support virtual and physical UI targets when their providers are configured. An external physical iPhone uses Appium/XCUITest; external Android uses ADB/UIAutomator. See external monitoring prerequisites. Device input support is separate from SDK pairing or app-tool availability.

Device accessibility and SDK trees

ansight.ui.getLiveVisualTree() first attempts the device accessibility hierarchy. In SDK mode, it can fall back to MAUI, React Native, Flutter, Capacitor DOM, or native SDK trees. Supplying toolId or requesting includeProperties: true selects app-provided detail and requires SDK mode. In device mode, unavailable accessibility or app-only tree options reject.

The current declaration still types this method as an AppToolCallResult. The device-accessibility response instead has responseType: "device-accessibility" and payload.result, without the SDK success discriminator. Do not assume every response is "tool.result". Use the typed find, waitFor, and assert results for portable UI checks; inspect the actual envelope when consuming a live tree directly.

UI selectors

UiSelector is shared by find, wait, assert, and UI actions:

interface UiSelector {
  nodeId?: string;
  automationId?: string;
  text?: string;
  role?: string;
  type?: string;
  ancestorAutomationId?: string;
  action?: string;
  visible?: boolean;
  enabled?: boolean;
  exact?: boolean;
  caseSensitive?: boolean;
  index?: number;
}

Use ansight.ui.assert for evidence-producing expectations and waitFor for a bounded state transition. UiAssertArguments additionally supports expectedCount, expectedText, expectedValue, expectedVisible, expectedEnabled, and an optional actionId.

tap, longPress, typeText, swipe, scroll, pinch, and back persist before-and-after evidence and return UiActionResult. runSequence accepts from 1 through 32 already-known coordinate tap, longPress, swipe, pinch, or back actions and returns per-step outcomes plus sequenceEndpoints evidence. Use separate actions when the next step depends on an intermediate screen or when the evidence trail needs a checkpoint around every input.

The includeScreenshot action option controls whether the underlying host result contains final image content. Repository task methods receive structured action and evidence data. Set includeScreenshot: false in a task when inline image transport is unnecessary.

Long press

Use ansight.ui.longPress(args) to press and hold a target, then release it. It accepts the same selectors and coordinates as tap: use a stable automationId, copy a discovered tapHint.selector including its source and fingerprint, or supply both normalizedX and normalizedY.

const held = await ansight.ui.longPress({
  automationId: "RouteCard",
  durationMs: 800,
});
expect(held.performed, { id: "route-card-held" }).toBe(true);

const menu = await ansight.ui.waitFor({
  automationId: "RouteContextMenu",
  condition: "visible",
});
expect(menu.satisfied, { id: "route-menu-visible" }).toBe(true);

durationMs defaults to 800 ms and accepts integers from 500 through 10,000 ms. Invalid durations are rejected. The press remains stationary until release. The result uses capability ui.long_press and includes before-and-after evidence. Check the resulting UI to verify the app’s response.

Long press supports Android emulators and physical devices through ADB, iOS Simulator through HID, and physical iOS through Appium/XCUITest. The corresponding input and capture providers must be configured.

Already-known coordinate holds can be included in a sequence:

await ansight.ui.runSequence({
  actions: [
    { kind: "longPress", normalizedX: 0.4, normalizedY: 0.6, durationMs: 1200 },
  ],
});

An app execute agent can load the gestures tool bundle and use ansight_long_press_ui with the same target and duration options. The direct CLI command is ansight ui long-press. Task extraction preserves recorded long presses with stable targets and their hold durations.

Software keyboard

ansight.keyboard.open(args) accepts the same stable selector fields as other targeted UI actions. It focuses the selected text input and verifies the opened keyboard through fresh device accessibility evidence. isOpen() performs a fresh read without input. dismiss(args?) is idempotent: when the keyboard is open, it calls the SDK’s ui.dismiss_keyboard tool to dismiss the app’s input method, then verifies that it closed. It never sends Back, even if keyboard visibility changes between observation and dispatch. An already-closed keyboard needs no input action. Apps must enable the UI tool suite and Write access; older SDKs or device-only sessions without that tool fail with an explicit capability message.

Keyboard state is intentionally unavailable when the host cannot capture a device accessibility hierarchy that reports system keyboard presence. The methods fail explicitly in that case instead of inferring visibility from a focused text field or returning an unverified success.

Screenshots and assertions

Use ansight.screenshots.capture(args?) for a persisted live capture with a flat result, ansight.screenshots.take(args?) for the existing app-tool envelope, ansight.screenshots.getFrame(args?) for retained frames, and ansight.screenshots.assert(args?) for an SDK-mode comparison with a baseline. Keep a named assertion on the comparison result; taking a screenshot alone does not make a task pass. Exact options and result fields are in the task declaration.

Enter and editor submission

await ansight.keyboard.press({ key: "Enter" });
await ansight.keyboard.submit();

Choose one operation for the intended interaction. press sends a literal Enter through host device input and can insert a newline in a multiline editor. submit invokes the focused editor’s configured action; it never falls back to a key or newline. It requires an updated SDK with Write-enabled ui.submit_keyboard. Android uses the input connection’s advertised editor action. UIKit and .NET iOS invoke the focused text field’s Return handler; React Native uses those native input adapters. Flutter invokes EditableTextState.performAction. Capacitor DOM tools with allowActions: true use the focused input’s form requestSubmit, including browser validation. Missing focus, an unsupported editor, or a newline-only editor produces an explicit error. A dispatched action does not prove that the app accepted the submission: wait for and assert the expected UI or domain state afterward.

The host retains these issued actions in the session so that task extraction can reproduce Enter and submit in order. This requires a new recording with an updated host. It does not add listeners to app controls or claim to record manually pressed IME Search/Done keys.

Capture-time system UI metadata

Updated SDK screenshot options include includeSystemUiMetadata, default true. It controls metadata collection, not masking. Set it to false on capture or take to retain only the image; SDK periodic and annotation screenshot options have their own independent setting (IncludeSystemUiMetadata in .NET).

const image = await ansight.screenshots.capture({
  format: "png", includeSystemUiMetadata: true,
});
const comparison = await ansight.screenshots.compare({
  image: { frameId: image.frameId },
  reference: { workspacePath: "references/home.png" },
  ignoreSystemUi: ["statusBar", "navigationBar"],
});
expect(comparison.passed, { id: "home-matches" }).toBe(true);

Capture results and retained frames expose optional geometry with normalized safe-area insets, a capture target, and present, absent or unknown entries for statusBar, navigationBar and displayCutout. compare and assert resolve ignoreSystemUi from the actual frame and retain systemUiMaskResolutions for review. Present entries add masks; absent entries add none. Unknown/missing geometry raises screenshot_geometry_unavailable; capture with metadata enabled, upgrade the provider, or supply explicit ignoreRegions. Old recordings and external device captures may have no geometry. assert rejects metadata opt-out with requested system masks before capture.

App-window renderers exclude OS status/navigation glyphs, even when the app has nonzero safe-area insets. Those insets must not hide the app’s top row. Exact iOS cutout bounds remain unknown. App-drawn clocks and arbitrary overlays need explicit rectangles. Manual and system masks share a 64-rectangle limit; overlapping pixels count once, and excluding the entire image is an error. Metadata is additive; no new workspace schema version or recording migration is required.

Retained screenshot baselines

const baseline = await ansight.screenshots.capture({ format: "png" });
const frame = await ansight.screenshots.getFrame({ frameId: baseline.frameId });
const comparison = await ansight.screenshots.assert({ baselineFrameId: baseline.frameId });
expect(comparison.passed, { id: "screen-unchanged" }).toBe(true);

Both capture and take store the image in the session, so the frame remains usable after the temporary transfer artifact is removed and is included in session archives. capture returns frameId, artifactPath, format, width, height, capturedAtUtc, and sha256. take retains its existing envelope and adds frameId to the result. A completed comparison returns passed: false on mismatch and retains the compared image as currentFrameId; the named expect determines task failure. Missing baselines, capture errors, and transport errors still throw. assert baselines belong to the same session. Use compare for reusable workspace reference images.

Direct task runs keep the continuous screenshot capture profile active during JavaScript waits and tool calls. Completion, failure, and cancellation release that scope and restore the normal recording cadence. SDK-managed capture remains under the SDK’s capture policy.

Compare against a workspace reference

Keep expected images under the app’s ansight/ directory, for example ansight/references/cubes.png. workspacePath is relative to that directory. The caller’s task workspace takes precedence over the app’s registered codebase. Absolute paths, traversal and symbolic links below the workspace root are rejected. PNG and JPEG inputs are supported up to 32 MiB and 16 megapixels; normalize EXIF orientation first. Prefer PNG when checking pixel differences.

const image = await ansight.screenshots.capture({ format: "png", maxWidth: 1024 });
const comparison = await ansight.screenshots.compare({
  image: { frameId: image.frameId },
  reference: { workspacePath: "references/cubes.png" },
  pixelThreshold: 16,
  maxDifferenceRatio: 0.01,
});
expect(comparison.passed, { id: "reference-image", message: comparison.message }).toBe(true);

compare reads the exact retained actual frame; it does not capture another screen. A reference can also be { frameId: "..." } from the same session. It copies both input images and their SHA-256 hashes into retained session artifacts, so changing the workspace image later does not change the evidence for an earlier run.

Dimensions must match by default. A mismatch returns status: "dimension-mismatch" and passed: false, without pixel statistics. Set resizeToReference: true to explicitly allow stretching the actual image to the reference’s proportions. maxWidth limits comparison resolution (default 1024, range 64–4096). The pixel algorithm compares RGBA channels: a pixel changes if its largest channel difference is strictly greater than pixelThreshold (default 16). The comparison passes when the changed-pixel ratio is at most maxDifferenceRatio (default 0.01).

The result includes an overlay highlighting changed pixels, connected changed regions and crops. At most the 64 largest regions are returned; regionCount and regionsTruncated disclose omissions, and every changed pixel still contributes to the score. Wait for the expected UI state before capturing; comparison does not settle animations or identify dynamic content automatically.

Ignore clocks and other dynamic areas

Both pixel APIs, screenshots.compare and screenshots.assert, accept ignoreRegions. Use explicit rectangles for clocks, timestamps, cursors or other content whose changes should not affect the result. Coordinates are normalized from 0 to 1 relative to the full actual image, with the origin at the top left. For example, this excludes the rightmost 20% of the top 5% of the image:

import type { TaskInvocation } from "./ansight-task.d.ts";

export default async function run({ ansight, expect }: TaskInvocation) {
  const image = await ansight.screenshots.capture({ format: "png" });
  const comparison = await ansight.screenshots.compare({
    image: { frameId: image.frameId },
    reference: { workspacePath: "references/cubes.png" },
    ignoreRegions: [{ x: 0.8, y: 0, width: 0.2, height: 0.05 }],
    maxDifferenceRatio: 0.01,
  });
  expect(comparison.passed, { id: "scene-matches", message: comparison.message }).toBe(true);
}

Up to 64 rectangles are supported. Each must have finite coordinates, positive width and height, and fit entirely within the image. The same normalized areas are excluded from actual and reference after resizing; edges round outward to comparison pixels, so even a very small rectangle masks at least one pixel. Overlapping areas count once.

Ignored pixels are excluded from differentPixelCount, totalPixelCount, differenceRatio, meanChannelDifference, difference highlights and detected changed regions. totalPixelCount is the number of unmasked pixels; ignoredPixelCount reports the excluded count at comparison resolution. For example, 100 changed pixels with 1,900 pixels ignored in a 100 × 100 image gives 100 / 8100, not 100 / 10000. A mask that covers every pixel at comparison resolution returns an error rather than passing an empty comparison. Omit the option or pass [] to compare the whole image.

Results record ignoreRegions; compare also retains them and the counts in result.json. For compare results, the player shows ignored areas with dashed, hatched rectangles and reports the excluded pixel count. Show ignored areas toggles those guides without changing the comparison. Original images and crops remain unredacted: masks affect comparison scoring, not image storage. evaluate does not use pixel masks; provide semantic criteria for what that assessment should consider.

Evaluate image content, optionally against an expected image

evaluate explicitly sends the selected actual image, optional reference and criteria to the existing configured AI provider, using its normal authorization and metering. Pixel compare runs locally and makes no model request. Both work with frames from any SDK stack and external device captures.

const assessment = await ansight.screenshots.evaluate({
  image: { frameId: image.frameId },
  reference: { workspacePath: "references/cubes.png" }, // Optional expected image.
  reasoning: "fast",
  criteria: [
    {
      id: "cube-count",
      description: "Exactly three cubes are visible, arranged as in the reference.",
      count: { label: "cube", equals: 3 },
    },
    {
      id: "purple-count",
      description: "Exactly two cubes are purple.",
      count: { label: "cube", attributes: { color: "purple" }, equals: 2 },
    },
  ],
});
expect(assessment.passed, { id: "cube-scene", message: assessment.message }).toBe(true);

Omit reference for criteria against the actual image alone, or use a retained reference frameId. Images are labelled REFERENCE (expected) and ACTUAL; all returned object bounds refer to ACTUAL. They are sent as full images, downscaled proportionally to at most 1536 pixels on the longest side. The original inputs are retained. Evaluation is one bounded, read-only model request with no app action tools, a two-minute limit, up to 16 criteria and up to 64 detected objects. A shorter task timeout still applies. reasoning uses fast (default), balanced or deep; an optional teamId selects the billing team.

Each criterion returns pass, fail or inconclusive, an evidence explanation and region IDs. Optional count rules are checked by host code over detected objects; labels and attribute values match case-insensitively, with exact attribute keys. The host never promotes uncertain visual evidence to a pass. Model recognition and boxes are approximate; ambiguous scenes and incomplete/malformed model responses are inconclusive. passed is true only when every criterion passes. Missing files, provider failures and authorization failures throw; completed assessments return data and a named expect determines task failure.

Results retain requested criteria, model/configuration identity, token usage, the model response and the original images. evidence points to the saved result.json, and image/overlay/crop references contain snapshotId and path for ansight.artifacts.readFile. Artifacts are included when exporting session artifacts.

Reuse regions as annotations

Both methods return regions with an ID, label, source (pixel-difference or semantic), a crop preview (at most 512 pixels on its longest side) and geometry. Geometry uses normalized coordinates in the full original actual frame, even when comparison or model input was resized. Finding a region does not automatically create an annotation.

await ansight.annotations.create({
  label: "Cube assessment",
  notes: assessment.message,
  geometries: assessment.regions.map(region => region.geometry),
});

In the local player’s recorded task API calls, select a comparison or assessment to see expected/actual images, the difference overlay and findings. Selecting a finding highlights its regions and shows their crops; Annotate selected regions saves those shapes onto the original session frame. Keep trace capture enabled for this view. Retained artifacts remain available independently of the call trace.

Pencil input playback

Use ansight.ui.playPen to await a bounded .pen.json file or in-memory sample sequence on iOS Simulator. hid+sdk uses the optional native Pencil package and a native target; sdk uses a bound Flutter, React Native or Capacitor surface. The host owns preparation, sample arming, dispatch and cleanup. Capture is optional for playback; enable it when asserting retained evidence.

const playback = await ansight.ui.playPen({
  file: "ansight/fixtures/drawing.pen.json",
  mode: "sdk",
  target: "drawing-canvas",
});
expect(playback.performed, { id: "pen-delivered" }).toBe(true);

See Pencil input files and delivery modes and the consumer integration guides. A successful transport result does not prove rendered output or drawing-library compatibility.