Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@

/** Serializes accessibility nodes using the helper's host-consumed XML contract. */
final class AccessibilityTreeXml {
/** Longest text emitted whole; longer app text keeps this prefix and adds `text-clipped`. */
static final int MAX_TEXT_CHARS = 64 * 1024;

private AccessibilityTreeXml() {}

@SuppressWarnings("deprecation")
Expand Down Expand Up @@ -39,7 +42,7 @@ static void appendNode(
}
CharSequence text = node.getText();
if (text != null) {
appendAttribute(xml, "text", text);
appendTextAttribute(xml, text);
}
// getText() returns the HINT for an empty field on modern Android, so `text` alone cannot
// distinguish a cleared field from one whose value equals its hint; only this flag can
Expand Down Expand Up @@ -213,6 +216,19 @@ private static void appendWindowMetadata(StringBuilder xml, WindowMetadata metad
}
}

static void appendTextAttribute(StringBuilder xml, CharSequence text) {
if (text.length() <= MAX_TEXT_CHARS) {
appendAttribute(xml, "text", text);
return;
}
int end =
Character.isHighSurrogate(text.charAt(MAX_TEXT_CHARS - 1))
Comment thread
thymikee marked this conversation as resolved.
Resolved
? MAX_TEXT_CHARS - 1
: MAX_TEXT_CHARS;
appendAttribute(xml, "text", text.subSequence(0, end));
appendAttribute(xml, "text-clipped", "true");
}

private static void appendAttribute(StringBuilder xml, String name, CharSequence value) {
String stringValue = value == null ? "" : value.toString();
xml.append(' ');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ static void run() {
" window-bounds=\"[-2147483648,-1][0,2147483647]\"");
assertLongClickable(true, " long-clickable=\"true\"");
assertLongClickable(false, " long-clickable=\"false\"");
assertTextClipping();
}

private static void assertTextClipping() {
String complete = "x".repeat(AccessibilityTreeXml.MAX_TEXT_CHARS);
StringBuilder xml = new StringBuilder();
AccessibilityTreeXml.appendTextAttribute(xml, complete);
if (!xml.toString().equals(" text=\"" + complete + "\"")) {
throw new AssertionError("Text at the limit must stay complete and unmarked");
}
xml.setLength(0);
AccessibilityTreeXml.appendTextAttribute(xml, complete + "y");
if (!xml.toString().equals(" text=\"" + complete + "\" text-clipped=\"true\"")) {
throw new AssertionError("Text past the limit must keep its prefix and mark the clip");
}
String split = "x".repeat(AccessibilityTreeXml.MAX_TEXT_CHARS - 1) + "\uD83D\uDE00";
String prefix = split.substring(0, AccessibilityTreeXml.MAX_TEXT_CHARS - 1);
xml.setLength(0);
AccessibilityTreeXml.appendTextAttribute(xml, split);
if (!xml.toString().equals(" text=\"" + prefix + "\" text-clipped=\"true\"")) {
throw new AssertionError("A clip must not split a surrogate pair");
}
}

