diff --git a/LICENSES/talkback.txt b/LICENSES/talkback.txt new file mode 100644 index 0000000000..dc23ef4331 --- /dev/null +++ b/LICENSES/talkback.txt @@ -0,0 +1,20 @@ +TalkBack 229212fdf5842191d0a93fc95d9ca1423b346866 ported source notices + +packages/platform-android/src/screen-reader-order.ts is a TypeScript port of these files from +https://github.com/google/talkback at commit 229212fdf5842191d0a93fc95d9ca1423b346866: + +utils/src/main/java/com/google/android/accessibility/utils/traversal/OrderedTraversalController.java +utils/src/main/java/com/google/android/accessibility/utils/traversal/ReorderedChildrenIterator.java +utils/src/main/java/com/google/android/accessibility/utils/traversal/NodeCachedBoundsCalculator.java +utils/src/main/java/com/google/android/accessibility/utils/traversal/WorkingTree.java + + Copyright (C) 2015 The Android Open Source Project + +utils/src/main/java/com/google/android/accessibility/utils/AccessibilityNodeInfoUtils.java + + Copyright (C) 2012 The Android Open Source Project + +Licensed under the Apache License, Version 2.0. The port changes the files: it is translated to +TypeScript, reads a captured accessibility tree instead of live nodes, drops nodes that are not +important for accessibility, and leaves out web content, picture-in-picture, the FAB-first option, +and initial focus. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index be02cf24e8..5bc3e7f305 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -44,3 +44,15 @@ Its wrapper scripts retain the upstream copyright notices for the original autho idb v1.5.2. Its MIT copyright notice and license are retained in [`apple/snapshot-bridge/LICENSE.idb`](apple/snapshot-bridge/LICENSE.idb), which also ships with the bridge in the npm package. + +## TalkBack traversal order + +`packages/platform-android/src/screen-reader-order.ts` is ported to TypeScript from +[TalkBack](https://github.com/google/talkback/tree/229212fdf5842191d0a93fc95d9ca1423b346866), +commit `229212fdf5842191d0a93fc95d9ca1423b346866`: `OrderedTraversalController`, +`ReorderedChildrenIterator`, `NodeCachedBoundsCalculator`, and `WorkingTree` +(Copyright (C) 2015 The Android Open Source Project), and the focus rules of +`AccessibilityNodeInfoUtils` (Copyright (C) 2012 The Android Open Source Project). +It is licensed under the [Apache License 2.0](LICENSES/Apache-2.0.txt). +[`LICENSES/talkback.txt`](LICENSES/talkback.txt) lists the ported files and the changes. The +build adds it and the Apache License 2.0 to the generated notice file whenever the port is bundled. diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java index bc2f5ad3c5..9b0a558301 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java @@ -6,7 +6,9 @@ import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; import android.view.accessibility.AccessibilityWindowInfo; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** Serializes accessibility nodes using the helper's host-consumed XML contract. */ final class AccessibilityTreeXml { @@ -31,6 +33,7 @@ static void appendNode( node.getBoundsInScreen(bounds); xml.append("= maxDepth ? 0 : node.getChildCount(); if (depth >= maxDepth && node.getChildCount() > 0) { @@ -222,6 +226,36 @@ static void appendLongClickableAttribute(StringBuilder xml, boolean longClickabl appendAttribute(xml, "long-clickable", Boolean.toString(longClickable)); } + // Inputs of the host's TalkBack order estimate: traversal links as capture ids, and the facts + // its focus rules read. `checked` above already marks a checkable node. + @SuppressWarnings("deprecation") + private static void appendScreenReaderFacts( + StringBuilder xml, AccessibilityNodeInfo node, Stats stats) { + appendTraversalLink(xml, "traversal-before", node.getTraversalBefore(), stats); + appendTraversalLink(xml, "traversal-after", node.getTraversalAfter(), stats); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + appendTrueAttribute(xml, "screen-reader-focusable", node.isScreenReaderFocusable()); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + appendAttribute(xml, "important", Boolean.toString(node.isImportantForAccessibility())); + } + appendTrueAttribute( + xml, "focus-action", hasAccessibilityAction(node, AccessibilityAction.ACTION_FOCUS)); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + appendNonEmptyAttribute(xml, "state-description", node.getStateDescription()); + } + appendTrueAttribute(xml, "collection", node.getCollectionInfo() != null); + appendTrueAttribute(xml, "range", node.getRangeInfo() != null); + } + + @SuppressWarnings("deprecation") + private static void appendTraversalLink( + StringBuilder xml, String name, AccessibilityNodeInfo target, Stats stats) { + if (target == null) return; + appendAttribute(xml, name, Integer.toString(stats.axIdOf(target))); + target.recycle(); + } + static void appendBoundsAttribute( StringBuilder xml, String name, int left, int top, int right, int bottom) { xml.append(' ').append(name).append("=\"[") @@ -271,14 +305,26 @@ private static void appendEscaped(StringBuilder xml, String value) { } static final class Stats { + /** Capture-wide node ids; AccessibilityNodeInfo equality covers window and virtual identity. */ + private Map axIds = new HashMap<>(); int nodeCount; boolean truncated; boolean activeWindowRootMissing; boolean focusedNonActiveWindowRootMissing; WindowMetadata activeWindowMetadata; + @SuppressWarnings("deprecation") + int axIdOf(AccessibilityNodeInfo node) { + Integer id = axIds.get(node); + if (id != null) return id; + int next = axIds.size(); + axIds.put(AccessibilityNodeInfo.obtain(node), next); + return next; + } + Stats copy() { Stats next = new Stats(); + next.axIds = axIds; next.nodeCount = nodeCount; next.truncated = truncated; next.activeWindowRootMissing = activeWindowRootMissing; diff --git a/docs/adr/0014-session-ref-frame-lifetime.md b/docs/adr/0014-session-ref-frame-lifetime.md index 7bd7f1073c..991e9b2449 100644 --- a/docs/adr/0014-session-ref-frame-lifetime.md +++ b/docs/adr/0014-session-ref-frame-lifetime.md @@ -158,7 +158,7 @@ These outputs are partial external publications: - Snapshot diffs. - Digests that omit the namespace. - `find`. -- `audit` finding refs. +- `audit` finding and screen-reader order refs. - Settled diffs/tails. - Replay divergence screens. diff --git a/packages/capture-kit/src/snapshot/__tests__/snapshot-audit-screen-reader-order.test.ts b/packages/capture-kit/src/snapshot/__tests__/snapshot-audit-screen-reader-order.test.ts new file mode 100644 index 0000000000..5a47147187 --- /dev/null +++ b/packages/capture-kit/src/snapshot/__tests__/snapshot-audit-screen-reader-order.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from 'vitest'; +import type { AuditContext } from '@agent-device/contracts/capture'; +import { attachSnapshotScreenReaderOrderEvidence } from '@agent-device/contracts/snapshot-private-evidence'; +import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; +import type { SnapshotNode } from '@agent-device/kernel/snapshot'; +import { auditSnapshotState } from '../snapshot-audit.ts'; + +const ANDROID: AuditContext = { platform: 'android', pixelDensity: 2, truncated: false }; + +function text(index: number, ref: string | undefined): SnapshotNode { + return { + index, + ...(ref ? { ref } : {}), + type: 'android.widget.TextView', + label: `Row ${index}`, + rect: { x: 0, y: index * 100, width: 400, height: 100 }, + }; +} + +function state(nodes: SnapshotNode[]): SnapshotState { + return { nodes, createdAt: 0 }; +} + +test('reports the producer estimate as refs per window, with its limitation', async () => { + const snapshot = state([text(0, 'e1'), text(1, 'e2'), text(2, 'e3')]); + attachSnapshotScreenReaderOrderEvidence(snapshot, () => ({ + windows: [ + { nodeIndexes: [2], omittedStops: 0 }, + { nodeIndexes: [1, 0], omittedStops: 0 }, + ], + })); + const result = await auditSnapshotState(snapshot, ANDROID); + expect(result.screenReaderOrder).toEqual({ + estimatedFrom: 'talkback-16.2', + windows: [{ refs: ['@e3'] }, { refs: ['@e2', '@e1'] }], + }); + expect(result.limitations).toContainEqual(expect.stringContaining('estimated from TalkBack')); +}); + +test('counts a stop without a ref as omitted and drops a window with no stop', async () => { + const snapshot = state([text(0, 'e1'), text(1, undefined)]); + attachSnapshotScreenReaderOrderEvidence(snapshot, () => ({ + windows: [ + { nodeIndexes: [], omittedStops: 0 }, + { nodeIndexes: [0, 1], omittedStops: 2 }, + ], + })); + expect((await auditSnapshotState(snapshot, ANDROID)).screenReaderOrder?.windows).toEqual([ + { refs: ['@e1'], omittedStops: 3 }, + ]); +}); + +test('a snapshot without the estimate reports no order and no order limitation', async () => { + const result = await auditSnapshotState(state([text(0, 'e1')]), ANDROID); + expect(result.screenReaderOrder).toBeUndefined(); + expect(result.limitations).toEqual([]); +}); diff --git a/packages/capture-kit/src/snapshot/__tests__/snapshot-audit.test.ts b/packages/capture-kit/src/snapshot/__tests__/snapshot-audit.test.ts index 6d08bedafa..e12f9fff69 100644 --- a/packages/capture-kit/src/snapshot/__tests__/snapshot-audit.test.ts +++ b/packages/capture-kit/src/snapshot/__tests__/snapshot-audit.test.ts @@ -526,7 +526,7 @@ describe('auditSnapshotState with retained tap facts', () => { return { nodes, createdAt: 0 }; } - test('restores exact android-helper evidence and reports the touchable as small-target', () => { + test('restores exact android-helper evidence and reports the touchable as small-target', async () => { const state = stateWithoutTapFacts([ node(1, { type: 'android.view.View', label: 'Custom action', rect: dp30 }), ]); @@ -536,7 +536,7 @@ describe('auditSnapshotState with retained tap facts', () => { clickableByNodeIndex: new Map([[1, true]]), longClickableByNodeIndex: new Map([[1, false]]), }); - const { findings } = auditSnapshotState(state, ANDROID); + const { findings } = await auditSnapshotState(state, ANDROID); expect(findings).toEqual([ expect.objectContaining({ kind: 'small-target', @@ -547,14 +547,14 @@ describe('auditSnapshotState with retained tap facts', () => { ]); }); - test('reports nothing when the capture retained no clickability evidence', () => { + test('reports nothing when the capture retained no clickability evidence', async () => { const state = stateWithoutTapFacts([ node(1, { type: 'android.view.View', label: 'Custom action', rect: dp30 }), ]); - expect(auditSnapshotState(state, ANDROID).findings).toEqual([]); + expect((await auditSnapshotState(state, ANDROID)).findings).toEqual([]); }); - test('reports nothing on divergence evidence, which names no clickable node', () => { + test('reports nothing on divergence evidence, which names no clickable node', async () => { const state = stateWithoutTapFacts([ node(1, { type: 'android.view.View', label: 'Custom action', rect: dp30 }), ]); @@ -563,7 +563,7 @@ describe('auditSnapshotState with retained tap facts', () => { provider: 'apple-xctest', reason: 'maestro-clickable-not-exposed-by-provider', }); - expect(auditSnapshotState(state, ANDROID).findings).toEqual([]); + expect((await auditSnapshotState(state, ANDROID)).findings).toEqual([]); }); }); diff --git a/packages/capture-kit/src/snapshot/snapshot-audit.ts b/packages/capture-kit/src/snapshot/snapshot-audit.ts index 57c7931744..efb932f9a1 100644 --- a/packages/capture-kit/src/snapshot/snapshot-audit.ts +++ b/packages/capture-kit/src/snapshot/snapshot-audit.ts @@ -5,7 +5,9 @@ import type { AuditFinding, AuditFindingKind, AuditResult, + AuditScreenReaderOrder, AuditSizeUnit, + SnapshotScreenReaderOrderEvidence, } from '@agent-device/contracts/capture'; import { readSnapshotClickabilityEvidence } from '@agent-device/contracts/snapshot-private-evidence'; import { isNativeIosSnapshotBarNode, normalizeType } from '@agent-device/contracts/snapshot'; @@ -148,8 +150,41 @@ function countSharedNames( * tap facts off their nodes, so the helper's retained clickability evidence is folded back onto * the nodes first; platforms that publish no tap fact audit the nodes as captured. */ -export function auditSnapshotState(snapshot: SnapshotState, context: AuditContext): AuditResult { - return auditSnapshot(withRetainedTapFacts(snapshot), context); +export async function auditSnapshotState( + snapshot: SnapshotState, + context: AuditContext, +): Promise { + const { readSnapshotScreenReaderOrderEvidence } = await import('@agent-device/contracts/capture'); + const audit = auditSnapshot(withRetainedTapFacts(snapshot), context); + const evidence = await readSnapshotScreenReaderOrderEvidence(snapshot); + if (!evidence) return audit; + const screenReaderOrder = estimatedScreenReaderOrder(snapshot, evidence); + if (!screenReaderOrder) return audit; + return { + ...audit, + screenReaderOrder, + limitations: [...audit.limitations, SCREEN_READER_ORDER_LIMITATION], + }; +} + +const SCREEN_READER_ORDER_LIMITATION = + "The screen-reader order is estimated from TalkBack 16.2's rules, not observed. It leaves out auto-scroll, scrolling past the screen, the order across windows, and web content."; + +/** The producer's TalkBack order estimate as refs, without windows that hold no stop. */ +function estimatedScreenReaderOrder( + snapshot: SnapshotState, + evidence: SnapshotScreenReaderOrderEvidence, +): AuditScreenReaderOrder | undefined { + const refByIndex = new Map( + snapshot.nodes.flatMap((node) => (node.ref ? [[node.index, `@${node.ref}`] as const] : [])), + ); + const windows = evidence.windows.flatMap(({ nodeIndexes, omittedStops }) => { + const refs = nodeIndexes.flatMap((index) => refByIndex.get(index) ?? []); + const omitted = omittedStops + nodeIndexes.length - refs.length; + if (refs.length === 0 && omitted === 0) return []; + return [{ refs, ...(omitted > 0 ? { omittedStops: omitted } : {}) }]; + }); + return windows.length > 0 ? { estimatedFrom: 'talkback-16.2', windows } : undefined; } function withRetainedTapFacts(snapshot: SnapshotState): readonly SnapshotNode[] { diff --git a/packages/command-output/src/capture/audit-output.ts b/packages/command-output/src/capture/audit-output.ts index 1537c7fcbd..397ea59db8 100644 --- a/packages/command-output/src/capture/audit-output.ts +++ b/packages/command-output/src/capture/audit-output.ts @@ -23,6 +23,7 @@ function formatAuditText(result: AuditSnapshotCommandResult): string { .filter((finding) => finding.kind === 'native') .map((finding) => nativeFindingLine(finding, result.refsGeneration)), ]; + lines.push(...screenReaderOrderLines(result)); const guidance = Object.entries(result.guidance); if (guidance.length > 0) lines.push('', ...guidance.map(([kind, sentence]) => `${kind}: ${sentence}`)); @@ -32,6 +33,20 @@ function formatAuditText(result: AuditSnapshotCommandResult): string { return `${lines.join('\n')}\n`; } +function screenReaderOrderLines(result: AuditSnapshotCommandResult): string[] { + const windows = result.screenReaderOrder?.windows ?? []; + if (windows.length === 0) return []; + const lines = windows.map((window, index) => { + const label = windows.length > 1 ? `, window ${index + 1}` : ''; + const refs = window.refs.map((ref) => pinnedRefText(ref, result.refsGeneration) ?? ref); + const omitted = window.omittedStops + ? ` (${plural(window.omittedStops, 'stop')} not in the snapshot)` + : ''; + return `Estimated TalkBack order${label}: ${refs.join(' ')}${omitted}`; + }); + return ['', ...lines]; +} + function summaryLine(findings: AuditSnapshotCommandResult['findings']): string { const warnings = findings.filter((finding) => finding.severity === 'warning').length; const observations = findings.length - warnings; diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-audit.test.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-audit.test.ts index 8dfad08dd9..8b1fe7109c 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-audit.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-audit.test.ts @@ -4,6 +4,7 @@ import { createAgentDevice } from '../../../runtime.ts'; import { createLocalArtifactAdapter } from '@agent-device/host-kit/local-artifact-adapter'; import { localCommandPolicy } from '@agent-device/contracts/command-policy'; import { makeSnapshotState } from '@agent-device/selectors/snapshot-geometry-fixtures'; +import { attachSnapshotScreenReaderOrderEvidence } from '@agent-device/contracts/capture'; test('runtime audit appends native issues without altering heuristic findings or assigning native refs', async () => { const nativeAuditFindings = [ @@ -56,3 +57,27 @@ test('runtime audit appends native issues without altering heuristic findings or nativeAuditFindings, ); }); + +test('runtime audit reports the backend capture screen-reader order as refs', async () => { + const snapshot = attachSnapshotScreenReaderOrderEvidence( + makeSnapshotState( + [ + { index: 0, depth: 0, type: 'android.widget.TextView', label: 'Title' }, + { index: 1, depth: 0, type: 'android.widget.Button', label: 'Save' }, + ], + { backend: 'android', producer: 'android-uiautomator' }, + ), + () => ({ windows: [{ nodeIndexes: [1, 0], omittedStops: 0 }] }), + ); + const device = createAgentDevice({ + backend: { platform: 'android', captureSnapshot: async () => ({ snapshot }) }, + artifacts: createLocalArtifactAdapter(), + sessions: { get: () => undefined, set: () => {} }, + policy: localCommandPolicy(), + }); + const result = await device.capture.auditSnapshot({}); + assert.deepEqual(result.screenReaderOrder, { + estimatedFrom: 'talkback-16.2', + windows: [{ refs: ['@e2', '@e1'] }], + }); +}); diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot.ts index dcb5440d40..e37a1d5902 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot.ts @@ -1,5 +1,6 @@ import { copySnapshotClickabilityEvidence, + copySnapshotScreenReaderOrderEvidence, publicSnapshotCaptureAnnotations, snapshotCaptureAnnotationsFrom, type AuditSnapshotCommandResult, @@ -197,7 +198,7 @@ export const auditSnapshotCommand: RuntimeCommand< const { auditSnapshotState, matchNativeAuditFindings } = await import('@agent-device/capture-kit/snapshot-audit'); const capture = await captureRuntimeSnapshot(runtime, options); - const audit = auditSnapshotState(capture.snapshot, { + const audit = await auditSnapshotState(capture.snapshot, { platform: runtime.backend.platform, producer: capture.snapshot.producer, target: options.target, @@ -250,9 +251,12 @@ async function captureRuntimeSnapshot( ...(options.observeOnly === undefined ? {} : { observeOnly: options.observeOnly }), }, ); - const snapshot = copySnapshotClickabilityEvidence( + const snapshot = copySnapshotScreenReaderOrderEvidence( result.snapshot, - ensureSnapshotPresentationKey(result.snapshot, options), + copySnapshotClickabilityEvidence( + result.snapshot, + ensureSnapshotPresentationKey(result.snapshot, options), + ), ); const annotations = snapshotCaptureAnnotationsFrom(result); const warningTime = now(runtime); diff --git a/packages/command-surface/src/capture/snapshot.ts b/packages/command-surface/src/capture/snapshot.ts index 3abdea44a3..8cca77058d 100644 --- a/packages/command-surface/src/capture/snapshot.ts +++ b/packages/command-surface/src/capture/snapshot.ts @@ -183,6 +183,28 @@ export const AUDIT_COMMAND_OUTPUT_SCHEMAS = { ], }, }, + screenReaderOrder: objectSchema( + { + estimatedFrom: enumSchema( + ['talkback-16.2'], + "Estimated from a port of TalkBack 16.2's rules, not observed.", + ), + windows: { + type: 'array', + items: objectSchema( + { + refs: { + type: 'array', + items: stringSchema('Plain ref, usable in the frame this audit published.'), + }, + omittedStops: numberSchema('Stops with no node in the snapshot.'), + }, + ['refs'], + ), + }, + }, + ['estimatedFrom', 'windows'], + ), guidance: objectSchema( { 'small-target': stringSchema(), @@ -203,7 +225,7 @@ export const AUDIT_COMMAND_OUTPUT_SCHEMAS = { ), limitations: stringArraySchema(), refsGeneration: numberSchema( - 'Present only with findings: pair each ref with it (@eN~sG) before a mutation.', + 'Present only with refs: pair each ref with it (@eN~sG) before a mutation.', ), warnings: stringArraySchema(), }, @@ -212,7 +234,7 @@ export const AUDIT_COMMAND_OUTPUT_SCHEMAS = { } satisfies Pick, 'audit'>; const auditCommandDescription = - 'Report advisory accessibility findings from one fresh capture of the current screen: touch targets below the platform recommendation, controls without an accessible name, controls of one role that share one accessible name, and covered controls. Each finding shows its role. On Android, a node the capture reports as clickable or long-clickable with no control role is evaluated as a control too. Missing-name findings omit rejected labels and can show the captured identifier. Other findings include the captured label when available. Guidance follows once per finding kind. Covered controls remain findings inside scroll containers, except a control or row a persistent bar covers when scrolling can reveal it. UIKit sheet grabbers are exempt from size and name checks. Direct items of recognized native iOS bars skip size checks and keep name checks. Custom bar children and nested app content remain subject to size checks. Findings are review prompts, not failures, and the audit changes nothing on the device.'; + 'Report advisory accessibility findings from one fresh capture of the current screen: touch targets below the platform recommendation, controls without an accessible name, controls of one role that share one accessible name, and covered controls. On Android, it also estimates the TalkBack swipe order of each app window. Each finding shows its role. On Android, a node the capture reports as clickable or long-clickable with no control role is evaluated as a control too. Missing-name findings omit rejected labels and can show the captured identifier. Other findings include the captured label when available. Guidance follows once per finding kind. Covered controls remain findings inside scroll containers, except a control or row a persistent bar covers when scrolling can reveal it. UIKit sheet grabbers are exempt from size and name checks. Direct items of recognized native iOS bars skip size checks and keep name checks. Custom bar children and nested app content remain subject to size checks. Findings are review prompts, not failures, and the audit changes nothing on the device.'; export const auditCommandFacet = defineParameterlessCommandFacet({ name: AUDIT_COMMAND_NAME, @@ -220,9 +242,9 @@ export const auditCommandFacet = defineParameterlessCommandFacet({ description: auditCommandDescription, text: { summary: 'Report advisory accessibility findings', - searchHint: 'a11y lint voiceover talkback', + searchHint: 'a11y lint voiceover', cliDetail: - 'Findings are a partial ref publication, like find: the text prints each ref pinned (@eN~sG), and a plain ref from before the audit stays refused after the frame expires. An audit with no findings changes no ref state. Target size is checked on iOS in points (44) and on Android in dp (48, from the captured display density); other targets report a limitation instead. Duplicate wrapper controls collapse only when a control is the sole child of a control with the same role; a clickable Android container whose only actionable descendant is already a control reports that control once, for each finding kind the container reports itself. An Android role-less touchable reports under role `clickable`, a role the snapshot itself never shows, and joins the shared-name check only with a name of its own: one named only by its descendants is excluded, because TalkBack announces it by joining their text. A name two or more controls of one role share is reported once per control, ignoring case and surrounding whitespace; controls of different roles may share a name. On iOS 17+ targets served by XCTest, the audit adds Apple contrast, element detection, hit region, description, and trait checks; it leaves out a hit region that small-target already reports. A unique frame match includes a ref, role, and name. Report findings without a rect without acting on an element.', + 'Findings are a partial ref publication, like find: the text prints each ref pinned (@eN~sG), and a plain ref from before the audit stays refused after the frame expires. An audit that returns no ref changes no ref state. Target size is checked on iOS in points (44) and on Android in dp (48, from the captured display density); other targets report a limitation instead. Duplicate wrapper controls collapse only when a control is the sole child of a control with the same role; a clickable Android container whose only actionable descendant is already a control reports that control once, for each finding kind the container reports itself. An Android role-less touchable reports under role `clickable`, a role the snapshot itself never shows, and joins the shared-name check only with a name of its own: one named only by its descendants is excluded, because TalkBack announces it by joining their text. A name two or more controls of one role share is reported once per control, ignoring case and surrounding whitespace; controls of different roles may share a name. On iOS 17+ targets served by XCTest, the audit adds Apple contrast, element detection, hit region, description, and trait checks; it leaves out a hit region that small-target already reports. A unique frame match includes a ref, role, and name. Report findings without a rect without acting on an element. On Android, screenReaderOrder lists the refs a TalkBack swipe is estimated to visit, per app window, from a port of the TalkBack 16.2 traversal and focus rules: it is not observed, and it leaves out auto-scroll, scrolling past the screen, the order across windows, and web content. A stop the snapshot hides is listed by its first presented descendant that is not a stop itself; omittedStops counts stops with no node in the snapshot. iOS reports no order.', }, run: (client, input) => client.capture.audit(input), }); diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 49d7c8cc45..bcdc022689 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -84,6 +84,10 @@ "types": "./src/async-lifecycle.ts", "default": "./src/async-lifecycle.ts" }, + "./audit-result-refs": { + "types": "./src/audit-result-refs.ts", + "default": "./src/audit-result-refs.ts" + }, "./audio-probe-result": { "types": "./src/audio-probe-result.ts", "default": "./src/audio-probe-result.ts" diff --git a/packages/contracts/src/audit-result-refs.ts b/packages/contracts/src/audit-result-refs.ts new file mode 100644 index 0000000000..675d9168ee --- /dev/null +++ b/packages/contracts/src/audit-result-refs.ts @@ -0,0 +1,11 @@ +import type { AuditSnapshotCommandResult } from './audit.ts'; + +/** Every plain ref an audit result returns: finding refs, then screen-reader order refs. */ +export function auditResultRefs( + result: Pick, +): string[] { + return [ + ...result.findings.flatMap((finding) => (finding.ref ? [finding.ref] : [])), + ...(result.screenReaderOrder?.windows.flatMap((window) => window.refs) ?? []), + ]; +} diff --git a/packages/contracts/src/audit.ts b/packages/contracts/src/audit.ts index 28e310f5a8..cea1d27c6f 100644 --- a/packages/contracts/src/audit.ts +++ b/packages/contracts/src/audit.ts @@ -93,8 +93,28 @@ export type AuditChecks = { snapshot: 'complete' | 'partial' | 'unknown'; }; +/** + * TalkBack's swipe order estimated from the capture, one entry per Android application window in + * capture order. It is computed with a port of TalkBack 16.2's traversal and focus rules, not + * observed from TalkBack. It leaves out auto-scroll, scrolling past the screen, the order across + * windows, and web content. + */ +export type AuditScreenReaderOrder = { + estimatedFrom: 'talkback-16.2'; + windows: AuditScreenReaderWindowOrder[]; +}; + +export type AuditScreenReaderWindowOrder = { + /** Plain refs in swipe order. They are valid only with the response's `refsGeneration`. */ + refs: string[]; + /** Stops with no node in the snapshot, left out of `refs`. Absent when none. */ + omittedStops?: number; +}; + export type AuditResult = { findings: AuditFinding[]; + /** Android only, from a snapshot helper that reports the facts the estimate reads. */ + screenReaderOrder?: AuditScreenReaderOrder; guidance: Partial>; checks: AuditChecks; /** Checks the audit could not run or could only partly run, with the reason. */ @@ -104,8 +124,8 @@ export type AuditResult = { export type AuditSnapshotCommandResult = Omit & { findings: (AuditFinding | NativeAuditFinding)[]; /** - * Ref-frame epoch the finding refs were minted from (ADR 0014). Present only when the audit - * returned a finding with a ref; pair each ref with it (`@e7~s`) before a mutation. + * Ref-frame epoch the finding and screen-reader order refs were minted from (ADR 0014). Present + * only when the audit returned a ref; pair each ref with it (`@e7~s`) before a mutation. */ refsGeneration?: number; warnings?: string[]; diff --git a/packages/contracts/src/facades/capture.ts b/packages/contracts/src/facades/capture.ts index 64275d57ad..8f052dbe1a 100644 --- a/packages/contracts/src/facades/capture.ts +++ b/packages/contracts/src/facades/capture.ts @@ -9,6 +9,8 @@ export type { AuditFindingKind, AuditNameDetail, AuditResult, + AuditScreenReaderOrder, + AuditScreenReaderWindowOrder, AuditSeverity, AuditSizeDetail, AuditSizeUnit, @@ -87,15 +89,20 @@ export { readSnapshotTextInputGeometry, attachSnapshotClickabilityEvidence, attachSnapshotOcclusionContextEvidence, + attachSnapshotScreenReaderOrderEvidence, copySnapshotClickabilityEvidence, + copySnapshotScreenReaderOrderEvidence, readSnapshotClickabilityEvidence, readSnapshotOcclusionContextEvidence, + readSnapshotScreenReaderOrderEvidence, } from '../snapshot-private-evidence.ts'; export type { SnapshotTextInputGeometry, AndroidSiblingOrderEvidence, SnapshotClickabilityEvidence, SnapshotOcclusionContextEvidence, + SnapshotScreenReaderOrderEvidence, + SnapshotScreenReaderOrderSource, } from '../snapshot-private-evidence.ts'; export { readViewportDimensions } from '../viewport.ts'; export type { ViewportCommandResult } from '../viewport.ts'; diff --git a/packages/contracts/src/snapshot-private-evidence.test.ts b/packages/contracts/src/snapshot-private-evidence.test.ts index d93201ab92..f5ad28ee56 100644 --- a/packages/contracts/src/snapshot-private-evidence.test.ts +++ b/packages/contracts/src/snapshot-private-evidence.test.ts @@ -2,8 +2,11 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { attachSnapshotClickabilityEvidence, + attachSnapshotScreenReaderOrderEvidence, copySnapshotClickabilityEvidence, + copySnapshotScreenReaderOrderEvidence, readSnapshotClickabilityEvidence, + readSnapshotScreenReaderOrderEvidence, } from './snapshot-private-evidence.ts'; test('retains exact evidence without adding enumerable snapshot or node fields', () => { @@ -38,3 +41,24 @@ test('copies evidence across internal snapshot construction without serializing assert.deepEqual(readSnapshotClickabilityEvidence(target), evidence); assert.deepEqual(JSON.parse(JSON.stringify(target)), { nodes: [] }); }); + +test('computes the screen-reader order once on the first read and shares it across concurrent reads', async () => { + const source = {}; + const target = {}; + const evidence = { windows: [{ nodeIndexes: [0], omittedStops: 0 }] }; + let runs = 0; + attachSnapshotScreenReaderOrderEvidence(source, () => { + runs += 1; + return Promise.resolve(evidence); + }); + copySnapshotScreenReaderOrderEvidence(source, target); + assert.equal(runs, 0); + + const [targetOrder, sourceOrder] = await Promise.all([ + readSnapshotScreenReaderOrderEvidence(target), + readSnapshotScreenReaderOrderEvidence(source), + ]); + assert.equal(targetOrder, evidence); + assert.equal(sourceOrder, evidence); + assert.equal(runs, 1); +}); diff --git a/packages/contracts/src/snapshot-private-evidence.ts b/packages/contracts/src/snapshot-private-evidence.ts index b992448938..7b00d1d386 100644 --- a/packages/contracts/src/snapshot-private-evidence.ts +++ b/packages/contracts/src/snapshot-private-evidence.ts @@ -38,6 +38,23 @@ export type SnapshotOcclusionContextEvidence = { androidSiblingOrderByNodeIndex?: ReadonlyMap; }; +/** + * TalkBack's swipe order estimated for each Android application window, as presented node indexes. + * A stop the presentation hides is listed by its first presented descendant that is not a stop. + */ +export type SnapshotScreenReaderOrderEvidence = { + windows: ReadonlyArray<{ + nodeIndexes: readonly number[]; + /** Stops with no presented node of their own or below them, left out of `nodeIndexes`. */ + omittedStops: number; + }>; +}; + +export type SnapshotScreenReaderOrderSource = () => + | SnapshotScreenReaderOrderEvidence + | undefined + | Promise; + /** Complete text-input geometry measured before iOS semantic projection; absent means unknown. */ export type SnapshotTextInputGeometry = Readonly<{ rects: readonly Rect[] }>; @@ -46,6 +63,8 @@ type SnapshotPrivateEvidence = { textInputGeometry?: SnapshotTextInputGeometry; clickability?: SnapshotClickabilityEvidence; occlusionContext?: SnapshotOcclusionContextEvidence; + /** Computed on first read: only `audit` reads it, so a regular snapshot never pays for it. */ + screenReaderOrder?: SnapshotScreenReaderOrderSource; }; const privateEvidenceBySnapshotObject = new WeakMap(); @@ -132,6 +151,41 @@ export function readSnapshotOcclusionContextEvidence( return owner ? privateEvidenceBySnapshotObject.get(owner)?.occlusionContext : undefined; } +/** Attaches the estimate as a computation that runs once, on the first read. */ +export function attachSnapshotScreenReaderOrderEvidence( + owner: T, + compute: SnapshotScreenReaderOrderSource, +): T { + // Dropped after the run, so the capture tree it closes over is not kept with the snapshot. + let pending: typeof compute | undefined = compute; + let evidence: ReturnType; + const screenReaderOrder = () => { + if (pending) { + evidence = pending(); + pending = undefined; + } + return evidence; + }; + return attachSnapshotPrivateEvidence(owner, { screenReaderOrder }); +} + +export async function readSnapshotScreenReaderOrderEvidence( + owner: object | null | undefined, +): Promise { + return owner ? privateEvidenceBySnapshotObject.get(owner)?.screenReaderOrder?.() : undefined; +} + +/** Carries the estimate without computing it. */ +export function copySnapshotScreenReaderOrderEvidence( + source: object | null | undefined, + target: T, +): T { + const screenReaderOrder = source + ? privateEvidenceBySnapshotObject.get(source)?.screenReaderOrder + : undefined; + return screenReaderOrder ? attachSnapshotPrivateEvidence(target, { screenReaderOrder }) : target; +} + export function attachSnapshotTextInputGeometry( owner: T, geometry: SnapshotTextInputGeometry, diff --git a/packages/daemon/src/core/__tests__/snapshot-capture.test.ts b/packages/daemon/src/core/__tests__/snapshot-capture.test.ts index 211094c97b..45b375a4e1 100644 --- a/packages/daemon/src/core/__tests__/snapshot-capture.test.ts +++ b/packages/daemon/src/core/__tests__/snapshot-capture.test.ts @@ -1,5 +1,9 @@ import { expect, test, vi } from 'vitest'; import { captureSnapshot, captureSnapshotData } from '../snapshot-capture.ts'; +import { + attachSnapshotScreenReaderOrderEvidence, + readSnapshotScreenReaderOrderEvidence, +} from '@agent-device/contracts/snapshot-private-evidence'; import { summarizeSnapshotDiagnostics } from '@agent-device/contracts/capture'; import { buildSnapshotVisibility } from '@agent-device/capture-kit/snapshot-visibility'; import { ANDROID_EMULATOR, buildNodes, IOS_SIMULATOR, MACOS_DEVICE } from '@agent-device/test-kit'; @@ -239,3 +243,25 @@ test('snapshot timing stats count the producer that served each capture', async 'apple-runner': 1, }); }); + +test('captureSnapshot keeps the screen-reader order estimate on the built snapshot state', async () => { + captureSnapshotWithInteractor.mockClear(); + const evidence = { windows: [{ nodeIndexes: [0], omittedStops: 0 }] }; + captureSnapshotWithInteractor.mockResolvedValueOnce( + attachSnapshotScreenReaderOrderEvidence( + { + nodes: buildNodes([{ index: 0, type: 'android.widget.TextView', label: 'Title' }]), + backend: 'android', + producer: 'android-uiautomator', + }, + () => evidence, + ), + ); + const { snapshot } = await captureSnapshot({ + device: ANDROID_EMULATOR, + session: undefined, + flags: {}, + logPath: '/tmp/snapshot-capture-test.log', + }); + expect(await readSnapshotScreenReaderOrderEvidence(snapshot)).toBe(evidence); +}); diff --git a/packages/daemon/src/core/snapshot-capture.ts b/packages/daemon/src/core/snapshot-capture.ts index 86c6a474f4..90732c6794 100644 --- a/packages/daemon/src/core/snapshot-capture.ts +++ b/packages/daemon/src/core/snapshot-capture.ts @@ -1,6 +1,7 @@ import type { CommandFlags } from '@agent-device/contracts/command'; import { copySnapshotClickabilityEvidence, + copySnapshotScreenReaderOrderEvidence, recordSnapshotTiming, snapshotCaptureAnnotationsFrom, type SnapshotCaptureAnnotations, @@ -146,9 +147,12 @@ async function captureSnapshotAttempt(params: CaptureSnapshotParams): Promise (finding.ref ? [finding.ref] : [])); + const refs = auditResultRefs(result); if (!session || refs.length === 0) return { data: result }; markSessionPartialRefsIssued(session, refs); const refsGeneration = session.snapshotGeneration; diff --git a/packages/platform-android/src/__tests__/screen-reader-order.test.ts b/packages/platform-android/src/__tests__/screen-reader-order.test.ts new file mode 100644 index 0000000000..fd105e8ae5 --- /dev/null +++ b/packages/platform-android/src/__tests__/screen-reader-order.test.ts @@ -0,0 +1,81 @@ +import { readFileSync } from 'node:fs'; +import { expect, test } from 'vitest'; +import type { AndroidNode } from '../ui-hierarchy-node.ts'; +import { parseUiHierarchyTree } from '../ui-hierarchy.ts'; +import { estimateTalkBackOrder } from '../screen-reader-order.ts'; + +type TalkBackWalk = { + visited: string[]; + /** Swipes from these bounds that TalkBack makes differently from the estimate, with the reason. */ + knownMisses?: { from: string; reason: string }[]; +}; + +/** + * Snapshot helper captures from an Android 17 emulator, each with the nodes TalkBack 17 focused + * while one-finger swipes walked the screen, by bounds and in visit order. + */ +function talkBackFixture(name: string): { xml: string } & TalkBackWalk { + const read = (file: string) => + readFileSync(new URL(`../fixtures/talkback/${file}`, import.meta.url), 'utf8'); + return { + xml: read(`${name}.xml`), + ...(JSON.parse(read(`${name}.talkback.json`)) as TalkBackWalk), + }; +} + +function boundsText(node: AndroidNode): string { + const rect = node.rect!; + return `[${rect.x},${rect.y}][${rect.x + rect.width},${rect.y + rect.height}]`; +} + +// The Compose dev launcher chains traversal links, the clock hides label-less stops from the +// snapshot, the dialog is its own window, and the React Native screen holds views that are not +// important for accessibility. +test.each(['compose-clock', 'compose-dev-launcher', 'permission-dialog', 'react-native-form'])( + '%s: every swipe TalkBack made within a window lands on the estimated next stop', + (name) => { + const { xml, visited, knownMisses = [] } = talkBackFixture(name); + const windows = estimateTalkBackOrder(parseUiHierarchyTree(xml))!.map((stops) => + stops.map(boundsText), + ); + const swipes = visited.slice(1).flatMap((to, position) => { + const from = visited[position]!; + const window = windows.find((stops) => stops.includes(from)); + // A swipe into another window leaves the per-window order. + if (!window || windows.some((stops) => stops !== window && stops.includes(to))) return []; + return [{ from, to, estimated: window[(window.indexOf(from) + 1) % window.length] }]; + }); + const missing = new Set(knownMisses.map(({ from }) => from)); + const matched = swipes.filter(({ from }) => !missing.has(from)); + expect(matched.length).toBeGreaterThanOrEqual(8); + expect(matched.map(({ estimated }) => estimated)).toEqual(matched.map(({ to }) => to)); + // A known miss that starts matching means the port changed: drop it from the fixture. + for (const { from, to, estimated } of swipes.filter(({ from }) => missing.has(from))) { + expect(estimated, from).not.toBe(to); + } + }, +); + +test('a container whose content sits below its next sibling is read after that sibling', () => { + // ReorderedChildrenIterator orders a non-focusable container by the bounds of its focusable + // content: the container spans the top of the window, but its only text sits below the sibling. + const node = (axId: number, attrs: string, children = '') => + `${children}`; + const xml = node( + 0, + 'class="android.widget.FrameLayout" window-type="1" bounds="[0,0][1080,2000]" window-bounds="[0,0][1080,2000]"', + node( + 1, + 'class="android.view.ViewGroup" bounds="[0,0][1080,1000]"', + node(2, 'class="android.widget.TextView" text="Lower" bounds="[0,800][1080,900]"'), + ) + node(3, 'class="android.widget.TextView" text="Upper" bounds="[0,300][1080,400]"'), + ); + const [window] = estimateTalkBackOrder(parseUiHierarchyTree(xml))!; + expect(window!.map(({ label }) => label)).toEqual(['Upper', 'Lower']); +}); + +test('a capture from a helper without the screen-reader facts has no estimate', () => { + const { xml } = talkBackFixture('permission-dialog'); + const older = xml.replaceAll(/ ax-id="\d+"/g, ''); + expect(estimateTalkBackOrder(parseUiHierarchyTree(older))).toBeUndefined(); +}); diff --git a/packages/platform-android/src/__tests__/snapshot-capture.test.ts b/packages/platform-android/src/__tests__/snapshot-capture.test.ts index aa933bed13..d747cd372d 100644 --- a/packages/platform-android/src/__tests__/snapshot-capture.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-capture.test.ts @@ -1,5 +1,7 @@ import assert from 'node:assert/strict'; -import { afterEach, beforeEach, test } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { afterEach, beforeEach, expect, test } from 'vitest'; +import { readSnapshotScreenReaderOrderEvidence } from '@agent-device/contracts/snapshot-private-evidence'; import './test-utils/android-host-test-setup.ts'; import { androidSnapshotPublicationInput, @@ -222,3 +224,32 @@ test('an input method window the helper could not read makes the published keybo reason: 'window-root-unavailable', }); }); + +test('a stop the snapshot hides is listed by its first presented descendant', async () => { + const xml = readFileSync( + new URL('../fixtures/talkback/compose-clock.xml', import.meta.url), + 'utf8', + ); + const capture = await snapshotAndroid(device, { + helperAdb: helperAdbServing({}, xml), + helperArtifact, + }); + const publication = androidSnapshotPublicationInput(capture); + const evidence = (await readSnapshotScreenReaderOrderEvidence(publication))!; + const labelByIndex = new Map(publication.nodes.map((node) => [node.index, node.label])); + // The capture lists the tip popup's window first. + const [popup, app] = evidence.windows.map(({ nodeIndexes, omittedStops }) => ({ + labels: nodeIndexes.map((index) => labelByIndex.get(index)), + omittedStops, + })); + expect(popup!.labels).toContain('Dismiss'); + // TalkBack reads the clock face and the date row as label-less containers. + expect(app!.labels.slice(0, 5)).toEqual([ + 'World Clock', + 'More options', + '5:35\u200aPM', + 'Sat, Nov 21', + 'No locations', + ]); + expect(app!.omittedStops).toBe(0); +}); diff --git a/packages/platform-android/src/fixtures/talkback/compose-clock.talkback.json b/packages/platform-android/src/fixtures/talkback/compose-clock.talkback.json new file mode 100644 index 0000000000..c237b734da --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/compose-clock.talkback.json @@ -0,0 +1,21 @@ +{ + "talkback": "17.0.0.889642762", + "visited": [ + "[954,162][1080,288]", + "[42,310][1038,725]", + "[42,725][1038,787]", + "[0,1081][1080,2193]", + "[828,1941][1038,2151]", + "[0,2193][216,2361]", + "[216,2193][432,2361]", + "[432,2193][648,2361]", + "[648,2193][864,2361]", + "[864,2193][1080,2361]", + "[535,1856][1048,2193]", + "[567,2011][695,2137]", + "[63,183][383,268]", + "[954,162][1080,288]", + "[42,310][1038,725]", + "[42,725][1038,787]" + ] +} diff --git a/packages/platform-android/src/fixtures/talkback/compose-clock.xml b/packages/platform-android/src/fixtures/talkback/compose-clock.xml new file mode 100644 index 0000000000..83e1ff1326 --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/compose-clock.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/platform-android/src/fixtures/talkback/compose-dev-launcher.talkback.json b/packages/platform-android/src/fixtures/talkback/compose-dev-launcher.talkback.json new file mode 100644 index 0000000000..f84a87f46e --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/compose-dev-launcher.talkback.json @@ -0,0 +1,24 @@ +{ + "talkback": "17.0.0.889642762", + "visited": [ + "[63,205][179,321]", + "[221,210][619,261]", + "[896,200][1022,326]", + "[221,272][526,317]", + "[63,489][424,530]", + "[916,447][1042,573]", + "[105,614][634,653]", + "[147,737][455,785]", + "[105,869][809,908]", + "[147,951][933,1077]", + "[105,1269][975,1308]", + "[105,1350][975,1487]", + "[42,2206][346,2361]" + ], + "knownMisses": [ + { + "from": "[147,951][933,1077]", + "reason": "TalkBack 17 skips the disabled Connect button below this field; the TalkBack 16.2 focus rules focus it." + } + ] +} diff --git a/packages/platform-android/src/fixtures/talkback/compose-dev-launcher.xml b/packages/platform-android/src/fixtures/talkback/compose-dev-launcher.xml new file mode 100644 index 0000000000..8c299bdc96 --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/compose-dev-launcher.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/platform-android/src/fixtures/talkback/permission-dialog.talkback.json b/packages/platform-android/src/fixtures/talkback/permission-dialog.talkback.json new file mode 100644 index 0000000000..847d6536d4 --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/permission-dialog.talkback.json @@ -0,0 +1,18 @@ +{ + "talkback": "17.0.0.889642762", + "visited": [ + "[133,1294][947,1420]", + "[133,1441][947,1567]", + "[133,1062][947,1231]", + "[133,1294][947,1420]", + "[133,1441][947,1567]", + "[133,1062][947,1231]", + "[133,1294][947,1420]", + "[133,1441][947,1567]", + "[133,1062][947,1231]", + "[133,1294][947,1420]", + "[133,1441][947,1567]", + "[133,1062][947,1231]", + "[133,1294][947,1420]" + ] +} diff --git a/packages/platform-android/src/fixtures/talkback/permission-dialog.xml b/packages/platform-android/src/fixtures/talkback/permission-dialog.xml new file mode 100644 index 0000000000..1b20fd24ce --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/permission-dialog.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/platform-android/src/fixtures/talkback/react-native-form.talkback.json b/packages/platform-android/src/fixtures/talkback/react-native-form.talkback.json new file mode 100644 index 0000000000..b539b53629 --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/react-native-form.talkback.json @@ -0,0 +1,24 @@ +{ + "talkback": "17.0.0.889642762", + "visited": [ + "[432,2150][648,2361]", + "[648,2150][864,2361]", + "[864,2150][1080,2361]", + "[937,219][1005,287]", + "[47,142][802,200]", + "[860,142][1005,164]", + "[47,215][802,398]", + "[90,558][990,624]", + "[90,639][990,798]", + "[90,836][990,887]", + "[90,908][990,1046]", + "[90,1081][990,1132]", + "[90,1153][990,1290]", + "[90,1326][990,1377]", + "[90,1398][990,1535]", + "[90,1652][990,1718]", + "[90,1733][990,1839]", + "[90,1877][990,1928]", + "[90,1949][990,2087]" + ] +} diff --git a/packages/platform-android/src/fixtures/talkback/react-native-form.xml b/packages/platform-android/src/fixtures/talkback/react-native-form.xml new file mode 100644 index 0000000000..5d64ab55b7 --- /dev/null +++ b/packages/platform-android/src/fixtures/talkback/react-native-form.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/platform-android/src/screen-reader-order.ts b/packages/platform-android/src/screen-reader-order.ts new file mode 100644 index 0000000000..9f22f35ea3 --- /dev/null +++ b/packages/platform-android/src/screen-reader-order.ts @@ -0,0 +1,416 @@ +/* + * Ported from TalkBack's OrderedTraversalController, ReorderedChildrenIterator, + * NodeCachedBoundsCalculator, WorkingTree (Copyright (C) 2015 The Android Open Source Project) and + * AccessibilityNodeInfoUtils.shouldFocusNode (Copyright (C) 2012 The Android Open Source Project), + * https://github.com/google/talkback at 229212fdf5842191d0a93fc95d9ca1423b346866 (TalkBack 16.2), + * licensed under the Apache License, Version 2.0 (LICENSES/Apache-2.0.txt). + * + * Changes: translated to TypeScript; reads one helper capture instead of live nodes; drops nodes + * that are not important for accessibility, which a UiAutomation capture includes and TalkBack + * never receives. Web content, picture-in-picture, the FAB-first option, and initial focus are + * left out. + */ +import type { Rect } from '@agent-device/kernel/snapshot'; +import { + ANDROID_WINDOW_TYPE_APPLICATION, + readAndroidScreenReaderFacts, + type AndroidNode, + type AndroidScreenReaderFacts, +} from './ui-hierarchy-node.ts'; + +type Bounds = { left: number; top: number; right: number; bottom: number }; + +type ReaderNode = { + source: AndroidNode; + facts: AndroidScreenReaderFacts; + parent?: ReaderNode; + children: ReaderNode[]; + bounds: Bounds; + windowBounds?: Bounds; +}; + +/** + * TalkBack's swipe order estimated for each application window of a helper capture, in capture + * window order: the source nodes a swipe lands on. Undefined when the helper predates the facts. + */ +export function estimateTalkBackOrder(tree: AndroidNode): AndroidNode[][] | undefined { + const windows = tree.children.filter( + (root) => root.windowType === ANDROID_WINDOW_TYPE_APPLICATION, + ); + if (windows.length === 0 || windows.some((root) => !readAndroidScreenReaderFacts(root))) { + return undefined; + } + return windows.map((root) => { + const rules = new FocusRules(); + const window = importantTree(root); + if (!window) return []; + return orderedNodes(window, rules) + .filter((node) => rules.shouldFocus(node)) + .map((node) => node.source); + }); +} + +/** + * TalkBack walks the tree the platform hands an accessibility service. A UiAutomation capture also + * carries views that are not important for accessibility; their children take their place. + */ +function importantTree(root: AndroidNode): ReaderNode | undefined { + const windowBounds = root.windowRect ? toBounds(root.windowRect) : undefined; + const keep = (node: AndroidNode, parent: ReaderNode | undefined): ReaderNode[] => { + const facts = readAndroidScreenReaderFacts(node); + if (!facts) return []; + if (parent !== undefined && facts.important === false) { + return node.children.flatMap((child) => keep(child, parent)); + } + const reader: ReaderNode = { + source: node, + facts, + parent, + children: [], + bounds: node.rect ? toBounds(node.rect) : { left: 0, top: 0, right: 0, bottom: 0 }, + windowBounds, + }; + reader.children = node.children.flatMap((child) => keep(child, reader)); + return [reader]; + }; + return keep(root, undefined)[0]; +} + +function toBounds(rect: Rect): Bounds { + return { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height, + }; +} + +// AccessibilityNodeInfoUtils focus rules. + +class FocusRules { + private readonly speaking = new Map(); + // Upstream asks the same node again for every descendant; the answer depends on the tree only. + private readonly focus = [new Map(), new Map()]; + + shouldFocus(node: ReaderNode, checkChildren = true): boolean { + const memo = this.focus[checkChildren ? 1 : 0]!; + let result = memo.get(node); + if (result === undefined) { + result = this.computeShouldFocus(node, checkChildren); + memo.set(node, result); + } + return result; + } + + private computeShouldFocus(node: ReaderNode, checkChildren: boolean): boolean { + if (!isVisible(node)) return false; + if ( + sameBounds(node.bounds, node.windowBounds) && + node.children.length > 0 && + !isFocusableOrClickable(node) + ) { + return false; + } + const focusable = + isFocusableOrClickable(node) || + (isTopLevelScrollItem(node) && this.isSpeaking(node, new Set())); + if (!checkChildren) return focusable; + if (focusable) { + return node.children.length === 0 || this.isSpeaking(node, new Set(), true); + } + return ( + !hasMatchingAncestor(node, (ancestor) => this.shouldFocus(ancestor, false)) && + (hasText(node) || hasStateDescription(node)) + ); + } + + isSpeaking(node: ReaderNode, visited: Set, cached = false): boolean { + if (cached && this.speaking.has(node)) return this.speaking.get(node)!; + const result = + hasText(node) || + hasStateDescription(node) || + isCheckable(node) || + this.hasNonActionableSpeakingChildren(node, visited, cached); + if (cached) this.speaking.set(node, result); + return result; + } + + private hasNonActionableSpeakingChildren( + node: ReaderNode, + visited: Set, + cached: boolean, + ): boolean { + for (const child of node.children) { + if (visited.has(child)) return false; + visited.add(child); + if (!isVisible(child) || isFocusableOrClickable(child)) continue; + if ( + isTopLevelScrollItem(child) && + this.isSpeaking(child, visited, cached) && + !(node.source.clickable || isLongClickable(node)) + ) { + continue; + } + if (this.isSpeaking(child, visited, cached)) return true; + } + if (node.source.scrollable === true) return false; + return node.children.some( + (child) => + !isVisible(child) && + hasText(child) && + !(child.facts.screenReaderFocusable || isActionableForAccessibility(child)), + ); + } +} + +function isVisible(node: ReaderNode): boolean { + return node.source.visibleToUser !== false; +} + +function isLongClickable(node: ReaderNode): boolean { + return node.source.passiveFacts.longClickable === true; +} + +function isCheckable(node: ReaderNode): boolean { + return node.source.passiveFacts.checked !== undefined; +} + +/** Text, content description, or hint; a collection's own text is not read as its name. */ +function hasText(node: ReaderNode): boolean { + return ( + !node.facts.collection && Boolean(node.source.label || node.source.passiveFacts.placeholder) + ); +} + +function hasStateDescription(node: ReaderNode): boolean { + return node.facts.stateDescription || isCheckable(node) || node.facts.range; +} + +function isActionableForAccessibility(node: ReaderNode): boolean { + return ( + node.source.clickable || + isLongClickable(node) || + node.source.focusable || + node.facts.focusAction + ); +} + +function isFocusableOrClickable(node: ReaderNode): boolean { + return ( + isVisible(node) && (node.facts.screenReaderFocusable || isActionableForAccessibility(node)) + ); +} + +function isTopLevelScrollItem(node: ReaderNode): boolean { + return isVisible(node) && node.parent !== undefined && isScrollItemContainer(node.parent); +} + +const SCROLL_CONTAINER = /(ListView|GridView|RecyclerView|ScrollView|HorizontalScrollView)$/; + +function isScrollItemContainer(node: ReaderNode): boolean { + const className = node.source.type ?? ''; + if (/Spinner$/.test(className)) return false; + return ( + node.source.scrollable === true || node.facts.collection || SCROLL_CONTAINER.test(className) + ); +} + +function hasMatchingAncestor(node: ReaderNode, predicate: (ancestor: ReaderNode) => boolean) { + for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { + if (predicate(ancestor)) return true; + } + return false; +} + +function sameBounds(a: Bounds, b: Bounds | undefined): boolean { + return ( + b !== undefined && + a.left === b.left && + a.top === b.top && + a.right === b.right && + a.bottom === b.bottom + ); +} + +// NodeCachedBoundsCalculator. + +class BoundsCalculator { + private readonly cache = new Map(); + private readonly calculating = new Set(); + private readonly rules: FocusRules; + + constructor(rules: FocusRules) { + this.rules = rules; + } + + get(node: ReaderNode): Bounds | undefined { + if (this.calculating.has(node)) return undefined; + if (this.cache.has(node)) return this.cache.get(node); + this.calculating.add(node); + const bounds = this.fetch(node); + this.cache.set(node, bounds); + this.calculating.delete(node); + return bounds; + } + + usesChildrenBounds(node: ReaderNode): boolean { + const bounds = this.get(node); + return bounds !== undefined && !sameBounds(node.bounds, bounds); + } + + private fetch(node: ReaderNode): Bounds | undefined { + if (!isVisible(node)) return undefined; + if (this.rules.shouldFocus(node)) return nonEmpty(node.bounds); + let child: Bounds | undefined; + for (const candidate of node.children) { + const bounds = this.get(candidate); + if (!bounds) continue; + child = child + ? { + left: Math.min(child.left, bounds.left), + top: Math.min(child.top, bounds.top), + right: Math.max(child.right, bounds.right), + bottom: Math.max(child.bottom, bounds.bottom), + } + : bounds; + } + if (!child) return nonEmpty(node.bounds); + return nonEmpty({ + left: Math.max(child.left, node.bounds.left), + top: Math.max(child.top, node.bounds.top), + right: Math.min(child.right, node.bounds.right), + bottom: Math.min(child.bottom, node.bounds.bottom), + }); + } +} + +function nonEmpty(bounds: Bounds): Bounds | undefined { + return bounds.left === 0 && bounds.top === 0 && bounds.right === 0 && bounds.bottom === 0 + ? undefined + : bounds; +} + +// ReorderedChildrenIterator. + +function reorderedChildren(node: ReaderNode, calc: BoundsCalculator): ReaderNode[] { + const nodes = [...node.children]; + if (nodes.length <= 1 || !nodes.some((child) => calc.usesChildrenBounds(child))) return nodes; + for (let index = nodes.length - 2; index >= 0; index -= 1) { + const current = nodes[index]!; + if (!calc.usesChildrenBounds(current)) continue; + let next = index + 1; + while (next < nodes.length && needSwap(current, nodes[next]!, calc)) { + nodes[next - 1] = nodes[next]!; + nodes[next] = current; + next += 1; + } + } + return nodes; +} + +function needSwap(left: ReaderNode, right: ReaderNode, calc: BoundsCalculator): boolean { + if (compareBounds(calc.get(left), calc.get(right)) > 0) { + return compareBounds(left.bounds, right.bounds) < 0; + } + return false; +} + +function compareBounds(left: Bounds | undefined, right: Bounds | undefined): number { + if (!left || !right) return -1; + if (left.bottom - right.top <= 0) return -1; + if (left.top - right.bottom >= 0) return 1; + return ( + left.left - right.left || + left.top - right.top || + -(left.bottom - left.top - (right.bottom - right.top)) || + -(left.right - left.left - (right.right - right.left)) || + -1 + ); +} + +// WorkingTree and OrderedTraversalController. + +class WorkingTree { + parent: WorkingTree | undefined; + readonly children: WorkingTree[] = []; + readonly node: ReaderNode; + + constructor(node: ReaderNode, parent: WorkingTree | undefined) { + this.node = node; + this.parent = parent; + } + + hasDescendant(tree: WorkingTree | undefined): boolean { + for (let current = tree; current; current = current.parent) { + if (current === this) return true; + } + return false; + } +} + +/** Every node of the window in TalkBack's traversal order, before the focus filter. */ +function orderedNodes(root: ReaderNode, rules: FocusRules): ReaderNode[] { + const calc = new BoundsCalculator(rules); + const trees = new Map(); + const build = (node: ReaderNode, parent: WorkingTree | undefined): WorkingTree | undefined => { + if (trees.has(node.facts.axId)) return undefined; + const tree = new WorkingTree(node, parent); + trees.set(node.facts.axId, tree); + for (const child of reorderedChildren(node, calc)) { + const subtree = build(child, tree); + if (subtree) tree.children.push(subtree); + } + return tree; + }; + const top = build(root, undefined)!; + + const movedRoot = (moving: WorkingTree): WorkingTree => { + const parent = moving.parent; + if (parent?.node.facts.traversalBefore === undefined) return moving; + return parent.node.facts.traversalBefore === moving.node.facts.axId + ? movedRoot(parent) + : moving; + }; + const detach = (tree: WorkingTree) => { + const siblings = tree.parent?.children; + if (siblings) siblings.splice(siblings.indexOf(tree), 1); + tree.parent = undefined; + }; + const moveBefore = (moving: WorkingTree, target: WorkingTree | undefined) => { + if (!target || moving.hasDescendant(target)) return; + const movingRoot = movedRoot(moving); + const parent = target.parent; + if (movingRoot.hasDescendant(parent)) return; + detach(movingRoot); + if (parent) { + const at = parent.children.indexOf(target); + if (at >= 0) parent.children[at] = movingRoot; + } + movingRoot.parent = parent; + moving.children.push(target); + target.parent = moving; + }; + const moveAfter = (moving: WorkingTree, target: WorkingTree | undefined) => { + if (!target || moving.hasDescendant(target)) return; + const movingRoot = movedRoot(moving); + if (movingRoot.hasDescendant(target)) return; + detach(movingRoot); + target.children.push(movingRoot); + movingRoot.parent = target; + }; + for (const tree of trees.values()) { + const { traversalBefore, traversalAfter } = tree.node.facts; + if (traversalBefore !== undefined) moveBefore(tree, trees.get(traversalBefore)); + else if (traversalAfter !== undefined) moveAfter(tree, trees.get(traversalAfter)); + } + + let start = top; + while (start.parent) start = start.parent; + const order: ReaderNode[] = []; + const walk = (tree: WorkingTree) => { + order.push(tree.node); + for (const child of tree.children) walk(child); + }; + walk(start); + return order; +} diff --git a/packages/platform-android/src/snapshot-capture.ts b/packages/platform-android/src/snapshot-capture.ts index 17fbe688d1..d2eaaf0f4f 100644 --- a/packages/platform-android/src/snapshot-capture.ts +++ b/packages/platform-android/src/snapshot-capture.ts @@ -2,9 +2,11 @@ import { stampSnapshotIdentity } from '@agent-device/contracts/snapshot-producer import { attachSnapshotClickabilityEvidence, attachSnapshotOcclusionContextEvidence, + attachSnapshotScreenReaderOrderEvidence, type AndroidSnapshotBackendMetadata, type SnapshotClickabilityEvidence, type SnapshotOcclusionContextEvidence, + type SnapshotScreenReaderOrderSource, } from '@agent-device/contracts/capture'; import type { RawSnapshotNode, @@ -23,6 +25,7 @@ const androidCaptureEvidence = Symbol('androidSnapshotCaptureEvidence'); type AndroidCaptureEvidence = Readonly<{ clickability: Extract; occlusionContext?: SnapshotOcclusionContextEvidence; + screenReaderOrder?: SnapshotScreenReaderOrderSource; }>; type AndroidSnapshotCaptureData = Readonly<{ @@ -90,5 +93,8 @@ export function androidSnapshotPublicationInput( if (evidence.occlusionContext) { attachSnapshotOcclusionContextEvidence(publication, evidence.occlusionContext); } + if (evidence.screenReaderOrder) { + attachSnapshotScreenReaderOrderEvidence(publication, evidence.screenReaderOrder); + } return publication; } diff --git a/packages/platform-android/src/snapshot-screen-reader-order.ts b/packages/platform-android/src/snapshot-screen-reader-order.ts new file mode 100644 index 0000000000..ee9bf6274e --- /dev/null +++ b/packages/platform-android/src/snapshot-screen-reader-order.ts @@ -0,0 +1,48 @@ +import type { SnapshotScreenReaderOrderEvidence } from '@agent-device/contracts/capture'; +import type { AndroidBuiltSnapshot } from './ui-hierarchy.ts'; +import type { AndroidNode } from './ui-hierarchy-node.ts'; +import { estimateTalkBackOrder } from './screen-reader-order.ts'; + +/** + * The TalkBack order estimate as presented node indexes. A stop the presentation hides, such as a + * label-less container TalkBack reads as one, is listed by its first presented descendant that is + * not a stop of its own. + */ +export function buildAndroidScreenReaderOrderEvidence( + tree: AndroidNode, + snapshot: Pick, +): SnapshotScreenReaderOrderEvidence | undefined { + const windows = estimateTalkBackOrder(tree); + if (!windows) return undefined; + const presented = new Map(); + snapshot.sourceNodes.forEach((source, position) => { + const node = snapshot.nodes[position]; + if (node) presented.set(source, node.index); + }); + const stops = new Set(windows.flat()); + return { + windows: windows.map((windowStops) => { + const nodeIndexes: number[] = []; + let omittedStops = 0; + for (const stop of windowStops) { + const index = presented.get(stop) ?? firstPresentedDescendant(stop, presented, stops); + if (index === undefined || nodeIndexes.includes(index)) omittedStops += 1; + else nodeIndexes.push(index); + } + return { nodeIndexes, omittedStops }; + }), + }; +} + +function firstPresentedDescendant( + node: AndroidNode, + presented: ReadonlyMap, + stops: ReadonlySet, +): number | undefined { + for (const child of node.children) { + if (stops.has(child)) continue; + const index = presented.get(child) ?? firstPresentedDescendant(child, presented, stops); + if (index !== undefined) return index; + } + return undefined; +} diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index 7bb24ec849..6c8ce3cee9 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -189,6 +189,11 @@ export async function snapshotAndroid( return createAndroidSnapshotCapture(result, { clickability: buildAndroidSnapshotClickabilityEvidence(built), occlusionContext, + screenReaderOrder: async () => { + const { buildAndroidScreenReaderOrderEvidence } = + await import('./snapshot-screen-reader-order.ts'); + return buildAndroidScreenReaderOrderEvidence(tree, built); + }, }); } catch (error) { if (!isAndroidSnapshotPresentationFailure(error)) throw error; diff --git a/packages/platform-android/src/ui-hierarchy-node.ts b/packages/platform-android/src/ui-hierarchy-node.ts index 0a98438031..c1d7a30ef8 100644 --- a/packages/platform-android/src/ui-hierarchy-node.ts +++ b/packages/platform-android/src/ui-hierarchy-node.ts @@ -86,6 +86,40 @@ export function readAndroidSiblingOrder(node: AndroidNode): AndroidSiblingOrder return siblingOrderByNode.get(node); } +/** + * Helper-only inputs of the TalkBack order estimate (`screen-reader-order.ts`). They stay off the + * presented node, like sibling order. Absent on a capture from a helper that predates them. + */ +export type AndroidScreenReaderFacts = { + /** Capture-wide node id that `traversalBefore` and `traversalAfter` refer to. */ + axId: number; + traversalBefore?: number; + traversalAfter?: number; + screenReaderFocusable: boolean; + /** `isImportantForAccessibility()`; absent below API 24. */ + important?: boolean; + focusAction: boolean; + stateDescription: boolean; + collection: boolean; + range: boolean; +}; + +const screenReaderFactsByNode = new WeakMap(); + +export function attachAndroidScreenReaderFacts( + node: AndroidNode, + facts: AndroidScreenReaderFacts | undefined, +): AndroidNode { + if (facts) screenReaderFactsByNode.set(node, facts); + return node; +} + +export function readAndroidScreenReaderFacts( + node: AndroidNode, +): AndroidScreenReaderFacts | undefined { + return screenReaderFactsByNode.get(node); +} + /** A node a touch can act on. */ function isTouchTarget(node: AndroidNode): boolean { return node.clickable; diff --git a/packages/platform-android/src/ui-hierarchy.fixtures.ts b/packages/platform-android/src/ui-hierarchy.fixtures.ts index da02209b60..d965c4150c 100644 --- a/packages/platform-android/src/ui-hierarchy.fixtures.ts +++ b/packages/platform-android/src/ui-hierarchy.fixtures.ts @@ -13,6 +13,7 @@ import { type AndroidUiHierarchySnapshotOptions, } from './mechanics.ts'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; +import { buildAndroidScreenReaderOrderEvidence } from './snapshot-screen-reader-order.ts'; /** * Reconstructs the `AndroidUiHierarchy` tree `buildUiHierarchySnapshot` expects @@ -102,7 +103,8 @@ export function parseUiHierarchy( maxNodes: number | undefined, options: AndroidUiHierarchySnapshotOptions, ): ReturnType { - const built = buildUiHierarchySnapshot(parseUiHierarchyTree(xml), maxNodes, options); + const tree = parseUiHierarchyTree(xml); + const built = buildUiHierarchySnapshot(tree, maxNodes, options); const { sourceNodes: _sourceNodes, occlusionContext, ...snapshot } = built; return createAndroidSnapshotCapture( { @@ -113,6 +115,7 @@ export function parseUiHierarchy( { clickability: buildAndroidSnapshotClickabilityEvidence(built), occlusionContext, + screenReaderOrder: () => buildAndroidScreenReaderOrderEvidence(tree, built), }, ); } diff --git a/packages/platform-android/src/ui-hierarchy.ts b/packages/platform-android/src/ui-hierarchy.ts index 17741376f5..94e0642b32 100644 --- a/packages/platform-android/src/ui-hierarchy.ts +++ b/packages/platform-android/src/ui-hierarchy.ts @@ -7,8 +7,10 @@ import type { Rect } from '@agent-device/kernel/snapshot'; import { parseBounds } from '@agent-device/kernel/bounds'; import { decodeXmlCharacterReferences } from '@agent-device/xml'; import { + attachAndroidScreenReaderFacts, attachAndroidSiblingOrder, type AndroidNode, + type AndroidScreenReaderFacts, type AndroidUiHierarchy, } from './ui-hierarchy-node.ts'; @@ -64,6 +66,8 @@ export type AndroidUiNodeMetadata = { windowFocused?: boolean; windowRect?: Rect; windowRegionRect?: boolean; + /** Helper-only inputs of the TalkBack order estimate. */ + screenReader?: AndroidScreenReaderFacts; } & AndroidSystemChromeProvenance; /** @@ -193,6 +197,21 @@ function readNodeAttributes(node: string): Omit { ...optionalBoolAttr('windowFocused', 'window-focused'), ...optionalRectAttr('windowRect', 'window-bounds'), ...optionalBoolAttr('windowRegionRect', 'window-region-rect'), + ...(numberAttr('ax-id') === undefined + ? {} + : { + screenReader: { + axId: numberAttr('ax-id')!, + traversalBefore: numberAttr('traversal-before'), + traversalAfter: numberAttr('traversal-after'), + screenReaderFocusable: boolAttr('screen-reader-focusable') === true, + important: boolAttr('important'), + focusAction: boolAttr('focus-action') === true, + stateDescription: Boolean(getAttr('state-description')), + collection: boolAttr('collection') === true, + range: boolAttr('range') === true, + }, + }), }; } @@ -326,7 +345,7 @@ function normalizeAndroidUiHierarchyNode( parent: AndroidNode, ): AndroidUiHierarchy { const label = attrs.text || attrs.desc; - return attachAndroidSiblingOrder( + const node = attachAndroidSiblingOrder( { type: attrs.className, label, @@ -373,6 +392,7 @@ function normalizeAndroidUiHierarchyNode( }, attrs.drawingOrder === undefined ? undefined : { parent, order: attrs.drawingOrder }, ); + return attachAndroidScreenReaderFacts(node, attrs.screenReader); } function androidFieldValue(attrs: AndroidUiNodeMetadata): string | null { diff --git a/scripts/__tests__/bundled-license-notices.test.ts b/scripts/__tests__/bundled-license-notices.test.ts index 4d667d5e2c..d58040de84 100644 --- a/scripts/__tests__/bundled-license-notices.test.ts +++ b/scripts/__tests__/bundled-license-notices.test.ts @@ -325,6 +325,28 @@ test.each(['0.4.4', '0.4.5'])( }, ); +test('a bundled TalkBack port carries its source notices and the Apache license', async () => { + const [sourceNotices, apacheLicense] = await Promise.all([ + fs.readFile(new URL('../../LICENSES/talkback.txt', import.meta.url), 'utf8'), + fs.readFile(new URL('../../LICENSES/Apache-2.0.txt', import.meta.url), 'utf8'), + ]); + const port = 'packages/platform-android/src/screen-reader-order.ts'; + const root = await fixture({ + 'input.ts': `export { value } from './${port}';`, + [port]: 'export const value = process.env.FIXTURE_NUMBER;', + 'LICENSES/talkback.txt': sourceNotices, + 'LICENSES/Apache-2.0.txt': apacheLicense, + }); + await bundle(root); + const notices = await fs.readFile(path.join(root, 'dist/THIRD_PARTY_NOTICES.txt'), 'utf8'); + assert.match( + notices, + /^talkback@229212fdf5842191d0a93fc95d9ca1423b346866 \(Apache-2\.0\): \[1\], \[2\]$/m, + ); + assert.ok(notices.includes(sourceNotices.trim())); + assert.ok(notices.includes(apacheLicense.replaceAll('\r\n', '\n').trim())); +}); + // A project that genuinely bundles nothing keeps getting the generic notice: the content policy that // holds the published CLI to naming somebody is the publish gate's, not this formatter's. Pinning it // here keeps a future "reject the placeholder" edit at the formatter from breaking an empty build. diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index b51f52ae76..085de6563f 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -23,6 +23,7 @@ "@agent-device/contracts/audio-probe-runtime-host", "@agent-device/contracts/audio-probe-support", "@agent-device/contracts/audio-runtime-plan", + "@agent-device/contracts/audit-result-refs", "@agent-device/contracts/back-mode", "@agent-device/contracts/back-runtime", "@agent-device/contracts/backend", diff --git a/scripts/lib/bundled-license-notices.ts b/scripts/lib/bundled-license-notices.ts index 3a633d78e2..75f523715a 100644 --- a/scripts/lib/bundled-license-notices.ts +++ b/scripts/lib/bundled-license-notices.ts @@ -21,10 +21,12 @@ export function bundledLicenseNotices(root: string): Rolldown.Plugin { name: 'bundled-license-notices', generateBundle(_options, bundle) { const packages = new Map(); + let portedTalkBack = false; for (const output of Object.values(bundle)) { if (output.type !== 'chunk') continue; for (const [id, module] of Object.entries(output.modules)) { if (module.renderedLength === 0) continue; + portedTalkBack ||= path.relative(root, id) === TALKBACK_PORT_MODULE; const owner = thirdPartyPackage(root, id); if (owner) packages.set(owner.directory, owner.manifest); } @@ -32,6 +34,7 @@ export function bundledLicenseNotices(root: string): Rolldown.Plugin { const dependencies = Array.from(packages, ([directory, manifest]) => attributableDependency(root, directory, manifest), ); + if (portedTalkBack) dependencies.push(talkBackNotice(root)); this.emitFile({ type: 'asset', fileName: 'THIRD_PARTY_NOTICES.txt', @@ -41,6 +44,24 @@ export function bundledLicenseNotices(root: string): Rolldown.Plugin { }; } +/** This project's TypeScript port of TalkBack's traversal order, an Apache-2.0 derivative work. */ +const TALKBACK_PORT_MODULE = 'packages/platform-android/src/screen-reader-order.ts'; + +/** Ported source has no package manifest; LICENSES/talkback.txt names the upstream commit. */ +function talkBackNotice(root: string): NoticeDependency { + const notices = fs.readFileSync(path.join(root, 'LICENSES/talkback.txt'), 'utf8'); + const version = notices + .split(/\r?\n/, 1)[0] + ?.match(/^TalkBack (\S+) ported source notices$/)?.[1]; + if (!version) throw new Error('LICENSES/talkback.txt must open with the ported TalkBack commit.'); + return { + name: 'talkback', + version, + license: 'Apache-2.0', + texts: [notices, fs.readFileSync(path.join(root, 'LICENSES/Apache-2.0.txt'), 'utf8')], + }; +} + function readManifest(directory: string): Manifest | undefined { const file = path.join(directory, 'package.json'); if (!fs.existsSync(file)) return undefined; diff --git a/src/commands/schema/cli-help-first-screen.test.ts b/src/commands/schema/cli-help-first-screen.test.ts index 44214bf501..cd34cbb63d 100644 --- a/src/commands/schema/cli-help-first-screen.test.ts +++ b/src/commands/schema/cli-help-first-screen.test.ts @@ -143,7 +143,7 @@ const FIRST_SCREEN_RULES: Record = { ], accessibility: [ 'Audit findings are advisory heuristics', - 'This tool does not measure color contrast or focus order, and does not give a compliance verdict. Do not claim compliance', + 'This tool does not measure color contrast or iOS focus order, and does not give a compliance verdict. Do not claim compliance', '2. Run agent-device audit, then agent-device snapshot -i', 'Visit every tab, pushed screen, sheet, dialog, and empty, error, and loading state', 'Large text: first run agent-device settings text-size to record the current size.', diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index e0885a2181..57da580def 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -207,7 +207,8 @@ Use this when asked for an accessibility review, a11y audit, or a screen-reader Scope: Audit findings are advisory heuristics. Audit checks touch-target size, missing accessible names, controls of one role that share one accessible name, and covered controls. - This tool does not measure color contrast or focus order, and does not give a compliance verdict. Do not claim compliance. + On Android, audit also prints an estimated TalkBack swipe order. It is an estimate, not observed TalkBack behavior. + This tool does not measure color contrast or iOS focus order, and does not give a compliance verdict. Do not claim compliance. Loop for each screen: 1. Open the app: agent-device open . Run mkdir -p ./a11y-output once. @@ -235,7 +236,8 @@ Additional manual checks: Dark mode: first note the current mode from a screenshot. Then run agent-device settings appearance dark, then screenshot each key screen. Look for low-contrast text and icons by eye. At the end, set the noted mode again. For example, if the noted mode was light, run agent-device settings appearance light. If settings refuses on this device, such as a physical iPhone, list large text and dark mode as not done. - Screen reader order and labels: read agent-device snapshot (without -i) from top to bottom. The order must match the visual order. + Screen reader order and labels: on Android, compare audit's estimated TalkBack order with the visual order. On iOS, read agent-device snapshot (without -i) from top to bottom. The order must match the visual order. + Report an order problem as a likely problem to check with the screen reader on a device, not as a confirmed failure. Audit reports a name that controls of one role share. Check by hand that each label names its target ("Save Lemon Herb Rice", not "Save"), even when it is unique, and that controls of different roles do not share one name. A control must expose its state (selected, checked, disabled). Gesture-only actions: every swipe or long-press action needs another way to reach it, such as a visible control or an accessibility action. On the iOS simulator, agent-device snapshot -i --actions names the custom actions that a merged element hides. diff --git a/src/mcp/__tests__/tool-ref-pins.test.ts b/src/mcp/__tests__/tool-ref-pins.test.ts index 585d01111e..f28a13ba28 100644 --- a/src/mcp/__tests__/tool-ref-pins.test.ts +++ b/src/mcp/__tests__/tool-ref-pins.test.ts @@ -466,7 +466,7 @@ test('ref-pin store leaves existing pins untouched for a mutating find without r assert.deepEqual(pinned, { session: 'demo', ref: '@e2~s7' }); }); -test('ref-pin store pins audit finding refs to the audit generation and keeps other pins', () => { +test('ref-pin store pins audit finding and screen-reader order refs to the audit generation and keeps other pins', () => { const pins = makeStore(); const checks = { snapshot: 'complete' } as const; @@ -499,6 +499,7 @@ test('ref-pin store pins audit finding refs to the audit generation and keeps ot }, checks, limitations: [], + screenReaderOrder: { estimatedFrom: 'talkback-16.2', windows: [{ refs: ['@e5'] }] }, refsGeneration: 9, } satisfies AuditSnapshotCommandResult, undefined, @@ -513,6 +514,10 @@ test('ref-pin store pins audit finding refs to the audit generation and keeps ot session: 'demo', ref: '@e3~s9', }); + assert.deepEqual(pins.pinInput('press', { session: 'demo', ref: '@e5' }, undefined), { + session: 'demo', + ref: '@e5~s9', + }); assert.deepEqual(pins.pinInput('press', { session: 'demo', ref: '@e37' }, undefined), { session: 'demo', ref: '@e37~s7', diff --git a/src/mcp/tool-ref-pins.ts b/src/mcp/tool-ref-pins.ts index c05f87ddaf..88b05344e5 100644 --- a/src/mcp/tool-ref-pins.ts +++ b/src/mcp/tool-ref-pins.ts @@ -1,3 +1,4 @@ +import { auditResultRefs } from '@agent-device/contracts/audit-result-refs'; import type { SettleObservation } from '@agent-device/contracts/interaction'; import { readElementMatchCandidateRefs } from '@agent-device/kernel/errors'; import { snapshotRefBodies, type SnapshotNode } from '@agent-device/kernel/snapshot'; @@ -219,8 +220,9 @@ function mergeFindRefPins( } /** - * `audit` publishes a partial frame for exactly its finding refs (ADR 0014), like a read-only - * `find`. A result without findings carries no generation, issues nothing, and leaves pins alone. + * `audit` publishes a partial frame for exactly its finding and screen-reader order refs (ADR 0014), + * like a read-only `find`. A result without refs carries no generation, issues nothing, and leaves + * pins alone. */ function mergeAuditRefPins( refPinsByScope: Map>, @@ -229,9 +231,7 @@ function mergeAuditRefPins( ): void { const refsGeneration = result.refsGeneration; if (typeof refsGeneration !== 'number') return; - const issued = result.findings.flatMap((finding) => - finding.ref ? [finding.ref.replace(/^@/, '')] : [], - ); + const issued = auditResultRefs(result).map((ref) => ref.replace(/^@/, '')); mergeIntoScopedPins(refPinsByScope, scopeKey, issued, refsGeneration); } diff --git a/test/integration/provider-scenarios/android-audit.test.ts b/test/integration/provider-scenarios/android-audit.test.ts index 256bb36058..11f68b1ef2 100644 --- a/test/integration/provider-scenarios/android-audit.test.ts +++ b/test/integration/provider-scenarios/android-audit.test.ts @@ -28,6 +28,72 @@ const AUDIT_SCREEN_XML = [ '', ].join('\n'); +// A helper capture with the screen-reader facts: two named texts and no control, so no finding. +const ORDER_SCREEN_XML = [ + '', + '', + ' ', + ' ', + ' ', + ' ', + '', +].join('\n'); + +function settingsAdbProvider(xml: string): AndroidAdbProvider { + const ime = createAndroidProviderShellState(); + return { + snapshotHelperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + imeHelperArtifact: ANDROID_IME_HELPER_FIXTURE_ARTIFACT, + exec: async (args) => { + const key = args.join(' '); + const imeResult = androidImeLifecycleAdbResult(key, [...args], ime); + if (imeResult) return imeResult; + if (key === 'shell getprop sys.boot_completed') { + return { stdout: '1\n', stderr: '', exitCode: 0 }; + } + if (key === 'shell dumpsys window windows') { + return { + stdout: 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n', + stderr: '', + exitCode: 0, + }; + } + if (key.startsWith('shell am instrument ')) { + return { + stdout: androidSnapshotHelperOutput(xml, { pixelDensity: PIXEL_DENSITY }), + stderr: '', + exitCode: 0, + }; + } + return { stdout: '', stderr: '', exitCode: 0 }; + }, + }; +} + +test('Provider-backed integration Android audit issues the estimated TalkBack order refs without findings', async () => { + const adbProvider = settingsAdbProvider(ORDER_SCREEN_XML); + const daemon = await createProviderScenarioHarness({ + androidAdbProvider: () => adbProvider, + deviceInventoryProvider: async () => [PROVIDER_SCENARIO_ANDROID], + }); + try { + const selection = { platform: 'android' as const, serial: PROVIDER_SCENARIO_ANDROID.id }; + assertRpcOk(await daemon.callCommand('open', ['settings'], selection)); + + const audit = assertRpcOk(await daemon.callCommand('audit', [], selection)); + assert.deepEqual(audit.findings, []); + const order = audit.screenReaderOrder as { windows: Array<{ refs: string[] }> }; + assert.equal(order.windows.length, 1); + assert.equal(order.windows[0]!.refs.length, 2); + assert.equal(typeof audit.refsGeneration, 'number'); + const ref = `${order.windows[0]!.refs[1]}~s${audit.refsGeneration}`; + const read = assertRpcOk(await daemon.callCommand('get', ['text', ref], selection)); + assert.equal(read.text, '42 GB used'); + } finally { + await daemon.close(); + } +}); + test('Provider-backed integration Android audit converts captured pixels to dp before judging target size', async () => { const ime = createAndroidProviderShellState(); const adbProvider: AndroidAdbProvider = { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index dfdcefe854..035404946b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -874,6 +874,7 @@ Exact behavior: `agent-device help audit`. `audit` checks the current screen for accessibility problems. Findings are review prompts, not failures, and `audit` changes nothing on the device. - It checks for small targets, controls with no accessible name, controls of one role that share a name, and controls covered by other UI. `agent-device help audit` describes each check and its exemptions. +- On Android, `audit` also prints an estimated TalkBack swipe order for each app window, as refs. The estimate uses TalkBack's ordering rules on the captured tree, so it can differ from TalkBack where TalkBack scrolls, moves between windows, or reads web content. Confirm an order problem with TalkBack on a device. - On iOS 17+ with the XCTest runner, `audit` also runs Apple's native accessibility checks. Other targets run the heuristic checks only. Apple's Dynamic Type and clipped-text checks are not run; `agent-device help accessibility` describes the large text check to use instead. - A system alert over the app stops Apple's checks with `native_audit_blocked_by_alert`. Run `agent-device alert accept` or `agent-device alert dismiss`, then run `audit` again. A runner answer the CLI cannot read fails with `native-audit-invalid-result`. - When a native finding matches a captured element, it includes its ref. Otherwise, match its `rect` against a new snapshot before you act. A finding without a rect names no element, so report it without acting.