diff --git a/README.md b/README.md index ceacfc69..de818f7c 100644 --- a/README.md +++ b/README.md @@ -486,6 +486,8 @@ The settle does not wait for a screen that is slow to appear. On Android, the fi On mobile, each observation, `describe_screen`, `list_testids` and `accessibility_snapshot` takes one device snapshot (plus the settle retries above). The consumer's `DeviceBackend` takes the snapshot. With the `@metamask/device-mcp` ADB backend (0.6.0 or later), Android snapshots use a signed test-only helper APK by default (`helper-first`). The backend installs it on the device the first time, so the first snapshot takes longer. To use only `uiautomator dump`, set `DEVICE_MCP_ADB_SNAPSHOT=dump` or the backend's `adb.snapshotMode` option. See the device-mcp README. The viewport for `visible` comes from the snapshot's root frames; the device window size is read at most once per session (and not refreshed after a rotation), only when a snapshot has no root frame. Elements that are not part of the app are removed from the tree, the refs, the test IDs and `generate_locators`: on Android, the system status bar and navigation bar windows (a full-width or full-height bar window whose ids are all `com.android.systemui:id/*`; other System UI windows such as the biometric prompt stay); on both platforms, the Expo DevLauncher "Tools" button of development builds (iOS `gearshape.fill` and its "Tools" text). Pass `{ excludeDevOverlay: false }` as the third `MobilePlatformDriver` argument to keep the DevLauncher button. Taps and waits inside `@metamask/device-mcp` still search the whole snapshot. +The `warnings` of the device snapshot (`SnapshotResult.warnings` of `@metamask/device-mcp`) are returned as a top-level `warnings` array in `describe_screen`, `accessibility_snapshot` and observations (also diff observations). There is no `warnings` key when the snapshot has none. Each entry is the device-mcp warning (a code and its details), followed for a known code by what to do. On iOS, `ax-tree-truncated(backend=,depth=,nodes=)` means the idb accessibility read stopped at its size bound, so elements on screen can be missing from `a11y`, `testIds` and the element search of the target tools. `ax-tree-fallback(from=,to=,reason=)` means the preferred read failed and the other backend served the tree; with `from=axbridge,to=ax` (the full read fails on a very deep screen) the tree is the flat read, where labelled controls usually remain but containers, screen markers and the text parts of rows are missing. For `ax-tree-truncated` the added text tells the agent to look with `screenshot` and tap with `tap_coordinates`; for `ax-tree-fallback` it also says that `wait_for` on a missing container can time out, and to confirm the screen with a control that is present. + The mobile accessibility tree (`describe_screen`, `accessibility_snapshot`, observations) is a flat list in pre-order with no `path` (on the browser, `path` holds the `role:name` of the ancestor dialogs and headings; on mobile the ancestors are native view classes). Layout-only elements are left out (`pruneLayoutOnly` in `src/platform/mobile-hierarchy.ts`): an element with no label, no value, no identifier, and a type that is not a control or a progress indicator. Its kept descendants take its place, in order. Controls are iOS `Button`, `Link`, `TextField`, `SecureTextField`, `SearchField`, `TextView`, `TextArea`, `Switch`, `Toggle`, `Slider`, `Stepper`, `Picker`, `Cell`, `Tab`, `MenuItem` and similar AX types (exact match, without the `XCUIElementType` prefix), and Android classes ending in `Button`, `EditText`, `CheckBox`, `CheckedTextView`, `Switch`, `SeekBar`, `Spinner`, `RatingBar` and similar. The device snapshot has no `clickable` flag, so a layout-only plain React Native view (`RCTViewComponentView` on iOS, `android.view.ViewGroup` on Android) that has no kept children and is at least 24×24 (iOS points, Android pixels) stays as an unlabelled tap target, for example the iOS wallet home action buttons. Node `bounds` are `{ x, y, width, height }`, in that key order. Node refs number the kept nodes only, and ambiguity is computed over them. A node with a testId, label or value that no other kept node shares resolves by that identity: the target tools look it up again at action time. Two other kinds of node get a bounds ref (their snapshot frame and identity) instead: unnamed nodes (unlabelled tap targets, progress indicators, unnamed controls), and `ambiguous` nodes (another kept node has the same testId, or the same label or value and type, so a lookup could find the other one). Only `click` takes a bounds ref: it takes a new snapshot, finds the element with the same type and identity at the same frame (1 pt/px tolerance), and taps it through the same viewport check and hit test as any other mobile tap; the result's `target` ends in ` (bounds)`. When no such element is there any more (the screen changed), it fails with `MM_TARGET_NOT_FOUND` and taps nothing. `type`, `wait_for`, `get_text`, `scroll_to_element` and `long_press` (also as `run_steps` steps) refuse a bounds ref with `MM_TARGET_NOT_FOUND` before any device call; the error's `hint` names `click` and `tap_coordinates` (unnamed) or a unique test ID (ambiguous). On real MetaMask screens: iOS wallet home 177 → 67 nodes (183 kB with `path` → 10 kB), Android wallet home 625 → 242 nodes (649 kB → 35 kB), Android login 47 → 15 nodes. `list_testids` and `generate_locators` are not affected, and `describe_screen` still returns the full `testIds` list next to the tree. ### Session Metadata @@ -564,7 +566,7 @@ All responses follow a consistent shape: ```typescript // Success -{ ok: true, result: T, observations?: { testIds, a11y, animationsSettled? } } +{ ok: true, result: T, observations?: { testIds, a11y, animationsSettled?, warnings? } } // Error { ok: false, error: { code: string, message: string } } @@ -590,7 +592,7 @@ When a call waited for animations, its observation has `animationsSettled`: `tru For `run_steps`, the top-level `observe` sets the level of the one observation collected after the batch. Without it, the `observe` in the last executed step's `args` is used; per-step `observe` on other steps is ignored. `includeObservations` was removed. -Observations contain `testIds`, `a11y` and, when the call waited for animations, `animationsSettled`. They do not include app state; call `get_state` for that. +Observations contain `testIds`, `a11y`, `animationsSettled` when the call waited for animations, and `warnings` when the mobile device read had a problem (see below). They do not include app state; call `get_state` for that. A call that times out is cancelled: its signal is aborted, it stops at its next step, it collects no observation, and its refs are dropped. `click` and `type` check the signal again after they wait for the target, so a call that timed out during that wait does not click or type. An action that already started is not cancelled. On the browser, the action includes Playwright's own checks inside `locator.click` / `locator.fill` (stable, enabled, not covered), which can wait up to the rest of the call's `timeoutMs`. On mobile, `@metamask/device-mcp` takes no signal: its element wait, tap and `typeText` run until they end, and the driver checks the signal between them. diff --git a/SKILL.md b/SKILL.md index 206a93f7..1ae79499 100644 --- a/SKILL.md +++ b/SKILL.md @@ -62,10 +62,18 @@ mm get-state --observe full # a read that also returns an observation - `animationsSettled: true` and the screen you expect: go on. - `animationsSettled: false`, or you are waiting for something that loads (a new screen, a list, a toast): `mm wait-for` the element you expect, e.g. `mm wait-for --testid activity-list` or `mm wait-for --selector "text=Copied"`. It returns as soon as the element is visible, so it is both faster and more reliable than a fixed sleep. -Observations contain `testIds`, `a11y` and (browser, after a mutating or batch call) `animationsSettled` — no app `state`. Call `mm get-state` for state. +Observations contain `testIds`, `a11y`, (browser, after a mutating or batch call) `animationsSettled` and (mobile, see below) `warnings` — no app `state`. Call `mm get-state` for state. On mobile, each observation and `describe-screen` comes from one device snapshot. The Android system status bar and navigation bar and the Expo DevLauncher "Tools" button (iOS `gearshape.fill`) are not part of the app and are removed from `testIds` and `a11y`. Other system windows, such as the biometric prompt (`com.android.systemui:id/biometric_*`), are kept. +**Mobile `warnings`.** When the device read has a problem, `describe-screen`, `accessibility-snapshot` and observations carry a top-level `warnings` array; without one there is no `warnings` key. Each entry is a code, its details, then what to do. On iOS there are two codes: `ax-tree-truncated` (the read stopped at the device's size limit) and `ax-tree-fallback` (the full read failed, for example on a very deep screen, and a flat read served the tree). Example: + +```json +"warnings": ["ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166): the tree hit the device read limit, so elements on screen can be missing from a11y and testIds. See them with `mm screenshot`; tap one with `mm tap-coordinates ` (same units as `bounds`)."] +``` + +With either code, an element you can see can be missing from `a11y` and `testIds`, and a `--testid` or ref target for it can fail with `MM_TARGET_NOT_FOUND` (the target commands search the same device read). Do not conclude that the element is not on screen: run `mm screenshot`, find it, and tap it with `mm tap-coordinates `. After `ax-tree-fallback`, labelled controls usually remain, but containers and screen markers (for example `wallet-screen`) are often missing, so `mm wait-for --testid` on them can time out on the right screen: confirm the screen with a control that is present instead. + On Android, a navigating tap can be observed while the new screen is still mounting: the screen-level test IDs are already there but much of the tree is not (P1-32 saw 51 of 360 nodes). The settle retries a screen that is still tearing down (the old screen's test IDs with most of its nodes gone), not one that is still filling in. When an observation looks partial, run `mm describe-screen` before acting on it. **Android: the first visit to a tab can return the old screen.** A screen that mounts for the first time in the session (for example the Explore or Money tab after an app restart) can take about 2 s to appear (measured on Explore, Android emulator, dev build). The tap works, but the click's observation can still show the old screen, whole or partly removed, and `mm describe-screen` right after the click shows it too. `screenChanged` does not help here: the tapped button's press feedback alone can make it `true`. So after a tap that should open a new screen: diff --git a/src/platform/mobile-platform-driver.test.ts b/src/platform/mobile-platform-driver.test.ts index a4126b38..71f81659 100644 --- a/src/platform/mobile-platform-driver.test.ts +++ b/src/platform/mobile-platform-driver.test.ts @@ -1147,29 +1147,106 @@ describe('MobilePlatformDriver', () => { expect(refMap.get('e2')).toBe('label:Email|type:TextField'); }); - it('reads a snapshot that has device-mcp warnings and does not report them', async () => { + it('adds what to do to a truncated-tree warning, in the tree and the capture', async () => { const backend = createMockBackend({ snapshot: vi.fn().mockResolvedValue({ platform: 'ios', hierarchy: [makeElement({ label: 'Submit', identifier: 'submit' })], raw: '[]', timestamp: Date.now(), - warnings: ['ax-tree-truncated(backend=axbridge,depth=60,nodes=900)'], + warnings: [ + 'ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166)', + 'future-code(x=1)', + ], }), }); const driver = new MobilePlatformDriver(backend); + const expected = [ + 'ax-tree-truncated(backend=axbridge-exclusive,depth=51,nodes=166): the tree hit the device read limit, so elements on screen can be missing from a11y and testIds. See them with `mm screenshot`; tap one with `mm tap-coordinates ` (same units as `bounds`).', + 'future-code(x=1)', + ]; const capture = await driver.captureScreen(); + const tree = await driver.getAccessibilityTree(); + + expect(capture.warnings).toStrictEqual(expected); + expect(capture.nodes.map(({ testId }) => testId)).toStrictEqual([ + 'submit', + ]); + expect(tree.warnings).toStrictEqual(expected); + }); + + it('adds what to do to a flat-fallback warning', async () => { + const backend = createMockBackend({ + snapshot: vi.fn().mockResolvedValue({ + platform: 'ios', + hierarchy: [makeElement({ label: 'Send', identifier: 'send' })], + raw: '[]', + timestamp: Date.now(), + warnings: [ + 'ax-tree-fallback(from=axbridge,to=ax,reason=not-responding)', + ], + }), + }); + const driver = new MobilePlatformDriver(backend); + + const { warnings } = await driver.getAccessibilityTree(); + + expect(warnings).toStrictEqual([ + 'ax-tree-fallback(from=axbridge,to=ax,reason=not-responding): the full read failed, so containers, screen markers and row texts can be missing and `wait-for` on them can time out. Confirm the screen with a control that is present or `mm screenshot`; tap a missing element with `mm tap-coordinates ` (same units as `bounds`).', + ]); + }); + + it('adds what to do to each warning when a fallback read is also truncated', async () => { + const backend = createMockBackend({ + snapshot: vi.fn().mockResolvedValue({ + platform: 'ios', + hierarchy: [makeElement({ label: 'Send', identifier: 'send' })], + raw: '[]', + timestamp: Date.now(), + warnings: [ + 'ax-tree-fallback(from=axbridge,to=ax,reason=error)', + 'ax-tree-truncated(backend=ax,depth=51,nodes=166)', + ], + }), + }); + const driver = new MobilePlatformDriver(backend); + + const { warnings } = await driver.captureScreen(); + + expect(warnings).toHaveLength(2); + expect(warnings?.[0]).toMatch( + /^ax-tree-fallback\(from=axbridge,to=ax,reason=error\): the full read failed, /u, + ); + expect(warnings?.[1]).toMatch( + /^ax-tree-truncated\(backend=ax,depth=51,nodes=166\): the tree hit the device read limit, /u, + ); + }); + + it('has no warnings key when the snapshot has no warnings', async () => { + const snapshot = { + platform: 'ios', + hierarchy: [makeElement({ label: 'Submit', identifier: 'submit' })], + raw: '[]', + timestamp: Date.now(), + }; + const backend = createMockBackend({ + snapshot: vi + .fn() + .mockResolvedValueOnce(snapshot) + .mockResolvedValueOnce({ ...snapshot, warnings: [] }), + }); + const driver = new MobilePlatformDriver(backend); + + const capture = await driver.captureScreen(); + const tree = await driver.getAccessibilityTree(); expect(Object.keys(capture).sort()).toStrictEqual([ 'getTestIds', 'nodes', 'refMap', ]); - expect(capture.nodes.map(({ testId }) => testId)).toStrictEqual([ - 'submit', - ]); - expect(await capture.getTestIds()).toHaveLength(1); + expect(Object.keys(tree).sort()).toStrictEqual(['nodes', 'refMap']); }); it('omits bounds for elements with zero-size frames', async () => { diff --git a/src/platform/mobile-platform-driver.ts b/src/platform/mobile-platform-driver.ts index e3e53dfe..b87c0799 100644 --- a/src/platform/mobile-platform-driver.ts +++ b/src/platform/mobile-platform-driver.ts @@ -18,6 +18,7 @@ import { } from './mobile-hierarchy.js'; import type { Viewport } from './mobile-hierarchy.js'; import type { + AccessibilityTree, IPlatformDriver, HermesDefaults, TargetType, @@ -508,9 +509,12 @@ export class MobilePlatformDriver implements IPlatformDriver { */ async getAccessibilityTree( _rootSelector?: string, - ): Promise<{ nodes: A11yNodeTrimmed[]; refMap: Map }> { - const { hierarchy } = await this.#snapshotApp(); - return normalizeSnapshot(hierarchy, this.#backend.platform); + ): Promise { + const { hierarchy, warnings } = await this.#snapshotApp(); + return { + ...normalizeSnapshot(hierarchy, this.#backend.platform), + ...(warnings === undefined ? {} : { warnings }), + }; } /** @@ -532,9 +536,10 @@ export class MobilePlatformDriver implements IPlatformDriver { * @returns The nodes, refMap and a test ID reader for the same snapshot. */ async captureScreen(): Promise { - const { hierarchy, viewport } = await this.#snapshotApp(); + const { hierarchy, viewport, warnings } = await this.#snapshotApp(); return { ...normalizeSnapshot(hierarchy, this.#backend.platform), + ...(warnings === undefined ? {} : { warnings }), getTestIds: async (limit?: number) => this.#testIdsOf(hierarchy, viewport, limit), }; @@ -545,11 +550,12 @@ export class MobilePlatformDriver implements IPlatformDriver { * elements that are not part of the app (see `filterAppHierarchy`), so the * tree, the refs and the test IDs all use the same filtered hierarchy. * - * @returns The filtered hierarchy and the viewport of the snapshot. + * @returns The filtered hierarchy, viewport and warnings. */ async #snapshotApp(): Promise<{ hierarchy: UIElement[]; viewport: Viewport | undefined; + warnings: string[] | undefined; }> { const snapshot = await this.#backend.snapshot(); const { platform } = this.#backend; @@ -559,6 +565,9 @@ export class MobilePlatformDriver implements IPlatformDriver { excludeDevOverlay: this.#excludeDevOverlay, }), viewport: viewportFromHierarchy(snapshot.hierarchy, platform), + warnings: snapshot.warnings?.length + ? snapshot.warnings.map(withAdvice) + : undefined, }; } @@ -1280,6 +1289,22 @@ type BoundsRef = { matches?: number; }; +const WARNING_ADVICE: Record = { + 'ax-tree-truncated': + 'the tree hit the device read limit, so elements on screen can be missing from a11y and testIds. See them with `mm screenshot`; tap one with `mm tap-coordinates ` (same units as `bounds`).', + 'ax-tree-fallback': + 'the full read failed, so containers, screen markers and row texts can be missing and `wait-for` on them can time out. Confirm the screen with a control that is present or `mm screenshot`; tap a missing element with `mm tap-coordinates ` (same units as `bounds`).', +}; + +/** + * @param warning - A device-mcp warning. + * @returns The warning with its advice. + */ +function withAdvice(warning: string): string { + const advice = WARNING_ADVICE[warning.split('(', 1)[0] ?? '']; + return advice ? `${warning}: ${advice}` : warning; +} + const BOUNDS_REF_PREFIX = 'bounds:'; /** Frame tolerance, in points (iOS) or pixels (Android). */ diff --git a/src/platform/types.ts b/src/platform/types.ts index 3b15ab07..f849de4d 100644 --- a/src/platform/types.ts +++ b/src/platform/types.ts @@ -106,13 +106,17 @@ export type WithinScope = { value: string; }; +export type AccessibilityTree = { + nodes: A11yNodeTrimmed[]; + refMap: Map; + warnings?: string[]; +}; + /** * One snapshot of the screen: the accessibility tree, and the test IDs of the * same snapshot. */ -export type ScreenCapture = { - nodes: A11yNodeTrimmed[]; - refMap: Map; +export type ScreenCapture = AccessibilityTree & { /** * Lists the test IDs of this snapshot (no new snapshot). * @@ -220,7 +224,7 @@ export type IPlatformDriver = { getAccessibilityTree( rootSelector?: string, frame?: FrameSnapshotTarget, - ): Promise<{ nodes: A11yNodeTrimmed[]; refMap: Map }>; + ): Promise; getTestIds(limit?: number): Promise; diff --git a/src/server/create-server.test.ts b/src/server/create-server.test.ts index dd01dc3c..08b90589 100644 --- a/src/server/create-server.test.ts +++ b/src/server/create-server.test.ts @@ -3223,6 +3223,7 @@ describe('createServer abort, ref generations and observations', () => { let minute = 0; let names: string[] = []; + let warnings: string[] | undefined; let backend: { platform: 'android'; snapshot: ReturnType; @@ -3235,6 +3236,7 @@ describe('createServer abort, ref generations and observations', () => { const startWithRealDriver = async (): Promise => { minute = 0; names = ['Wallet']; + warnings = undefined; backend = { platform: 'android', // A new clock value on every snapshot, like a real status bar. @@ -3245,6 +3247,7 @@ describe('createServer abort, ref generations and observations', () => { hierarchy: screen(`12:${String(minute).padStart(2, '0')}`, names), raw: '', timestamp: 0, + ...(warnings && { warnings }), }; }), getWindowSize: vi.fn().mockResolvedValue({ width: 1080, height: 2400 }), @@ -3313,6 +3316,55 @@ describe('createServer abort, ref generations and observations', () => { expect(backend.snapshot).toHaveBeenCalledTimes(1); expect(JSON.stringify(body)).not.toContain('systemui'); }); + describe('device snapshot warnings', () => { + const truncated = 'ax-tree-truncated(depth=51,nodes=166)'; + + const inputOf = (tool: string): Record => + tool === 'click' ? { testId: 'btn-Wallet' } : {}; + + it.each([ + ['describe_screen', 'result'], + ['accessibility_snapshot', 'result'], + ['click', 'observations'], + ] as const)('reports them in %s (%s)', async (tool, part) => { + await startWithRealDriver(); + warnings = [truncated]; + + const { body } = await post(`/tool/${tool}`, inputOf(tool)); + + const reported = (body[part] as { warnings?: string[] }).warnings; + expect(reported).toHaveLength(1); + expect(reported?.[0]).toMatch( + /^ax-tree-truncated\(depth=51,nodes=166\): .*`mm screenshot`.*`mm tap-coordinates `/u, + ); + }); + + it('keeps them in a diff observation', async () => { + await startWithRealDriver(); + await post('/tool/click', { testId: 'btn-Wallet' }); + names = ['Wallet', 'Send']; + warnings = [truncated]; + + const { body } = await post('/tool/click', { testId: 'btn-Wallet' }); + + expect(body.observations?.a11y.diff).toBeDefined(); + expect( + (body.observations as { warnings?: string[] }).warnings?.[0], + ).toMatch(/^ax-tree-truncated\(/u); + }); + + it.each(['describe_screen', 'accessibility_snapshot', 'click'])( + 'has no warnings key in %s when there are none', + async (tool) => { + await startWithRealDriver(); + + const { body } = await post(`/tool/${tool}`, inputOf(tool)); + + expect(body.ok).toBe(true); + expect(JSON.stringify(body)).not.toContain('warnings'); + }, + ); + }); }); describe('P1-09: mobile settle after a mutating tool', () => { diff --git a/src/server/create-server.ts b/src/server/create-server.ts index d51c6243..02f2494b 100644 --- a/src/server/create-server.ts +++ b/src/server/create-server.ts @@ -31,7 +31,11 @@ import type { ISessionManager } from './session-manager.js'; import pkg from '../../package.json'; import type { PortMap, WorkflowContext } from '../capabilities/context.js'; import { PlaywrightPlatformDriver } from '../platform/playwright-driver.js'; -import type { IPlatformDriver, ScreenCapture } from '../platform/types.js'; +import type { + AccessibilityTree, + IPlatformDriver, + ScreenCapture, +} from '../platform/types.js'; import { toolRegistry, getToolCategory, @@ -93,10 +97,8 @@ export type ServerInstance = { stop(): Promise; }; -type ObservedTree = { +type ObservedTree = AccessibilityTree & { testIds: TestIdItem[]; - nodes: A11yNodeTrimmed[]; - refMap: Map; animationsSettled?: boolean; }; @@ -585,7 +587,13 @@ export function createServer(config: ServerConfig): ServerInstance { } signal.throwIfAborted(); const testIds = await screen.getTestIds(OBSERVATION_TESTID_LIMIT); - return { testIds, nodes: screen.nodes, refMap: screen.refMap }; + const { nodes, refMap, warnings } = screen; + return { + testIds, + nodes, + refMap, + ...(warnings === undefined ? {} : { warnings }), + }; } /** @@ -681,10 +689,13 @@ export function createServer(config: ServerConfig): ServerInstance { signal.throwIfAborted(); refs.set(tree.refMap, 'observation'); - const observation = createDefaultObservation(tree.testIds, tree.nodes); - return tree.animationsSettled === undefined - ? observation - : { ...observation, animationsSettled: tree.animationsSettled }; + return { + ...(tree.warnings === undefined ? {} : { warnings: tree.warnings }), + ...createDefaultObservation(tree.testIds, tree.nodes), + ...(tree.animationsSettled === undefined + ? {} + : { animationsSettled: tree.animationsSettled }), + }; } /** diff --git a/src/server/observation-compaction.ts b/src/server/observation-compaction.ts index 84b43a8b..e4992221 100644 --- a/src/server/observation-compaction.ts +++ b/src/server/observation-compaction.ts @@ -257,6 +257,7 @@ export function diffObservation( } return { + ...(current.warnings === undefined ? {} : { warnings: current.warnings }), testIds: current.testIds, a11y: { nodes: changedOrNewNodes, diff --git a/src/tools/discovery-tools.test.ts b/src/tools/discovery-tools.test.ts index 17af3d52..b85cb356 100644 --- a/src/tools/discovery-tools.test.ts +++ b/src/tools/discovery-tools.test.ts @@ -187,6 +187,34 @@ describe('discovery-tools', () => { } }); + it('returns the driver warnings, and no warnings key without them', async () => { + const context = createMockContext(); + const getAccessibilityTree = vi + .fn() + .mockResolvedValueOnce({ + nodes: [], + refMap: new Map(), + warnings: ['ax-tree-truncated(depth=51,nodes=166): advice'], + }) + .mockResolvedValueOnce({ nodes: [], refMap: new Map() }); + const toolContext = { + ...context, + driver: { getAccessibilityTree }, + } as unknown as ToolContext; + + const truncated = await accessibilitySnapshotTool({}, toolContext); + const complete = await accessibilitySnapshotTool({}, toolContext); + + expect(truncated).toStrictEqual({ + ok: true, + result: { + warnings: ['ax-tree-truncated(depth=51,nodes=166): advice'], + nodes: [], + }, + }); + expect(complete).toStrictEqual({ ok: true, result: { nodes: [] } }); + }); + it('uses root selector when provided', async () => { const context = createMockContext(); @@ -590,6 +618,38 @@ describe('discovery-tools', () => { ); }); + it('returns the warnings of the captured screen first, and no warnings key without them', async () => { + const context = createMockContext(); + const screen = { + nodes: [], + refMap: new Map(), + getTestIds: vi.fn().mockResolvedValue([]), + }; + const captureScreen = vi + .fn() + .mockResolvedValueOnce({ + ...screen, + warnings: ['ax-tree-truncated(depth=51,nodes=166): advice'], + }) + .mockResolvedValueOnce(screen); + const toolContext = { + ...context, + driver: { + getAppState: vi.fn().mockResolvedValue({ isLoaded: true }), + captureScreen, + }, + } as unknown as ToolContext; + + const truncated = await describeScreenTool({}, toolContext); + const complete = await describeScreenTool({}, toolContext); + + expect(truncated.ok && Object.keys(truncated.result)[0]).toBe('warnings'); + expect(truncated.ok && truncated.result.warnings).toStrictEqual([ + 'ax-tree-truncated(depth=51,nodes=166): advice', + ]); + expect(complete.ok && 'warnings' in complete.result).toBe(false); + }); + it('reads the app state and captures the screen at the same time', async () => { const context = createMockContext(); const order: string[] = []; diff --git a/src/tools/discovery-tools.ts b/src/tools/discovery-tools.ts index 1f0b6b93..f05dc139 100644 --- a/src/tools/discovery-tools.ts +++ b/src/tools/discovery-tools.ts @@ -100,11 +100,14 @@ export async function accessibilitySnapshotTool( const { driver } = driverResult; try { - const { nodes, refMap } = await driver.getAccessibilityTree( + const { nodes, refMap, warnings } = await driver.getAccessibilityTree( input.rootSelector, ); context.sessionManager.setRefMap(refMap); - return createToolSuccess({ nodes }); + return createToolSuccess({ + ...(warnings === undefined ? {} : { warnings }), + nodes, + }); } catch (error) { const errorInfo = classifyDiscoveryError(error); return createToolError(errorInfo.code, errorInfo.message); @@ -164,7 +167,7 @@ export async function describeScreenTool( if (aborted) { return aborted; } - const { nodes, refMap } = + const { nodes, refMap, warnings } = screen ?? (await driver.getAccessibilityTree(undefined, frameTarget)); context.sessionManager.setRefMap( frameTarget ? new Map([...context.refMap, ...refMap]) : refMap, @@ -201,6 +204,7 @@ export async function describeScreenTool( } return createToolSuccess({ + ...(warnings === undefined ? {} : { warnings }), state, activeTab, testIds: { items: testIds }, diff --git a/src/tools/types/observation.ts b/src/tools/types/observation.ts index 6085b786..aafbb6f9 100644 --- a/src/tools/types/observation.ts +++ b/src/tools/types/observation.ts @@ -22,6 +22,7 @@ export type StepRecordObservation = { * (spinners) and network requests are not checked. */ animationsSettled?: boolean; + warnings?: string[]; }; /** diff --git a/src/tools/types/tool-outputs.ts b/src/tools/types/tool-outputs.ts index 9e8019cf..7e850368 100644 --- a/src/tools/types/tool-outputs.ts +++ b/src/tools/types/tool-outputs.ts @@ -68,6 +68,7 @@ export type ListTestIdsResult = { export type AccessibilitySnapshotResult = { nodes: A11yNodeTrimmed[]; + warnings?: string[]; }; export type ScreenshotInfo = { @@ -87,6 +88,7 @@ export type DescribeScreenResult = { nodes: A11yNodeTrimmed[]; }; screenshot: ScreenshotInfo; + warnings?: string[]; }; export type ScreenshotToolResult = {