private static void assertLongClickable(boolean longClickable, String expected) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ const PRESENTATION_SCALAR_FIELDS = {
value: true,
contentDescription: true,
text: true,
textClipped: true,
identifier: true,
enabled: true,
editable: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
type SelectorSnapshotOptions,
captureSelectorSnapshot,
observationReadFailure,
refuseClippedText,
} from './selector-read-shared.ts';
import { deriveSelectorCapturePolicy } from './selector-capture-policy.ts';
import { absenceCaptureOptionRefusal } from '@agent-device/selectors/absence-observation';
Expand Down Expand Up @@ -156,6 +157,7 @@ async function resolveAssertedPredicate(
},
});
}
if (predicate === 'text') refuseClippedText(outcome.node);
const result = evaluateIsPredicate({
predicate,
node: outcome.node,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,24 @@ export async function captureSelectorSnapshot(
return { sessionName, session, snapshot };
}

/** A clipped text is only a prefix, so no text read or assertion may use it as the value. */
export function refuseClippedText(node: Pick<SnapshotNode, 'textClipped'>): void {
if (node.textClipped !== true) return;
throw new AppError(
'COMMAND_FAILED',
'The element text is clipped, so its full value is unknown',
{
reason: INTERACTION_ERROR_REASONS.textClipped.reason,
},
);
}

export async function readText(
runtime: AgentDeviceRuntime,
capture: CapturedSnapshot,
node: SnapshotNode,
): Promise<string> {
refuseClippedText(node);
Comment thread
thymikee marked this conversation as resolved.
Resolved
if (runtime.backend.readText) {
const result = await runtime.backend.readText(
toBackendContext(runtime, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,32 @@ test('runtime get reads text from a selector target', async () => {
]);
});

test('runtime get text and is text refuse a clipped node and accept the complete one', async () => {
const complete = selectorReadSnapshot();
const clipped = makeSnapshotState([{ ...complete.nodes[0]!, textClipped: true }]);
const read = (snapshot: typeof complete) =>
createSelectorDevice(snapshot).selectors.get({
session: 'default',
property: 'text',
target: { kind: 'selector', selector: 'label=Continue' },
});

const assertText = (snapshot: typeof complete) =>
createSelectorDevice(snapshot).selectors.is({
session: 'default',
predicate: 'text',
selector: 'label=Continue',
expectedText: 'Continue',
});
const isClipped = (error: unknown) =>
error instanceof AppError && error.details?.reason === 'text_clipped';

assert.equal((await read(complete)).kind, 'text');
await assertText(complete);
await assert.rejects(read(clipped), isClipped);
await assert.rejects(assertText(clipped), isClipped);
});

test('runtime get selector target captures fresh snapshot without a stored session snapshot', async () => {
const snapshot = selectorReadSnapshot();
const sessions = createMemorySessionStore([{ name: 'default' }]);
Expand Down
4 changes: 4 additions & 0 deletions packages/command-surface/src/interaction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,8 @@ const getCommandFacet = defineCommandFacet({
text: {
summary: 'Read element text or attributes',
searchHint: 'value label',
cliDetail:
'get text refuses a node marked textClipped with reason text_clipped: Android snapshots keep only a prefix of very long text.',
},
metadata: metadata('get'),
run: (client, input) => client.interactions.get(toGetOptions(input)),
Expand All @@ -666,6 +668,8 @@ const isCommandFacet = defineCommandFacet({
text: {
summary: 'Check a UI predicate on a selector',
searchHint: 'assert enabled',
cliDetail:
'is text refuses a node marked textClipped with reason text_clipped: a clipped prefix cannot prove the full value.',
},
metadata: metadata('is'),
run: (client, input) => client.interactions.is(input as IsOptions),
Expand Down
2 changes: 2 additions & 0 deletions packages/kernel/src/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,8 @@ export type RawSnapshotNode = {
* so `text ?? label` is the text the view shows.
*/
text?: string;
/** The Android helper capped the text, so `label` and `value` hold only its prefix. */
textClipped?: boolean;
identifier?: string;
rect?: Rect;
enabled?: boolean;
Expand Down
45 changes: 30 additions & 15 deletions packages/platform-android/src/__tests__/ime-helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a
replace?: boolean;
}> = [];
const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return { exitCode: 1, stdout: '', stderr: 'not found' };
}
if (isImeListCall(args)) {
Expand Down Expand Up @@ -119,24 +119,30 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a
assert.deepEqual(installCalls, [{ apkPath, replace: true }]);
});

test('ensureAndroidImeHelper skips install when a newer version is already present', async () => {
const tmpDir = await mkdtempForTest('ime-helper-current-');
test('ensureAndroidImeHelper replaces a newer installed version with the trusted artifact', async () => {
const tmpDir = await mkdtempForTest('ime-helper-newer-');
const apkPath = path.join(tmpDir, 'helper.apk');
await fs.writeFile(apkPath, 'helper-apk');
const calls: string[] = [];
const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return {
exitCode: 0,
stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode + 1}`,
stdout: `Package [${manifest.packageName}] (0):\n versionCode=${manifest.versionCode + 1}`,
stderr: '',
};
}
throw new Error(`unexpected adb call: ${args.join(' ')}`);
if (isImeListCall(args)) {
return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' };
}
calls.push(args.join(' '));
return { exitCode: 0, stdout: '', stderr: '' };
};
const adbProvider: AndroidAdbProvider = {
exec: adb,
install: async () => {
throw new Error('install should not be called when a newer version is present');
install: async (installApkPath) => {
calls.push(`install ${installApkPath}`);
return { exitCode: 0, stdout: '', stderr: '' };
},
};

Expand All @@ -147,8 +153,9 @@ test('ensureAndroidImeHelper skips install when a newer version is already prese
deviceKey: 'android:emulator-5554',
});

assert.equal(result.installed, false);
assert.equal(result.reason, 'current');
assert.equal(result.installed, true);
assert.equal(result.reason, 'newer');
assert.deepEqual(calls.slice(0, 2), [`uninstall ${PACKAGE}`, `install ${apkPath}`]);
});

test('ensureAndroidImeHelper returns from an install once the IME is registered', async () => {
Expand All @@ -157,7 +164,7 @@ test('ensureAndroidImeHelper returns from an install once the IME is registered'
await fs.writeFile(apkPath, 'helper-apk');
let imeListCalls = 0;
const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return { exitCode: 0, stdout: '', stderr: '' };
}
if (isImeListCall(args)) {
Expand Down Expand Up @@ -188,7 +195,7 @@ test('ensureAndroidImeHelper returns the install when the registration listing t
const apkPath = path.join(tmpDir, 'helper.apk');
await fs.writeFile(apkPath, 'helper-apk');
const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return { exitCode: 0, stdout: '', stderr: '' };
}
if (isImeListCall(args)) {
Expand Down Expand Up @@ -222,15 +229,19 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer
await fs.writeFile(apkPath, 'helper-apk');
let present = false;
const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return present
? {
exitCode: 0,
stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode}`,
stdout: `Package [${manifest.packageName}] (0):\n versionCode=${manifest.versionCode}`,
stderr: '',
}
: { exitCode: 0, stdout: '', stderr: '' };
}
if (args.join(' ') === `shell pm path ${PACKAGE}`) {
const stdout = present ? `package:/data/app/${PACKAGE}-1/base.apk\n` : '';
return { exitCode: present ? 0 : 1, stdout, stderr: '' };
}
if (isImeListCall(args)) {
return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' };
}
Expand All @@ -244,6 +255,10 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer
present = true;
return { exitCode: 0, stdout: '', stderr: '' };
},
pull: async (_remotePath, localPath) => {
await fs.writeFile(localPath, 'helper-apk');
return { exitCode: 0, stdout: '', stderr: '' };
},
};
const ensure = () =>
ensureAndroidImeHelper({
Expand All @@ -268,7 +283,7 @@ test('ensureAndroidImeHelper install timeout points at the OEM install dialog',
const apkPath = path.join(tmpDir, 'helper.apk');
await fs.writeFile(apkPath, 'helper-apk');
const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return { exitCode: 1, stdout: '', stderr: 'not found' };
}
throw new Error(`unexpected adb call: ${args.join(' ')}`);
Expand Down
18 changes: 15 additions & 3 deletions packages/platform-android/src/__tests__/ime-lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import assert from 'node:assert/strict';
import { promises as fsp } from 'node:fs';
import fs, { promises as fsp } from 'node:fs';
import path from 'node:path';
import { beforeEach, expect, test, vi } from 'vitest';
import { mkdtempForTest } from './test-utils/tmp-dir.ts';
import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts';
import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts';

const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService';
const SETTINGS_KEY = 'agent_device_ime_helper_previous_ime';
Expand Down Expand Up @@ -105,7 +106,7 @@ function fakeDeviceState(initialIme: string) {

function handleShowVersionCode(): FakeAdbResult {
return installed
? ok('package:com.callstack.agentdevice.imehelper versionCode:19002')
? ok('Package [com.callstack.agentdevice.imehelper] (0):\n versionCode=1')
: { exitCode: 1, stdout: '', stderr: 'not found' };
}

Expand Down Expand Up @@ -157,7 +158,18 @@ function fakeDeviceState(initialIme: string) {
};

const adb: AndroidAdbExecutor = async (args) => {
if (args.includes('--show-versioncode')) return handleShowVersionCode();
if (args.join(' ').includes('dumpsys package')) return handleShowVersionCode();
if (args.join(' ') === 'shell pm path com.callstack.agentdevice.imehelper') {
return ok('package:/data/app/com.callstack.agentdevice.imehelper/base.apk\n');
}
if (
args[0] === 'pull' &&
args[1] === '/data/app/com.callstack.agentdevice.imehelper/base.apk' &&
args[2]
) {
fs.copyFileSync(ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]);
return ok('1 file pulled\n');
}
const handler = handlers[args.slice(0, 3).join(' ')];
if (!handler) throw new Error(`unexpected adb call: ${args.join(' ')}`);
return handler(args);
Expand Down
6 changes: 3 additions & 3 deletions packages/platform-android/src/__tests__/input-actions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ afterEach(async () => {
});

/**
* Answers one helper session: the version probe says "current" so no install is faked, the viewport
* Answers one helper session: the version probe reports a newer helper, so the helper reinstalls, the viewport
* read reports `window` plus an optional IME window, and the gesture accepts whatever it is given.
*/
function helperRouteAdb(window: {
Expand All @@ -66,9 +66,9 @@ function helperRouteAdb(window: {
keyboard?: { x: number; y: number; width: number; height: number };
}) {
return (args: string[]) => {
if (args.includes('--show-versioncode')) {
if (args.join(' ').includes('dumpsys package')) {
return {
stdout: `package:${HELPER_MANIFEST.packageName} versionCode:999999`,
stdout: `Package [${HELPER_MANIFEST.packageName}] (0):\n versionCode=999999`,
Comment thread
thymikee marked this conversation as resolved.
Resolved
stderr: '',
};
}
Expand Down
Loading
Loading