Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions LICENSES/talkback.txt
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -31,6 +33,7 @@ static void appendNode(
node.getBoundsInScreen(bounds);
xml.append("<node");
appendAttribute(xml, "index", Integer.toString(nodeIndex));
appendAttribute(xml, "ax-id", Integer.toString(stats.axIdOf(node)));
if (windowMetadata != null) {
appendWindowMetadata(xml, windowMetadata);
}
Expand Down Expand Up @@ -92,6 +95,7 @@ static void appendNode(
}
appendAttribute(xml, "password", Boolean.toString(node.isPassword()));
appendBoundsAttribute(xml, "bounds", bounds.left, bounds.top, bounds.right, bounds.bottom);
appendScreenReaderFacts(xml, node, stats);

int childCount = depth >= maxDepth ? 0 : node.getChildCount();
if (depth >= maxDepth && node.getChildCount() > 0) {
Expand Down Expand Up @@ -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("=\"[")
Expand Down Expand Up @@ -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<AccessibilityNodeInfo, Integer> 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;
Expand Down
2 changes: 1 addition & 1 deletion docs/adr/0014-session-ref-frame-lifetime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
@@ -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([]);
});
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
]);
Expand All @@ -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',
Expand All @@ -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 }),
]);
Expand All @@ -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([]);
});
});

Expand Down
39 changes: 37 additions & 2 deletions packages/capture-kit/src/snapshot/snapshot-audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<AuditResult> {
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[] {
Expand Down
15 changes: 15 additions & 0 deletions packages/command-output/src/capture/audit-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`));
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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'] }],
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
copySnapshotClickabilityEvidence,
copySnapshotScreenReaderOrderEvidence,
publicSnapshotCaptureAnnotations,
snapshotCaptureAnnotationsFrom,
type AuditSnapshotCommandResult,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading