From 24ca46508043b658ea7157f7d2ae867ea568605d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 14:04:40 +0100 Subject: [PATCH 01/26] fix(android): bound helper output and verify installed artifacts --- .../snapshothelper/AccessibilityTreeXml.java | 33 ++++--- .../src/__tests__/ime-helper.test.ts | 21 ++--- .../src/__tests__/ime-lifecycle.test.ts | 16 +++- .../src/__tests__/input-actions.test.ts | 16 ++-- .../src/__tests__/settings-locale.test.ts | 32 +++---- .../snapshot-capture-failure-reason.test.ts | 12 ++- .../src/__tests__/snapshot-capture.test.ts | 10 +-- .../snapshot-helper-exit-result.test.ts | 14 ++- ...snapshot-helper-session-touch-peer.test.ts | 22 +++++ .../snapshot-helper-session.fixtures.ts | 8 +- .../src/__tests__/snapshot-helper.test.ts | 90 ++++++++----------- .../__tests__/snapshot-quality-fixtures.ts | 14 ++- .../src/__tests__/snapshot-results.test.ts | 29 ++---- .../src/__tests__/snapshot.test.ts | 51 ++++------- .../test-utils/android-snapshot-helper.ts | 46 ++++++---- .../test-utils/android-snapshot-test-world.ts | 13 ++- .../text-input-fill-helper-lifecycle.test.ts | 8 +- .../__tests__/touch-helper-session.test.ts | 23 ++--- .../src/__tests__/touch-helper.fixtures.ts | 20 ++--- .../src/helper-package-install.ts | 22 ++++- .../src/snapshot-helper-install.ts | 21 ++++- .../src/snapshot-helper-session-protocol.ts | 26 +++++- ...android-snapshot-occlusion-context.test.ts | 10 +-- .../test-utils/android-snapshot-helper.ts | 32 +++++++ .../provider-scenarios/android-find.test.ts | 23 ++++- .../android-ime-lifecycle-world.ts | 14 ++- .../composite-deadline.test.ts | 37 +++++--- website/docs/docs/error-reasons.md | 7 ++ 28 files changed, 408 insertions(+), 262 deletions(-) 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 9b0a5583016..0607f2c0b67 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 @@ -12,6 +12,9 @@ /** Serializes accessibility nodes using the helper's host-consumed XML contract. */ final class AccessibilityTreeXml { + private static final int MAX_XML_CHARS = 8 * 1024 * 1024; + private static final int MAX_APP_ATTRIBUTE_CHARS = 64 * 1024; + private AccessibilityTreeXml() {} @SuppressWarnings("deprecation") @@ -24,7 +27,7 @@ static void appendNode( int maxNodes, Stats stats, WindowMetadata windowMetadata) { - if (stats.nodeCount >= maxNodes) { + if (stats.nodeCount >= maxNodes || xml.length() >= MAX_XML_CHARS) { stats.truncated = true; return; } @@ -39,7 +42,7 @@ static void appendNode( } CharSequence text = node.getText(); if (text != null) { - appendAttribute(xml, "text", text); + appendAppAttribute(xml, "text", text, stats); } // 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 @@ -48,18 +51,18 @@ static void appendNode( appendAttribute(xml, "hint-showing", Boolean.toString(node.isShowingHintText())); // The hint itself, whether or not the field is showing it: `text` holds the hint only while // the field is empty, so a filled field's placeholder is readable nowhere else. - appendNonEmptyAttribute(xml, "hint", node.getHintText()); + appendAppAttribute(xml, "hint", node.getHintText(), stats); } appendAttribute(xml, "editable", Boolean.toString(node.isEditable())); // Accessibility selection offsets, not a measurement of the value's length. Read-only // selectable text exposes a selection too, so they do not depend on `editable`; -1 = unavailable. appendNonNegativeAttribute(xml, "selection-start", node.getTextSelectionStart()); appendNonNegativeAttribute(xml, "selection-end", node.getTextSelectionEnd()); - appendNonEmptyAttribute(xml, "resource-id", node.getViewIdResourceName()); - appendAttribute(xml, "class", node.getClassName()); - appendNonEmptyAttribute(xml, "package", node.getPackageName()); - appendNonEmptyAttribute(xml, "content-desc", node.getContentDescription()); - appendNonEmptyAttribute(xml, "role-description", roleDescription(node)); + appendAppAttribute(xml, "resource-id", node.getViewIdResourceName(), stats); + appendAppAttribute(xml, "class", node.getClassName(), stats); + appendAppAttribute(xml, "package", node.getPackageName(), stats); + appendAppAttribute(xml, "content-desc", node.getContentDescription(), stats); + appendAppAttribute(xml, "role-description", roleDescription(node), stats); appendTrueAttribute(xml, "heading", isHeading(node)); appendAttribute(xml, "visible-to-user", Boolean.toString(node.isVisibleToUser())); appendDrawingOrderAttribute(xml, node); @@ -108,7 +111,7 @@ static void appendNode( xml.append(">"); int index = 0; - while (index < childCount && stats.nodeCount < maxNodes) { + while (index < childCount && stats.nodeCount < maxNodes && xml.length() < MAX_XML_CHARS) { int count = Math.min( AccessibilityReadBatch.MAX_READS, Math.min(childCount - index, maxNodes - stats.nodeCount)); int offset = 0; @@ -116,7 +119,7 @@ static void appendNode( new AccessibilityReadBatch<>( index, count, childIndex -> AccessibilityNodeReads.child(node, childIndex), AccessibilityNodeInfo::recycle)) { - for (; offset < count && stats.nodeCount < maxNodes; offset += 1) { + for (; offset < count && stats.nodeCount < maxNodes && xml.length() < MAX_XML_CHARS; offset += 1) { AccessibilityNodeInfo child = children.get(offset); if (child != null) { appendNode(xml, child, index + offset, depth + 1, maxDepth, maxNodes, stats, null); @@ -168,6 +171,14 @@ private static void appendNonEmptyAttribute( appendAttribute(xml, name, value); } + private static void appendAppAttribute( + StringBuilder xml, String name, CharSequence value, Stats stats) { + if (value == null || value.length() == 0) return; + int length = Math.min(value.length(), MAX_APP_ATTRIBUTE_CHARS); + if (length < value.length()) stats.truncated = true; + appendAttribute(xml, name, value.subSequence(0, length)); + } + private static void appendNonNegativeAttribute(StringBuilder xml, String name, int value) { if (value >= 0) { appendAttribute(xml, name, Integer.toString(value)); @@ -242,7 +253,7 @@ private static void appendScreenReaderFacts( appendTrueAttribute( xml, "focus-action", hasAccessibilityAction(node, AccessibilityAction.ACTION_FOCUS)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - appendNonEmptyAttribute(xml, "state-description", node.getStateDescription()); + appendAppAttribute(xml, "state-description", node.getStateDescription(), stats); } appendTrueAttribute(xml, "collection", node.getCollectionInfo() != null); appendTrueAttribute(xml, "range", node.getRangeInfo() != null); diff --git a/packages/platform-android/src/__tests__/ime-helper.test.ts b/packages/platform-android/src/__tests__/ime-helper.test.ts index 1b93ec47d26..507502127f8 100644 --- a/packages/platform-android/src/__tests__/ime-helper.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper.test.ts @@ -119,7 +119,7 @@ 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 () => { +test('ensureAndroidImeHelper refuses a newer helper whose digest is not trusted', async () => { const tmpDir = await mkdtempForTest('ime-helper-current-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -140,15 +140,16 @@ test('ensureAndroidImeHelper skips install when a newer version is already prese }, }; - const result = await ensureAndroidImeHelper({ - adb, - adbProvider, - artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, - deviceKey: 'android:emulator-5554', - }); - - assert.equal(result.installed, false); - assert.equal(result.reason, 'current'); + await assert.rejects( + ensureAndroidImeHelper({ + adb, + adbProvider, + artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, + deviceKey: 'android:emulator-5554', + }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'android_helper_newer_untrusted', + ); }); test('ensureAndroidImeHelper returns from an install once the IME is registered', async () => { diff --git a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts index 6d37d8638c5..eb7b2e6532c 100644 --- a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts @@ -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'; @@ -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 versionCode:1') : { exitCode: 1, stdout: '', stderr: 'not found' }; } @@ -158,6 +159,17 @@ function fakeDeviceState(initialIme: string) { const adb: AndroidAdbExecutor = async (args) => { if (args.includes('--show-versioncode')) 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); diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index c31b6ff6426..9b96777cdaf 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -19,7 +19,10 @@ import { withFakeAdb } from './test-utils/fake-adb.ts'; import { withAndroidAdbProvider } from '../adb-executor.ts'; import type { AndroidTouchInjector } from '../adb-executor.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; import { ANDROID_TOUCH_HELPER_MANIFEST as HELPER_MANIFEST, androidTouchHelperResultRecord as helperRecord, @@ -66,12 +69,11 @@ function helperRouteAdb(window: { keyboard?: { x: number; y: number; width: number; height: number }; }) { return (args: string[]) => { - if (args.includes('--show-versioncode')) { - return { - stdout: `package:${HELPER_MANIFEST.packageName} versionCode:999999`, - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args, { + apkPath: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, + manifest: HELPER_MANIFEST, + }); + if (installedHelper) return installedHelper; if (args.includes('viewport')) { const { keyboard, ...app } = window; return { diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts index fc4d360de38..0ff277d644f 100644 --- a/packages/platform-android/src/__tests__/settings-locale.test.ts +++ b/packages/platform-android/src/__tests__/settings-locale.test.ts @@ -199,22 +199,21 @@ test('settings locale runs app_process from the base APK whose digest it verifie const firstCalls = calls.length; helper.pulls.length = 0; await setAndroidSetting(device, 'locale', 'de-DE'); - // The cached install decision skipped the package manager, yet the base APK was hashed. - expect(calls.slice(firstCalls).map((args) => args.join(' '))).not.toContain(VERSION_QUERY); + // The cached decision rechecks package presence before the base APK is hashed. + expect(calls.slice(firstCalls).map((args) => args.join(' '))).toContain(VERSION_QUERY); expect(helper.pulls).toEqual([APK]); expect(helper.launches).toEqual([APK, APK]); }); }); -test('settings locale refuses a newer installed helper APK whose digest the manifest does not name', async () => { +test('settings locale refuses a newer installed helper before running its code', async () => { await withHelperDevice( async ({ device, helper }) => { await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { - reason: 'locale-helper-apk-unverified', - dispatched: 'no', - apkPath: APK, + reason: 'android_helper_newer_untrusted', + installedVersionCode: VERSION_CODE + 1, }, }); expect(helper.launches).toEqual([]); @@ -230,18 +229,22 @@ test('a locale refusal keeps the snapshot install memo and makes the next locale details: { reason: 'locale-helper-apk-unverified' }, }); - // The snapshot install step answers from its memo without touching the device. + // The snapshot install memo rechecks package presence before answering current. const snapshotCalls: (readonly string[])[] = []; const install = await ensureAndroidSnapshotHelper({ adb: async (args) => { snapshotCalls.push(args); - return { stdout: '', stderr: 'unexpected', exitCode: 1 }; + return { + stdout: `package:${PACKAGE} versionCode:${VERSION_CODE}`, + stderr: '', + exitCode: 0, + }; }, artifact, deviceKey: `android:${device.id}`, }); expect(install).toMatchObject({ reason: 'current', installed: false }); - expect(snapshotCalls).toEqual([]); + expect(snapshotCalls.map((args) => args.join(' '))).toEqual([VERSION_QUERY]); const firstCall = calls.length; await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ @@ -250,7 +253,7 @@ test('a locale refusal keeps the snapshot install memo and makes the next locale expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); expect(helper.launches).toEqual([]); }, - { versionCode: VERSION_CODE + 1, bytes: 'another-apk' }, + { versionCode: undefined, installs: 'another-apk' }, ); }); @@ -317,7 +320,7 @@ test('settings locale refuses a helper package replaced after a cached install d apkPath: helper.apkPath, }, }); - expect(calls.slice(firstCall).map((args) => args.join(' '))).not.toContain(VERSION_QUERY); + expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); expect(helper.launches).toHaveLength(1); // The genuine helper is back; the next locale command inspects the package again. @@ -372,8 +375,7 @@ test('settings locale refuses with dispatched no when pm path reports no base AP expect(helper.launches).toEqual([]); }, { - // A newer versionCode lets the install step accept the package without reading its path. - versionCode: VERSION_CODE + 1, + versionCode: VERSION_CODE, override: (args) => args.join(' ') === `shell pm path ${PACKAGE}` ? 'package:/data/app/split_config.arm64_v8a.apk\n' @@ -400,7 +402,7 @@ test('settings locale keeps the adb classification when pm path fails on the tra expect(helper.launches).toEqual([]); }, { - versionCode: VERSION_CODE + 1, + versionCode: VERSION_CODE, override: (args) => args.join(' ') === `shell pm path ${PACKAGE}` ? { stderr: 'error: device offline', exitCode: 1 } @@ -423,7 +425,7 @@ test('settings locale keeps the adb failure when the base APK cannot be pulled', expect(helper.launches).toEqual([]); }, { - versionCode: VERSION_CODE + 1, + versionCode: VERSION_CODE, // `pm path` names a base APK that the pull cannot read. override: (args) => args.join(' ') === `shell pm path ${PACKAGE}` diff --git a/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts b/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts index bded0d90741..ba913765e83 100644 --- a/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts @@ -7,7 +7,10 @@ import type { AndroidAdbExecutor, AndroidAdbExecutorResult } from '../adb-execut import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; import { isAndroidSnapshotTimeoutError } from '@agent-device/capture-kit/snapshot-timeout-policy'; import './test-utils/android-host-test-setup.ts'; @@ -55,12 +58,7 @@ function createHelperAdb( } function helperVersionResponse(args: readonly string[]): AndroidAdbExecutorResult | undefined { - if (!args.includes('--show-versioncode')) return undefined; - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', - stderr: '', - }; + return trustedInstalledSnapshotHelperResult(args); } function isHelperForceStop(args: readonly string[]): boolean { diff --git a/packages/platform-android/src/__tests__/snapshot-capture.test.ts b/packages/platform-android/src/__tests__/snapshot-capture.test.ts index 4f6cc026dd7..69d276a17bd 100644 --- a/packages/platform-android/src/__tests__/snapshot-capture.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-capture.test.ts @@ -16,6 +16,7 @@ import { androidSnapshotQualityDevice as device, androidSnapshotQualityHelperArtifact as helperArtifact, } from './snapshot-quality-fixtures.ts'; +import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; const SCREEN_XML = ''; @@ -70,13 +71,8 @@ function helperAdbServing( 'INSTRUMENTATION_CODE: 0', ].join('\n'); return async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) { return { exitCode: 0, stdout, stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts index 99a03b85c20..1e1a3e5b988 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts @@ -30,7 +30,10 @@ import { isAndroidHelperRuntimeProbe, } from './snapshot-helper-session.fixtures.ts'; import { mkdtempForTest } from './test-utils/tmp-dir.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; beforeEach(async () => { resetAndroidSnapshotHelperRetirements(); @@ -103,13 +106,8 @@ function encodedPayload(xml: string): string { function helperFailingWith(run: FailedRun): AndroidAdbExecutor { return async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); if (isAndroidHelperRuntimeForceStop(args)) return { exitCode: 0, stdout: '', stderr: '' }; return { stderr: '', ...run }; diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts index a6d118df701..efb7e9d440d 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts @@ -79,6 +79,28 @@ async function listenOnce(onSocket: (socket: net.Socket) => void) { return { port: address.port, close }; } +test('authenticated helper response stops at its byte ceiling', async () => { + const listener = await listenOnce((socket) => { + onSessionCommand(socket, () => { + socket.write(Buffer.alloc(16 * 1024 * 1024 + 1)); + }); + }); + try { + await assert.rejects( + sendAndroidSnapshotHelperSessionCommand( + { port: listener.port, secret: Buffer.from(FIXTURE_SESSION_SECRET, 'hex') }, + 'snapshot req-oversized', + 5_000, + ), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'android_snapshot_helper_session_response_too_large', + ); + } finally { + await listener.close(); + } +}); + test.each([ { label: 'a refused connection', closedBeforeConnect: true }, { label: 'a socket that closes before the hello', closedBeforeConnect: false }, diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts index 1761c06bd6e..5ce3a25a9e9 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -25,10 +25,11 @@ import { } from '../snapshot-helper-types.ts'; import type { AndroidAdbExecutor } from '../snapshot-helper-types.ts'; import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts'; +import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; export const ANDROID_HELPER_INSTALLED_VERSION_PROBE = { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13003', stderr: '', }; @@ -502,9 +503,8 @@ function persistentSnapshotExecResult( options: PersistentSnapshotHelperProviderOptions, args: readonly string[], ): ReturnType { - if (args.includes('--show-versioncode')) { - return Promise.resolve(ANDROID_HELPER_INSTALLED_VERSION_PROBE); - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return Promise.resolve(installedHelper); // A current adb: it negotiated shell protocol v2, so a host exit status is the device's. if (args[0] === 'features') { return Promise.resolve({ exitCode: 0, stdout: 'cmd\nstat_v2\nshell_v2\n', stderr: '' }); diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index cc6e8ff8200..59a401db7d6 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -173,7 +173,7 @@ test('parseAndroidSnapshotHelperOutput falls back to error type for null helper }); }); -test('ensureAndroidSnapshotHelper installs when missing and skips a newer version', async () => { +test('ensureAndroidSnapshotHelper installs when missing and refuses an untrusted newer version', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -199,17 +199,18 @@ test('ensureAndroidSnapshotHelper installs when missing and skips a newer versio assert.equal(installed.reason, 'missing'); assert.deepEqual(calls[1], ['install', '-r', apkPath]); - const skipped = await ensureAndroidSnapshotHelper({ - adb: async () => ({ - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', + await assert.rejects( + ensureAndroidSnapshotHelper({ + adb: async () => ({ + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }), + artifact: { apkPath, manifest: localManifest }, }), - artifact: { apkPath, manifest: localManifest }, - }); - - assert.equal(skipped.installed, false); - assert.equal(skipped.reason, 'current'); + (error: unknown) => + error instanceof AppError && error.details?.reason === 'android_helper_newer_untrusted', + ); }); test('ensureAndroidSnapshotHelper tags a device-side install rejection distinctly from artifact resolution', async () => { @@ -408,11 +409,19 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an sha256: sha256Text('helper-apk'), }; const calls: (readonly string[])[] = []; + let installedVersionCode: number | undefined; const adb: AndroidAdbExecutor = async (args) => { calls.push(args); if (args.includes('--show-versioncode')) { - return { exitCode: 1, stdout: '', stderr: 'not found' }; + return installedVersionCode === undefined + ? { exitCode: 1, stdout: '', stderr: 'not found' } + : { + exitCode: 0, + stdout: `package:${localManifest.packageName} versionCode:${installedVersionCode}`, + stderr: '', + }; } + if (args[0] === 'install') installedVersionCode = localManifest.versionCode; return { exitCode: 0, stdout: '', stderr: '' }; }; const artifact = { apkPath, manifest: localManifest }; @@ -433,18 +442,7 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an assert.equal(cached.reason, 'current'); assert.equal(cached.installed, false); assert.equal(cached.installedVersionCode, localManifest.versionCode); - assert.deepEqual(calls, [ - [ - 'shell', - 'cmd', - 'package', - 'list', - 'packages', - '--show-versioncode', - localManifest.packageName, - ], - ['install', '-r', apkPath], - ]); + assert.equal(calls.filter((args) => args[0] === 'install').length, 1); await fs.writeFile(apkPath, 'helper-apk'); await ensureAndroidSnapshotHelper({ @@ -452,7 +450,7 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an artifact, deviceKey: 'android:device-2', }); - assert.equal(calls.length, 4); + assert.equal(calls.filter((args) => args[0] === 'install').length, 2); forgetAndroidSnapshotHelperInstall({ deviceKey: 'android:emulator-5554', @@ -464,7 +462,7 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an artifact, deviceKey: 'android:emulator-5554', }); - assert.equal(calls.length, 6); + assert.equal(calls.filter((args) => args[0] === 'install').length, 3); }); test('ensureAndroidSnapshotHelper always policy bypasses cached install result', async () => { @@ -489,11 +487,15 @@ test('ensureAndroidSnapshotHelper always policy bypasses cached install result', }; const artifact = { apkPath, manifest: localManifest }; - const cached = await ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:emulator-5554', - }); + await assert.rejects( + ensureAndroidSnapshotHelper({ + adb, + artifact, + deviceKey: 'android:emulator-5554', + }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'android_helper_newer_untrusted', + ); const forced = await ensureAndroidSnapshotHelper({ adb, artifact, @@ -501,30 +503,12 @@ test('ensureAndroidSnapshotHelper always policy bypasses cached install result', installPolicy: 'always', }); - assert.equal(cached.reason, 'current'); assert.equal(forced.reason, 'forced'); assert.equal(forced.installed, true); - assert.deepEqual(calls, [ - [ - 'shell', - 'cmd', - 'package', - 'list', - 'packages', - '--show-versioncode', - localManifest.packageName, - ], - [ - 'shell', - 'cmd', - 'package', - 'list', - 'packages', - '--show-versioncode', - localManifest.packageName, - ], - ['install', '-r', apkPath], - ]); + assert.deepEqual( + calls.filter((args) => args[0] === 'install'), + [['install', '-r', apkPath]], + ); }); test('shared Android helper verifier rejects snapshot helper checksum mismatch', async () => { diff --git a/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts b/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts index c7f3434204a..695e62ea1bd 100644 --- a/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts @@ -1,5 +1,8 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; import type { AndroidAdbExecutor } from '../snapshot-helper.ts'; export const androidSnapshotQualityDevice: DeviceInfo = { @@ -12,15 +15,10 @@ export const androidSnapshotQualityDevice: DeviceInfo = { export const androidSnapshotQualityHelperArtifact = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT; -const installedHelperProbe = { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', -}; - export function androidSnapshotQualityHelperAdb(xml: string): AndroidAdbExecutor { return async (args) => { - if (args.includes('--show-versioncode')) return installedHelperProbe; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/snapshot-results.test.ts b/packages/platform-android/src/__tests__/snapshot-results.test.ts index 21d82352d86..e2389a4ba8f 100644 --- a/packages/platform-android/src/__tests__/snapshot-results.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-results.test.ts @@ -22,10 +22,8 @@ import { AppError } from '@agent-device/kernel/errors'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; import { type AndroidAdbExecutor } from '../snapshot-helper.ts'; -import { - androidHelperInstrumentationOutput as helperOutput, - ANDROID_HELPER_INSTALLED_VERSION_PROBE as installedHelperProbe, -} from './snapshot-helper-session.fixtures.ts'; +import { androidHelperInstrumentationOutput as helperOutput } from './snapshot-helper-session.fixtures.ts'; +import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; import { mockSleep, @@ -45,13 +43,8 @@ afterEach(async () => { test('snapshotAndroid emits helper failure diagnostics', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') return { exitCode: 0, stdout: '', stderr: '' }; return { exitCode: 1, stdout: '', stderr: 'helper unavailable' }; @@ -196,7 +189,8 @@ test('snapshotAndroid fails closed after unparseable helper output', async () => const calls: (readonly string[])[] = []; const helperAdb: AndroidAdbExecutor = async (args) => { calls.push(args); - if (args.includes('--show-versioncode')) return installedHelperProbe; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) return { exitCode: 0, stdout: '', stderr: '' }; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; @@ -250,14 +244,9 @@ test('snapshotAndroid re-probes helper install after helper capture failure', as let versionProbeCount = 0; let instrumentAttempts = 0; const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { - versionProbeCount += 1; - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + if (args.includes('--show-versioncode')) versionProbeCount += 1; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) { instrumentAttempts += 1; if (instrumentAttempts === 1) { diff --git a/packages/platform-android/src/__tests__/snapshot.test.ts b/packages/platform-android/src/__tests__/snapshot.test.ts index e1e4f79ecf4..b29d7c78390 100644 --- a/packages/platform-android/src/__tests__/snapshot.test.ts +++ b/packages/platform-android/src/__tests__/snapshot.test.ts @@ -27,7 +27,6 @@ import { androidHelperInstrumentationOutput as helperOutput, createPersistentSnapshotHelperProvider, isAndroidHelperRuntimeForceStop as isHelperRuntimeReset, - ANDROID_HELPER_INSTALLED_VERSION_PROBE as installedHelperProbe, androidSystemWindowOnlyXml, type FakeAndroidProcess, } from './snapshot-helper-session.fixtures.ts'; @@ -45,6 +44,7 @@ import { captureDiagnostics, resetSnapshotTestState, } from './test-utils/android-snapshot-test-world.ts'; +import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; beforeEach(resetSnapshotTestState); @@ -205,13 +205,8 @@ test('snapshotAndroid uses the injected helper artifact', async () => { const timeouts: Array = []; const helperAdb: AndroidAdbExecutor = async (args, options) => { timeouts.push(options?.timeoutMs); - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) { return { exitCode: 0, @@ -233,13 +228,14 @@ test('snapshotAndroid uses the injected helper artifact', async () => { assert.equal(result.androidSnapshot.installReason, 'current'); assert.equal(result.androidSnapshot.captureMode, 'interactive-windows'); assert.equal(result.androidSnapshot.windowCount, 1); - assert.deepEqual(timeouts, [5000, 30000]); + assert.deepEqual(timeouts, [5000, 10000, 10000, 30000]); assert.equal(mockRunCmd.mock.calls.length, 0); }); test('snapshotAndroid reports helper-side truncation on the public snapshot result', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) return installedHelperProbe; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) { return { exitCode: 0, @@ -268,7 +264,8 @@ test('snapshotAndroid reports helper-side truncation on the public snapshot resu test('snapshotAndroid discloses unavailable sibling order for API 23 helper trees', async () => { const captured: string[] = []; const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) return installedHelperProbe; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) { const xml = captured.shift(); if (!xml) throw new Error('unexpected extra capture'); @@ -291,13 +288,8 @@ test('snapshotAndroid discloses unavailable sibling order for API 23 helper tree test('snapshotAndroid emits helper phase diagnostics', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args.includes('instrument')) { return { exitCode: 0, @@ -333,13 +325,8 @@ test('snapshotAndroid resolves helper adb through scoped provider', async () => snapshotHelperArtifact: helperArtifact, exec: async (args) => { adbCalls.push(args); - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (isAndroidSdkVersionCommand(args)) { return { exitCode: 0, stdout: '35', stderr: '' }; } @@ -368,7 +355,7 @@ test('snapshotAndroid resolves helper adb through scoped provider', async () => assert.equal(result.androidSnapshot.helperVersion, helperArtifact.manifest.version); assert.deepEqual( adbCalls.map((args) => args[0]), - ['shell', 'shell'], + ['shell', 'shell', 'pull', 'shell'], ); assert.equal(mockRunCmd.mock.calls.length, 0); }); @@ -595,13 +582,8 @@ test('snapshotAndroid fails closed when the helper fails', async () => { const adbCalls: (readonly string[])[] = []; const helperAdb: AndroidAdbExecutor = async (args) => { adbCalls.push(args); - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } @@ -624,7 +606,8 @@ test('snapshotAndroid fails closed when helper returns only system windows', asy const helperXml = androidSystemWindowOnlyXml(); const helperAdb: AndroidAdbExecutor = async (args) => { adbCalls.push(args); - if (args.includes('--show-versioncode')) return installedHelperProbe; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts b/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts index fc75575b560..9341e8a7525 100644 --- a/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts +++ b/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts @@ -1,5 +1,6 @@ import { fileURLToPath } from 'node:url'; -import type { AndroidAdbExecutor } from '../../adb-executor.ts'; +import fs from 'node:fs'; +import type { AndroidAdbExecutor, AndroidAdbExecutorResult } from '../../adb-executor.ts'; import type { AndroidSnapshotHelperArtifact } from '../../snapshot-helper-types.ts'; const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; @@ -26,18 +27,38 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti }, }; +export function trustedInstalledSnapshotHelperResult( + args: readonly string[], + artifact: { + apkPath: string; + manifest: { packageName: string; versionCode: number }; + } = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, +): AndroidAdbExecutorResult | undefined { + const packageName = artifact.manifest.packageName; + if (args.includes('--show-versioncode') && args.includes(packageName)) { + return { + exitCode: 0, + stdout: `package:${packageName} versionCode:${artifact.manifest.versionCode}\n`, + stderr: '', + }; + } + if (args.join(' ') === `shell pm path ${packageName}`) { + return { exitCode: 0, stdout: `package:/data/app/${packageName}/base.apk\n`, stderr: '' }; + } + if (args[0] === 'pull' && args[1] === `/data/app/${packageName}/base.apk` && args[2]) { + fs.copyFileSync(artifact.apkPath, args[2]); + return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; + } + return undefined; +} + export function createAndroidSnapshotHelperExecutor(options: { readonly exec: AndroidAdbExecutor; readonly captureXml: () => string | Promise; }): AndroidAdbExecutor { return async (args, execOptions) => { - if (isAndroidSnapshotHelperVersionProbe(args)) { - return { - exitCode: 0, - stdout: `package:${SNAPSHOT_HELPER_PACKAGE} versionCode:999999`, - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (isAndroidSnapshotHelperCapture(args)) { return { exitCode: 0, @@ -69,17 +90,12 @@ function androidSnapshotHelperOutput(xml: string): string { ].join('\n'); } -function isAndroidSnapshotHelperVersionProbe(args: readonly string[]): boolean { - return args.includes('--show-versioncode') && args.includes(SNAPSHOT_HELPER_PACKAGE); -} - export function androidSnapshotHelperScriptResponse( args: readonly string[], captureXml: () => string, ): string | undefined { - if (isAndroidSnapshotHelperVersionProbe(args)) { - return `package:${SNAPSHOT_HELPER_PACKAGE} versionCode:999999`; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper.stdout; if (isAndroidSnapshotHelperCapture(args)) return androidSnapshotHelperOutput(captureXml()); return undefined; } diff --git a/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts b/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts index 798a41539fc..0b5509bd76b 100644 --- a/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts +++ b/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts @@ -10,11 +10,13 @@ import { resetAndroidSnapshotHelperInstallCache } from '../../snapshot-helper-in import { resetAndroidSnapshotHelperSessions } from '../../snapshot-helper-session-lifecycle.ts'; import type { AndroidAdbExecutor } from '../../snapshot-helper.ts'; import { mkdtempForTest } from './android-host-test-setup.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './android-snapshot-helper.ts'; import { androidHelperInstrumentationOutput as helperOutput, isAndroidHelperRuntimeForceStop as isHelperRuntimeReset, - ANDROID_HELPER_INSTALLED_VERSION_PROBE as installedHelperProbe, } from '../snapshot-helper-session.fixtures.ts'; export const VALID_PNG = Buffer.from( @@ -54,7 +56,8 @@ export function createHelperAdb( handlers: Partial>, ): AndroidAdbExecutor { return async (args, options) => { - if (isHelperVersionProbe(args)) return installedHelperProbe; + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (isHelperRuntimeReset(args)) { return { exitCode: 0, stdout: '', stderr: '' }; } @@ -65,10 +68,6 @@ export function createHelperAdb( }; } -function isHelperVersionProbe(args: readonly string[]): boolean { - return args.includes('--show-versioncode'); -} - function helperAdbOperation(args: readonly string[]): 'instrument' | 'activity' | undefined { if (args.includes('instrument')) return 'instrument'; return args.includes('dumpsys') && args.includes('activity') ? 'activity' : undefined; diff --git a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts index 40565921ef6..3423419ad25 100644 --- a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts @@ -87,7 +87,13 @@ function createFillWorld( if (options.shellTextError) throw options.shellTextError; fieldText = args[3] ?? ''; } - if (args.includes('--show-versioncode')) return await persistent.exec(args, execOptions); + if ( + args.includes('--show-versioncode') || + args.join(' ') === 'shell pm path com.callstack.agentdevice.snapshothelper' || + args[0] === 'pull' + ) { + return await persistent.exec(args, execOptions); + } if (args[0] === 'shell' && args[1] !== 'am') return { exitCode: 0, stdout: '', stderr: '' }; return await persistent.exec(args, execOptions); }, diff --git a/packages/platform-android/src/__tests__/touch-helper-session.test.ts b/packages/platform-android/src/__tests__/touch-helper-session.test.ts index b66d24e6a1c..9a3528ce919 100644 --- a/packages/platform-android/src/__tests__/touch-helper-session.test.ts +++ b/packages/platform-android/src/__tests__/touch-helper-session.test.ts @@ -28,7 +28,10 @@ import { executeAndroidTouchHelperPlan, readAndroidTouchHelperViewportReading, } from '../touch-helper.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; import { ANDROID_TOUCH_HELPER_MANIFEST as manifest, androidTouchHelperResultRecord as resultRecord, @@ -372,13 +375,8 @@ test('a provider artifact that mismatches the live session helper stops it and r // Artifact B is already current on the device, so no install happens: the session started // by artifact A must be invalidated by the helper-identity guard, not the install path. exec: async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: `package:${providerArtifact.manifest.packageName} versionCode:999999`, - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args, providerArtifact); + if (installedHelper) return installedHelper; instrumentArgs = [...args]; return { exitCode: 0, @@ -443,13 +441,8 @@ test('a same-version artifact with a different sha stops the live session and ru // A is reported already current by versionCode, so no install occurs: only the sha in the // session helper identity can reveal that the live session runs B's binary. exec: async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: `package:${artifactA.manifest.packageName} versionCode:999999`, - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args, artifactA); + if (installedHelper) return installedHelper; instrumentArgs = [...args]; return { exitCode: 0, diff --git a/packages/platform-android/src/__tests__/touch-helper.fixtures.ts b/packages/platform-android/src/__tests__/touch-helper.fixtures.ts index f5cd36e57fd..67eaf59f71b 100644 --- a/packages/platform-android/src/__tests__/touch-helper.fixtures.ts +++ b/packages/platform-android/src/__tests__/touch-helper.fixtures.ts @@ -3,6 +3,10 @@ import { buildGesturePlan } from '@agent-device/gestures/gesture-plan'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { AndroidAdbExecutor } from '../adb-executor.ts'; import type { AndroidLongPressTouchPlan } from '../touch-plan-lowering.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; // The one-shot touch helper path now runs through the snapshot-helper APK/runner // (issue #1275 consolidation), so these fixtures mirror the snapshot helper's @@ -63,18 +67,14 @@ export function flingPlan() { ); } -// Wraps an executor that answers the shared install-decision probe as "already -// current" (a much newer installed versionCode) so tests can focus on the -// gesture/viewport call that follows without also faking an install flow. +// Wraps an executor that presents the trusted fixture APK as already installed. export function currentVersionAdb(handleInstrument: AndroidAdbExecutor): AndroidAdbExecutor { return async (args, options) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: `package:${ANDROID_TOUCH_HELPER_MANIFEST.packageName} versionCode:999999`, - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args, { + apkPath: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, + manifest: ANDROID_TOUCH_HELPER_MANIFEST, + }); + if (installedHelper) return installedHelper; return handleInstrument(args, options); }; } diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts index 7a5c7c461b6..097af372cee 100644 --- a/packages/platform-android/src/helper-package-install.ts +++ b/packages/platform-android/src/helper-package-install.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type ReasonTable } from '@agent-device/kernel/errors'; import { findProjectRoot, readVersion } from '@agent-device/host-kit/version'; import { androidAdbResultError, @@ -24,6 +24,10 @@ import { export type { AndroidHelperInstallDecision, InstalledAndroidHelperState }; const ANDROID_HELPER_IDENTITY_TIMEOUT_MS = 10_000; +export const ANDROID_HELPER_ADMISSION_REASONS = { + // The installed helper has a higher version than the bundled artifact and cannot be trusted. + newerUntrusted: { reason: 'android_helper_newer_untrusted' }, +} as const satisfies ReasonTable<'android helper'>; /** * The one install seam every Android helper APK crosses, so an install timeout carries the @@ -70,7 +74,7 @@ async function ensureAndroidHelperPackageInstalled(options: { // The cache skips the checksums, never the presence check: an emulator that is wiped or // restored from a snapshot keeps its serial but may no longer have the helper. const installedVersionCode = await readInstalledAndroidPackageVersionCode(adb, packageName); - if (installedVersionCode !== undefined && installedVersionCode >= versionCode) { + if (installedVersionCode === versionCode) { return { packageName, versionCode, @@ -99,6 +103,19 @@ async function ensureAndroidHelperPackageInstalled(options: { }; } + if (state.installedVersionCode !== undefined && state.installedVersionCode > versionCode) { + throw new AppError( + 'COMMAND_FAILED', + 'Installed Android helper is newer than the trusted artifact.', + { + reason: ANDROID_HELPER_ADMISSION_REASONS.newerUntrusted.reason, + packageName, + installedVersionCode: state.installedVersionCode, + versionCode, + }, + ); + } + const result = await installAndroidHelperPackage(apkPath, { provider: adbProvider, replace: true, @@ -142,7 +159,6 @@ export async function inspectInstalledAndroidHelper(options: { installedVersionCode, reason: ANDROID_HELPER_INSTALL_STATE_REASONS.outdated.reason, }; - if (installedVersionCode > versionCode) return { installedVersionCode, reason: 'current' }; try { const installedSha256 = await readInstalledAndroidPackageSha256( diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index a4a020de001..73b2f3ab9b0 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -1,5 +1,6 @@ import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/errors'; import { + ANDROID_HELPER_ADMISSION_REASONS, inspectInstalledAndroidHelper, installAndroidHelperPackage, verifyAndroidHelperApkChecksum, @@ -110,7 +111,9 @@ export async function ensureAndroidSnapshotHelper(options: { installCacheKey && installPolicy !== 'always' && !options.inspectInstalled && - cachedVersionCode !== undefined + cachedVersionCode !== undefined && + (await readInstalledVersionCode(adb, packageName, options.timeoutMs, options.signal)) === + versionCode ) { return { packageName, @@ -155,6 +158,22 @@ export async function ensureAndroidSnapshotHelper(options: { reason, }; } + if ( + installPolicy !== 'always' && + installedVersionCode !== undefined && + installedVersionCode > versionCode + ) { + throw new AppError( + 'COMMAND_FAILED', + 'Installed Android helper is newer than the trusted artifact.', + { + reason: ANDROID_HELPER_ADMISSION_REASONS.newerUntrusted.reason, + packageName, + installedVersionCode, + versionCode, + }, + ); + } if (installPolicy === 'current-only') { throw new AppError( 'COMMAND_FAILED', diff --git a/packages/platform-android/src/snapshot-helper-session-protocol.ts b/packages/platform-android/src/snapshot-helper-session-protocol.ts index 076f516d3ee..ddd4ea2e6e2 100644 --- a/packages/platform-android/src/snapshot-helper-session-protocol.ts +++ b/packages/platform-android/src/snapshot-helper-session-protocol.ts @@ -43,6 +43,7 @@ export function allocateAndroidSnapshotHelperSessionPort(): Promise { // A 64 KiB `fill --text-stdin` value of JSON-escaped control characters encodes to 524,368 Base64 // bytes, and the action and request id follow; SessionPeerPolicy.java owns the full derivation. export const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_COMMAND_BYTES = 513 * 1024; +const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES = 16 * 1024 * 1024; /** * What this host launched one session with: the abstract socket the helper was told to bind, named @@ -73,6 +74,8 @@ const SNAPSHOT_HELPER_SESSION_REASONS = { requestTimeout: { reason: 'android_snapshot_helper_session_request_timeout' }, // The listener could not prove the session secret, so it is not the helper this session launched. peerUnverified: { reason: 'android_snapshot_helper_session_peer_unverified' }, + // The helper answer exceeded the authenticated session's response byte limit. + responseTooLarge: { reason: 'android_snapshot_helper_session_response_too_large' }, // The helper process never reported readiness before the readiness budget ran out. readyTimeout: { reason: 'android_snapshot_helper_session_ready_timeout' }, // The readiness record the helper sent does not prove this session's protocol, socket, or secret. @@ -135,6 +138,7 @@ export function sendAndroidSnapshotHelperSessionCommand( let phase: 'nonce-sent' | 'proven' | 'refused' = 'nonce-sent'; let hello = Buffer.alloc(0); const chunks: Buffer[] = []; + let responseBytes = 0; const timer = setTimeout(() => { cleanup(); socket.destroy(); @@ -186,7 +190,27 @@ export function sendAndroidSnapshotHelperSessionCommand( socket.on('connect', () => socket.write(`${clientNonce}\n`)); // Only the helper that printed the secret can answer the nonce; anything else is refused. socket.on('data', (chunk) => { - if (phase === 'proven') return void chunks.push(Buffer.from(chunk)); + if (phase === 'proven') { + responseBytes += chunk.byteLength; + if (responseBytes > ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES) { + phase = 'refused'; + cleanup(); + socket.destroy(); + reject( + new AppError( + 'COMMAND_FAILED', + 'Android snapshot helper response exceeds the size limit', + { + reason: SNAPSHOT_HELPER_SESSION_REASONS.responseTooLarge.reason, + limitBytes: ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES, + }, + ), + ); + return; + } + chunks.push(Buffer.from(chunk)); + return; + } if (phase === 'refused') return; // Keep at most the one hello line, `<64 hex nonce> <64 hex proof>\n`. An honest helper sends // nothing more before the client proof, so any byte past that window, or a line of any other diff --git a/src/__tests__/android-snapshot-occlusion-context.test.ts b/src/__tests__/android-snapshot-occlusion-context.test.ts index 29525e0a8aa..4cd5f5a3ce7 100644 --- a/src/__tests__/android-snapshot-occlusion-context.test.ts +++ b/src/__tests__/android-snapshot-occlusion-context.test.ts @@ -14,6 +14,7 @@ import { coveredAndroidReplacementNodeIndexes } from '@agent-device/capture-kit/ import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, androidSnapshotHelperOutput, + trustedInstalledSnapshotHelperResult, } from './test-utils/android-snapshot-helper.ts'; import '../platform-runtime-android-adb-host.ts'; @@ -68,13 +69,8 @@ test('scoped Android captures retain broad off-wire context for daemon occlusion function oneShotHelper(xml: string): AndroidAdbExecutor { return async (args) => { - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', - stderr: '', - }; - } + const installedHelper = trustedInstalledSnapshotHelperResult(args); + if (installedHelper) return installedHelper; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } diff --git a/src/__tests__/test-utils/android-snapshot-helper.ts b/src/__tests__/test-utils/android-snapshot-helper.ts index 55d38858977..6c390c1408f 100644 --- a/src/__tests__/test-utils/android-snapshot-helper.ts +++ b/src/__tests__/test-utils/android-snapshot-helper.ts @@ -1,4 +1,5 @@ import type { AndroidSnapshotHelperArtifact } from '@agent-device/platform-android/mechanics'; +import fs from 'node:fs'; import { fileURLToPath } from 'node:url'; const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; @@ -25,6 +26,37 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti }, }; +export function trustedInstalledSnapshotHelperResult( + args: readonly string[], +): { exitCode: number; stdout: string; stderr: string } | undefined { + if ( + args.join(' ') === + `shell cmd package list packages --show-versioncode ${SNAPSHOT_HELPER_PACKAGE}` + ) { + return { + exitCode: 0, + stdout: `package:${SNAPSHOT_HELPER_PACKAGE} versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, + stderr: '', + }; + } + if (args.join(' ') === `shell pm path ${SNAPSHOT_HELPER_PACKAGE}`) { + return { + exitCode: 0, + stdout: `package:/data/app/${SNAPSHOT_HELPER_PACKAGE}/base.apk\n`, + stderr: '', + }; + } + if ( + args[0] === 'pull' && + args[1] === `/data/app/${SNAPSHOT_HELPER_PACKAGE}/base.apk` && + args[2] + ) { + fs.copyFileSync(SNAPSHOT_HELPER_FIXTURE_APK_PATH, args[2]); + return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; + } + return undefined; +} + export function androidSnapshotHelperOutput( xml: string, options: { pixelDensity?: number } = {}, diff --git a/test/integration/provider-scenarios/android-find.test.ts b/test/integration/provider-scenarios/android-find.test.ts index 15228f7ff95..08aa5f78e91 100644 --- a/test/integration/provider-scenarios/android-find.test.ts +++ b/test/integration/provider-scenarios/android-find.test.ts @@ -21,17 +21,25 @@ import { createProviderScenarioHarness } from './harness.ts'; test('Provider-backed integration Android find flow covers refs, wait, ambiguity, and first/last selection', async () => { const adbCalls: string[][] = []; let includeDuplicateAppsRow = false; + let snapshotHelperInstalled = false; const ime = createAndroidProviderShellState(); const adbProvider: AndroidAdbProvider = { snapshotHelperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, imeHelperArtifact: ANDROID_IME_HELPER_FIXTURE_ARTIFACT, exec: async (args) => { adbCalls.push([...args]); + if (args[0] === 'install') snapshotHelperInstalled = true; updateAndroidProviderImeShellState([...args], ime); if (args[0] === 'shell' && args[1] === 'input' && args[2] === 'text') { ime.searchText = String(args[3] ?? '').replaceAll('%s', ' '); } - return androidFindAdbResult([...args], ime.searchText, includeDuplicateAppsRow, ime); + return androidFindAdbResult( + [...args], + ime.searchText, + includeDuplicateAppsRow, + ime, + snapshotHelperInstalled, + ); }, }; const daemon = await createProviderScenarioHarness({ @@ -227,7 +235,20 @@ function androidFindAdbResult( searchText: string, includeDuplicateAppsRow: boolean, ime: ReturnType, + snapshotHelperInstalled: boolean, ): { stdout: string; stderr: string; exitCode: number } { + if ( + args.join(' ') === + 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.snapshothelper' + ) { + return snapshotHelperInstalled + ? { + stdout: `package:com.callstack.agentdevice.snapshothelper versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, + stderr: '', + exitCode: 0, + } + : { stdout: '', stderr: '', exitCode: 1 }; + } const imeResult = androidImeLifecycleAdbResult(args.join(' '), args, ime); if (imeResult) return imeResult; const imeAck = androidImeBroadcastAckResult(args); diff --git a/test/integration/provider-scenarios/android-ime-lifecycle-world.ts b/test/integration/provider-scenarios/android-ime-lifecycle-world.ts index 9ef2cac415b..84798d8bb80 100644 --- a/test/integration/provider-scenarios/android-ime-lifecycle-world.ts +++ b/test/integration/provider-scenarios/android-ime-lifecycle-world.ts @@ -1,3 +1,6 @@ +import fs from 'node:fs'; +import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-ime-helper.ts'; + type AndroidImeAdbResult = { stdout: string; stderr: string; @@ -92,14 +95,19 @@ export function androidImeLifecycleAdbResult( if ( key === 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.imehelper' ) { - // A newer provider-installed helper takes the actual durable activation/recovery path without - // adding an unrelated helper-installation fixture to each scenario. return { - stdout: 'package:com.callstack.agentdevice.imehelper versionCode:999999\n', + stdout: `package:${IME_PACKAGE} versionCode:${ANDROID_IME_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, stderr: '', exitCode: 0, }; } + if (key === `shell pm path ${IME_PACKAGE}`) { + return { stdout: `package:/data/app/${IME_PACKAGE}/base.apk\n`, stderr: '', exitCode: 0 }; + } + if (args[0] === 'pull' && args[1] === `/data/app/${IME_PACKAGE}/base.apk` && args[2]) { + fs.copyFileSync(ANDROID_IME_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]); + return { stdout: '1 file pulled\n', stderr: '', exitCode: 0 }; + } if (!state) return undefined; if (argsStartWith(args, ['shell', 'settings', 'get', 'secure']) && args[4]) { return { diff --git a/test/integration/provider-scenarios/composite-deadline.test.ts b/test/integration/provider-scenarios/composite-deadline.test.ts index ef2487f230b..83250f0de5f 100644 --- a/test/integration/provider-scenarios/composite-deadline.test.ts +++ b/test/integration/provider-scenarios/composite-deadline.test.ts @@ -24,6 +24,27 @@ type DeadlineAdbState = { searchText: string; }; +function trustedSnapshotHelperResponse( + args: readonly string[], +): AndroidAdbExecutorResult | undefined { + const packageName = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName; + if (args.join(' ') === `shell cmd package list packages --show-versioncode ${packageName}`) { + return { + exitCode: 0, + stdout: `package:${packageName} versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, + stderr: '', + }; + } + if (args.join(' ') === `shell pm path ${packageName}`) { + return { exitCode: 0, stdout: `package:/data/app/${packageName}/base.apk\n`, stderr: '' }; + } + if (args[0] === 'pull' && args[1] === `/data/app/${packageName}/base.apk` && args[2]) { + fs.copyFileSync(ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]); + return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; + } + return undefined; +} + function awaitGestureAbort(signal: AbortSignal): Promise { return new Promise((_resolve, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }); @@ -44,12 +65,8 @@ function deadlineAdbInfrastructureResponse( if (state.signal?.aborted) state.retired = true; return { exitCode: 0, stdout: '', stderr: '' }; } - if (args.includes('--show-versioncode')) - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', - stderr: '', - }; + const helperResponse = trustedSnapshotHelperResponse(args); + if (helperResponse) return helperResponse; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') return { exitCode: 0, stdout: 'Starting: Intent', stderr: '' }; return undefined; @@ -287,12 +304,8 @@ test('annotated replay capture aborts within its deadline without post-failure f if (!captureSignal) throw new Error('annotated replay capture lost the request signal'); return await awaitGestureAbort(captureSignal); } - if (args.includes('--show-versioncode')) - return { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', - stderr: '', - }; + const helperResponse = trustedSnapshotHelperResponse(args); + if (helperResponse) return helperResponse; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') return { exitCode: 0, stdout: 'Starting: Intent', stderr: '' }; return respondToAndroidSettingsAdbCommand([...args], '', '', {}); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index de5c147e0e8..e356c24174b 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -486,6 +486,12 @@ These reasons can come from more than one command. | --- | --- | | `managed-device-transport-mismatch` | The call aimed a managed adb transport at another device, target, or server. | +### Android helper + +| Reason | Meaning | +| --- | --- | +| `android_helper_newer_untrusted` | The installed helper has a higher version than the bundled artifact and cannot be trusted. | + ### Android helper install | Reason | Meaning | @@ -509,6 +515,7 @@ These reasons can come from more than one command. | `android_snapshot_helper_runtime_occupied` | Another helper process still holds UiAutomation, so nothing can take the runtime. | | `android_snapshot_helper_session_request_timeout` | The helper accepted the session request but sent no answer before the command deadline. | | `android_snapshot_helper_session_peer_unverified` | The listener could not prove the session secret, so it is not the helper this session launched. | +| `android_snapshot_helper_session_response_too_large` | The helper answer exceeded the authenticated session's response byte limit. | | `android_snapshot_helper_session_ready_timeout` | The helper process never reported readiness before the readiness budget ran out. | | `android_snapshot_helper_session_ready_malformed` | The readiness record the helper sent does not prove this session's protocol, socket, or secret. | | `android_snapshot_helper_session_exited_before_ready` | The helper process ended before it reported readiness. | From 5b36515b4f4a880275bf1d802dd0692675c93a14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:11:39 +0100 Subject: [PATCH 02/26] fix(android): enforce helper resource boundaries --- .../snapshothelper/AccessibilityTreeXml.java | 55 ++++++++++++++----- .../AccessibilityTreeXmlTest.java | 15 +++++ .../snapshot-helper-session-protocol.test.ts | 21 +++++++ ...snapshot-helper-session-touch-peer.test.ts | 2 +- .../src/__tests__/snapshot-helper.test.ts | 36 ++++++------ .../src/snapshot-helper-install.ts | 27 ++++++--- .../src/snapshot-helper-session-protocol.ts | 5 +- 7 files changed, 118 insertions(+), 43 deletions(-) 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 0607f2c0b67..711226efb2f 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 @@ -171,12 +171,20 @@ private static void appendNonEmptyAttribute( appendAttribute(xml, name, value); } - private static void appendAppAttribute( + static void appendAppAttribute( StringBuilder xml, String name, CharSequence value, Stats stats) { if (value == null || value.length() == 0) return; - int length = Math.min(value.length(), MAX_APP_ATTRIBUTE_CHARS); - if (length < value.length()) stats.truncated = true; - appendAttribute(xml, name, value.subSequence(0, length)); + String prefix = " " + name + "=\""; + int escapedBudget = + Math.min(MAX_APP_ATTRIBUTE_CHARS, MAX_XML_CHARS - xml.length() - prefix.length() - 1); + if (escapedBudget <= 0) { + stats.truncated = true; + return; + } + xml.append(prefix); + int consumed = appendEscaped(xml, value, escapedBudget); + xml.append('"'); + if (consumed < value.length()) stats.truncated = true; } private static void appendNonNegativeAttribute(StringBuilder xml, String name, int value) { @@ -281,38 +289,57 @@ private static boolean hasAccessibilityAction( } private static void appendEscaped(StringBuilder xml, String value) { + appendEscaped(xml, value, Integer.MAX_VALUE); + } + + private static int appendEscaped(StringBuilder xml, CharSequence value, int maxChars) { + int appendedChars = 0; for (int index = 0; index < value.length(); index += 1) { char character = value.charAt(index); + String escaped; switch (character) { case '&': - xml.append("&"); + escaped = "&"; break; case '<': - xml.append("<"); + escaped = "<"; break; case '>': - xml.append(">"); + escaped = ">"; break; case '"': - xml.append("""); + escaped = """; break; case '\'': - xml.append("'"); + escaped = "'"; break; case '\n': - xml.append(" "); + escaped = " "; break; case '\r': - xml.append(" "); + escaped = " "; break; case '\t': - xml.append(" "); + escaped = " "; break; default: - xml.append(character); - break; + int sourceChars = + Character.isHighSurrogate(character) + && index + 1 < value.length() + && Character.isLowSurrogate(value.charAt(index + 1)) + ? 2 + : 1; + if (appendedChars + sourceChars > maxChars) return index; + xml.append(value, index, index + sourceChars); + appendedChars += sourceChars; + index += sourceChars - 1; + continue; } + if (appendedChars + escaped.length() > maxChars) return index; + xml.append(escaped); + appendedChars += escaped.length(); } + return value.length(); } static final class Stats { diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index 8aec97b2cf2..df5490f0691 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -10,6 +10,21 @@ static void run() { " window-bounds=\"[-2147483648,-1][0,2147483647]\""); assertLongClickable(true, " long-clickable=\"true\""); assertLongClickable(false, " long-clickable=\"false\""); + assertAppAttributeBoundsEscapedOutput(); + } + + private static void assertAppAttributeBoundsEscapedOutput() { + StringBuilder value = new StringBuilder(); + for (int index = 0; index < 64 * 1024; index += 1) value.append('&'); + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendAppAttribute(xml, "text", value, stats); + if (xml.length() > 64 * 1024 + " text=\"\"".length()) { + throw new AssertionError("Escaped app attribute exceeded its serialized limit"); + } + if (!stats.truncated || !xml.toString().endsWith("\"")) { + throw new AssertionError("Escaped app attribute must report truncation and stay well formed"); + } } private static void assertLongClickable(boolean longClickable, String expected) { diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts index ef9848a31ba..9864cf40723 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-protocol.test.ts @@ -31,6 +31,27 @@ test('a session launch owns one abstract socket name and the forward targets it' ); }); +test('the host response ceiling admits the helper XML character budget', () => { + const java = readFileSync( + new URL( + '../../../../android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXml.java', + import.meta.url, + ), + 'utf8', + ); + const cap = /MAX_XML_CHARS = (\d+) \* (\d+) \* (\d+);/.exec(java); + assert.ok(cap, 'expected an XML character cap in AccessibilityTreeXml'); + const protocol = readFileSync( + new URL('../snapshot-helper-session-protocol.ts', import.meta.url), + 'utf8', + ); + const responseCap = /MAX_RESPONSE_BYTES = (\d+) \* (\d+) \* (\d+);/.exec(protocol); + assert.ok(responseCap, 'expected a session response byte cap'); + const maxXmlChars = Number(cap[1]) * Number(cap[2]) * Number(cap[3]); + const maxResponseBytes = Number(responseCap[1]) * Number(responseCap[2]) * Number(responseCap[3]); + assert.ok(maxResponseBytes >= maxXmlChars * 4); +}); + test('the host socket namespace, session mode and byte cap agree with the Android helper', () => { const java = readFileSync( new URL( diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts index efb7e9d440d..e8c1dd674f4 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-touch-peer.test.ts @@ -82,7 +82,7 @@ async function listenOnce(onSocket: (socket: net.Socket) => void) { test('authenticated helper response stops at its byte ceiling', async () => { const listener = await listenOnce((socket) => { onSessionCommand(socket, () => { - socket.write(Buffer.alloc(16 * 1024 * 1024 + 1)); + socket.write(Buffer.alloc(32 * 1024 * 1024 + 1)); }); }); try { diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index 59a401db7d6..e3fb01ccb14 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -400,7 +400,7 @@ test('installing a same-version different-sha helper evicts the stale install me assert.deepEqual(installs, [apkPathB, apkPathA]); }); -test('ensureAndroidSnapshotHelper caches successful install checks per device and helper version', async () => { +test('ensureAndroidSnapshotHelper revalidates a cached same-version helper digest', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-cache-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -410,6 +410,7 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an }; const calls: (readonly string[])[] = []; let installedVersionCode: number | undefined; + let installedBytes = ''; const adb: AndroidAdbExecutor = async (args) => { calls.push(args); if (args.includes('--show-versioncode')) { @@ -421,7 +422,17 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an stderr: '', }; } - if (args[0] === 'install') installedVersionCode = localManifest.versionCode; + if (args.join(' ') === `shell pm path ${localManifest.packageName}`) { + return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; + } + if (args[0] === 'pull' && args[2]) { + await fs.writeFile(args[2], installedBytes); + return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; + } + if (args[0] === 'install') { + installedVersionCode = localManifest.versionCode; + installedBytes = 'helper-apk'; + } return { exitCode: 0, stdout: '', stderr: '' }; }; const artifact = { apkPath, manifest: localManifest }; @@ -431,7 +442,6 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an artifact, deviceKey: 'android:emulator-5554', }); - await fs.rm(apkPath); const cached = await ensureAndroidSnapshotHelper({ adb, artifact, @@ -444,25 +454,15 @@ test('ensureAndroidSnapshotHelper caches successful install checks per device an assert.equal(cached.installedVersionCode, localManifest.versionCode); assert.equal(calls.filter((args) => args[0] === 'install').length, 1); - await fs.writeFile(apkPath, 'helper-apk'); - await ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:device-2', - }); - assert.equal(calls.filter((args) => args[0] === 'install').length, 2); - - forgetAndroidSnapshotHelperInstall({ - deviceKey: 'android:emulator-5554', - packageName: localManifest.packageName, - versionCode: localManifest.versionCode, - }); - await ensureAndroidSnapshotHelper({ + installedBytes = 'same-version-replacement'; + const replaced = await ensureAndroidSnapshotHelper({ adb, artifact, deviceKey: 'android:emulator-5554', }); - assert.equal(calls.filter((args) => args[0] === 'install').length, 3); + assert.equal(replaced.reason, 'mismatched'); + assert.equal(replaced.installed, true); + assert.equal(calls.filter((args) => args[0] === 'install').length, 2); }); test('ensureAndroidSnapshotHelper always policy bypasses cached install result', async () => { diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 73b2f3ab9b0..99128778437 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -107,23 +107,31 @@ export async function ensureAndroidSnapshotHelper(options: { const cachedVersionCode = installCacheKey ? installedSnapshotHelpers.get(installCacheKey) : undefined; - if ( + const cachedInstalledState = installCacheKey && installPolicy !== 'always' && !options.inspectInstalled && - cachedVersionCode !== undefined && - (await readInstalledVersionCode(adb, packageName, options.timeoutMs, options.signal)) === - versionCode - ) { + cachedVersionCode !== undefined + ? await inspectInstalledAndroidHelper({ + adb, + adbProvider: normalizeAdbProvider(options.adbProvider, adb), + packageName, + versionCode, + sha256, + signal: options.signal, + }) + : undefined; + if (cachedInstalledState?.reason === 'current') { return { packageName, versionCode, - installedVersionCode: cachedVersionCode, - installedSha256: sha256, + installedVersionCode: cachedInstalledState.installedVersionCode, + installedSha256: cachedInstalledState.installedSha256, installed: false, reason: 'current', }; } + if (cachedInstalledState) forgetInstalledSnapshotHelper(installCacheKey); await verifyAndroidHelperApkChecksum(artifact.apkPath, sha256, 'Android snapshot helper'); const installedState = installPolicy === 'always' @@ -137,14 +145,15 @@ export async function ensureAndroidSnapshotHelper(options: { reason: 'forced' as const, installedSha256: undefined, } - : await inspectInstalledAndroidHelper({ + : (cachedInstalledState ?? + (await inspectInstalledAndroidHelper({ adb, adbProvider: normalizeAdbProvider(options.adbProvider, adb), packageName, versionCode, sha256, signal: options.signal, - }); + }))); const { installedVersionCode, installedSha256, reason } = installedState; if (reason === 'current') { diff --git a/packages/platform-android/src/snapshot-helper-session-protocol.ts b/packages/platform-android/src/snapshot-helper-session-protocol.ts index ddd4ea2e6e2..7a168d22799 100644 --- a/packages/platform-android/src/snapshot-helper-session-protocol.ts +++ b/packages/platform-android/src/snapshot-helper-session-protocol.ts @@ -43,7 +43,10 @@ export function allocateAndroidSnapshotHelperSessionPort(): Promise { // A 64 KiB `fill --text-stdin` value of JSON-escaped control characters encodes to 524,368 Base64 // bytes, and the action and request id follow; SessionPeerPolicy.java owns the full derivation. export const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_COMMAND_BYTES = 513 * 1024; -const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES = 16 * 1024 * 1024; +// AccessibilityTreeXml admits 8 MiB UTF-16 chars and limits an escaped app attribute to 64 KiB. +// UTF-8 needs at most three bytes per UTF-16 code unit, so 32 MiB admits every helper-legal tree +// plus its bounded final-node structural overshoot while still rejecting an unbounded peer. +const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES = 32 * 1024 * 1024; /** * What this host launched one session with: the abstract socket the helper was told to bind, named From cd5ec291176c7a9a0af14d1617ed15e60606462e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 15:26:04 +0100 Subject: [PATCH 03/26] fix(android): satisfy helper boundary gates --- .../src/__tests__/snapshot-helper.test.ts | 1 - .../src/snapshot-helper-install.ts | 56 ++++++++++++++----- .../android-fill-capture-evidence.test.ts | 14 +++-- 3 files changed, 51 insertions(+), 20 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index e3fb01ccb14..deb96b8906e 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -9,7 +9,6 @@ import { } from '../snapshot-helper-capture.ts'; import { ensureAndroidSnapshotHelper, - forgetAndroidSnapshotHelperInstall, resetAndroidSnapshotHelperInstallCache, } from '../snapshot-helper-install.ts'; import { AppError } from '@agent-device/kernel/errors'; diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 99128778437..3019baddd01 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -79,6 +79,36 @@ function forgetInstalledSnapshotHelper(cacheKey: string | undefined): void { } } +async function inspectCachedSnapshotHelper(options: { + installCacheKey: string | undefined; + cachedVersionCode: number | undefined; + installPolicy: AndroidSnapshotHelperInstallPolicy; + inspectInstalled: boolean | undefined; + adb: AndroidAdbExecutor; + adbProvider: AndroidAdbProvider | AndroidAdbExecutor | undefined; + packageName: string; + versionCode: number; + sha256: string; + signal: AbortSignal | undefined; +}): Promise> | undefined> { + if ( + !options.installCacheKey || + options.installPolicy === 'always' || + options.inspectInstalled || + options.cachedVersionCode === undefined + ) { + return undefined; + } + return await inspectInstalledAndroidHelper({ + adb: options.adb, + adbProvider: normalizeAdbProvider(options.adbProvider, options.adb), + packageName: options.packageName, + versionCode: options.versionCode, + sha256: options.sha256, + signal: options.signal, + }); +} + export async function ensureAndroidSnapshotHelper(options: { adb: AndroidAdbExecutor; adbProvider?: AndroidAdbProvider | AndroidAdbExecutor; @@ -107,20 +137,18 @@ export async function ensureAndroidSnapshotHelper(options: { const cachedVersionCode = installCacheKey ? installedSnapshotHelpers.get(installCacheKey) : undefined; - const cachedInstalledState = - installCacheKey && - installPolicy !== 'always' && - !options.inspectInstalled && - cachedVersionCode !== undefined - ? await inspectInstalledAndroidHelper({ - adb, - adbProvider: normalizeAdbProvider(options.adbProvider, adb), - packageName, - versionCode, - sha256, - signal: options.signal, - }) - : undefined; + const cachedInstalledState = await inspectCachedSnapshotHelper({ + installCacheKey, + cachedVersionCode, + installPolicy, + inspectInstalled: options.inspectInstalled, + adb, + adbProvider: options.adbProvider, + packageName, + versionCode, + sha256, + signal: options.signal, + }); if (cachedInstalledState?.reason === 'current') { return { packageName, diff --git a/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts b/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts index 0b34d51ac46..8cc55a6f315 100644 --- a/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts +++ b/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts @@ -9,7 +9,10 @@ import type { AndroidAdbProvider, } from '@agent-device/platform-android/mechanics'; import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-ime-helper.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import { androidImeLifecycleAdbResult, createAndroidProviderShellState, @@ -454,7 +457,11 @@ function createAdbProvider(device: Device): AndroidAdbProvider { if (key.startsWith('shell am instrument ')) device.events.push('capture:one-shot'); if (key.startsWith('shell input ')) device.events.push(key); updateAndroidProviderImeShellState(args, ime); - return androidImeLifecycleAdbResult(key, args, ime) ?? ok(adbStdout(key)); + return ( + trustedInstalledSnapshotHelperResult(args) ?? + androidImeLifecycleAdbResult(key, args, ime) ?? + ok(adbStdout(key)) + ); }, spawn: (args) => startHelperSession(device, args), }; @@ -465,9 +472,6 @@ function adbStdout(key: string): string { if (key.startsWith('shell dumpsys window')) { return `mCurrentFocus=Window{42 u0 ${APP}/.Settings}\n`; } - if (key.includes('--show-versioncode com.callstack.agentdevice.snapshothelper')) { - return `package:com.callstack.agentdevice.snapshothelper versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`; - } return ''; } From 54b618957e13885a42f5aa896e60fb1ef03469e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:13:05 +0100 Subject: [PATCH 04/26] test(android): expect cached helper revalidation --- .../platform-android/src/__tests__/settings-locale.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts index 0ff277d644f..ae31c1913e5 100644 --- a/packages/platform-android/src/__tests__/settings-locale.test.ts +++ b/packages/platform-android/src/__tests__/settings-locale.test.ts @@ -199,9 +199,10 @@ test('settings locale runs app_process from the base APK whose digest it verifie const firstCalls = calls.length; helper.pulls.length = 0; await setAndroidSetting(device, 'locale', 'de-DE'); - // The cached decision rechecks package presence before the base APK is hashed. + // The cached decision rechecks package presence and digest before the locale owner hashes the + // base APK it is about to execute. expect(calls.slice(firstCalls).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.pulls).toEqual([APK]); + expect(helper.pulls).toEqual([APK, APK]); expect(helper.launches).toEqual([APK, APK]); }); }); From 3070f6fa5043894e5e207982d44f6cf6fabdbe65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:21:48 +0100 Subject: [PATCH 05/26] test(android): expect cached helper repair --- .../src/__tests__/settings-locale.test.ts | 29 ++++++++----------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts index ae31c1913e5..be9f5e9ca28 100644 --- a/packages/platform-android/src/__tests__/settings-locale.test.ts +++ b/packages/platform-android/src/__tests__/settings-locale.test.ts @@ -223,7 +223,7 @@ test('settings locale refuses a newer installed helper before running its code', ); }); -test('a locale refusal keeps the snapshot install memo and makes the next locale call inspect the install', async () => { +test('a locale refusal keeps the snapshot install memo and makes the next helper use repair it', async () => { await withHelperDevice( async ({ calls, device, helper, artifact }) => { await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ @@ -244,8 +244,8 @@ test('a locale refusal keeps the snapshot install memo and makes the next locale artifact, deviceKey: `android:${device.id}`, }); - expect(install).toMatchObject({ reason: 'current', installed: false }); - expect(snapshotCalls.map((args) => args.join(' '))).toEqual([VERSION_QUERY]); + expect(install).toMatchObject({ reason: 'unverifiable', installed: true }); + expect(snapshotCalls.map((args) => args.join(' '))).toContain(VERSION_QUERY); const firstCall = calls.length; await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ @@ -258,7 +258,7 @@ test('a locale refusal keeps the snapshot install memo and makes the next locale ); }); -test('a locale call that saw no refusal keeps a refusal recorded while it prepared the helper', async () => { +test('a concurrent locale call repairs a replaced helper while another call prepares it', async () => { let pmPathFails = false; await withHelperDevice( async ({ calls, device, helper }) => { @@ -280,9 +280,9 @@ test('a locale call that saw no refusal keeps a refusal recorded while it prepar const callA = setAndroidSetting(device, 'locale', 'de-DE'); await preparing; - // Call B refuses the APK and records a recheck. - await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({ - details: { reason: 'locale-helper-apk-unverified' }, + // Call B revalidates the cached install and repairs the replaced APK before dispatch. + await expect(setAndroidSetting(device, 'locale', 'de-DE')).resolves.toMatchObject({ + locale: 'de-DE', }); // Call A resumes and fails on the transport, so it answers no refusal. @@ -307,29 +307,24 @@ test('a locale call that saw no refusal keeps a refusal recorded while it prepar ); }); -test('settings locale refuses a helper package replaced after a cached install decision, then rechecks it', async () => { +test('settings locale repairs a helper package replaced after a cached install decision', async () => { await withHelperDevice(async ({ calls, device, helper }) => { await setAndroidSetting(device, 'locale', 'en-IN'); let firstCall = calls.length; helper.apkPath = `/data/app/~~c3==/${PACKAGE}-d4==/base.apk`; helper.files.set(helper.apkPath, 'another-apk'); - await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - details: { - reason: 'locale-helper-apk-unverified', - dispatched: 'no', - apkPath: helper.apkPath, - }, + await expect(setAndroidSetting(device, 'locale', 'de-DE')).resolves.toMatchObject({ + locale: 'de-DE', }); expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.launches).toHaveLength(1); + expect(helper.launches).toHaveLength(2); // The genuine helper is back; the next locale command inspects the package again. helper.files.set(helper.apkPath, HELPER_BYTES); firstCall = calls.length; await setAndroidSetting(device, 'locale', 'de-DE'); expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.launches).toHaveLength(2); + expect(helper.launches).toHaveLength(3); }); }); From 2e43d99a959091b01d845266639e22de276f3433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:28:48 +0100 Subject: [PATCH 06/26] test(android): inject fill verification poll budget --- .../src/__tests__/fill-verification.test.ts | 37 +++++++++---------- .../text-input-fill-helper-lifecycle.test.ts | 1 + .../platform-android/src/fill-verification.ts | 24 +++++++++++- 3 files changed, 41 insertions(+), 21 deletions(-) diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index 81201caefd9..fceb169c86b 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -20,6 +20,7 @@ import { isAndroidFillCommitDropped, readAndroidFillTargetBeforeMutation, verifyAndroidFilledText, + verifyAndroidFilledTextWithDeadline, } from '../fill-verification.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; import { @@ -36,6 +37,11 @@ const device: DeviceInfo = { booted: true, }; +function sampleBudget(samples: number): { remainingMs(): number } { + let remaining = samples; + return { remainingMs: () => (remaining-- > 0 ? 150 : 0) }; +} + beforeEach(async () => { await resetAndroidSnapshotHelperSessions(); }); @@ -108,7 +114,7 @@ test('a value the app renders late still verifies, as long as it lands before th await withFillHelperProvider( session.provider, async () => - await verifyAndroidFilledText(device, 10, 10, 'chips', { + await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { helperSessionScope: 'daemon-session', }), ), @@ -122,28 +128,21 @@ test('a value that never lands is a mismatch read from the last sample', async ( const session = createFillHelperSession({ textForCapture: (captureIndex) => `Key echo ${captureIndex}`, }); - let elapsedMs = 0; - - const verification = await underFakeTimers(async () => { - const startedAt = Date.now(); - const result = await withFillHelperProvider( - session.provider, - async () => - await verifyAndroidFilledText(device, 10, 10, 'chips', { - helperSessionScope: 'daemon-session', - }), - ); - elapsedMs = Date.now() - startedAt; - return result; - }); + const verification = await underFakeTimers( + async () => + await withFillHelperProvider( + session.provider, + async () => + await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { + helperSessionScope: 'daemon-session', + }), + ), + ); assert.equal(verification.ok, false); assert.equal(verification.reason, 'text_mismatch'); assert.equal(verification.actual, `Key echo ${session.captureCount()}`); - assert.ok( - elapsedMs >= 1_500 && elapsedMs < 1_650, - `sampled until the deadline, took ${elapsedMs} ms`, - ); + assert.equal(session.captureCount(), 11, 'initial sample plus the ten-sample poll budget'); }); test('the pre-action target read shares the daemon-session helper with the samples', async () => { diff --git a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts index 3423419ad25..b7722154432 100644 --- a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts @@ -94,6 +94,7 @@ function createFillWorld( ) { return await persistent.exec(args, execOptions); } + if (args[0] === 'install') return { exitCode: 0, stdout: 'Success\n', stderr: '' }; if (args[0] === 'shell' && args[1] !== 'am') return { exitCode: 0, stdout: '', stderr: '' }; return await persistent.exec(args, execOptions); }, diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 30b801317c1..982d5927ed3 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -1,7 +1,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, discloseDispatch } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry'; +import { Deadline, pollUntilSettled, type DeadlineClock } from '@agent-device/host-kit/retry'; import { containsPoint } from '@agent-device/kernel/rect'; import type { Rect } from '@agent-device/kernel/snapshot'; import { @@ -96,7 +96,27 @@ export async function verifyAndroidFilledText( helper: AndroidHelperSessionOptions = {}, beforeCapture?: AndroidFillTargetCapture | null, ): Promise { - const deadline = Deadline.fromTimeoutMs(FILL_VERIFICATION_DEADLINE_MS); + return await verifyAndroidFilledTextWithDeadline( + device, + x, + y, + expected, + Deadline.fromTimeoutMs(FILL_VERIFICATION_DEADLINE_MS), + helper, + beforeCapture, + ); +} + +/** @internal Runs fill verification against the caller's poll budget. */ +export async function verifyAndroidFilledTextWithDeadline( + device: DeviceInfo, + x: number, + y: number, + expected: string, + deadline: DeadlineClock, + helper: AndroidHelperSessionOptions = {}, + beforeCapture?: AndroidFillTargetCapture | null, +): Promise { const capture = await captureAndroidUiHierarchy(device, { ...helper, idleWait: 'none' }); let initialObservation: AndroidFillObservation | undefined = parseAndroidFillObservation( capture.xml, From 6bc4fcf0a07464c99bd160280c0e90e6271215db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:41:09 +0100 Subject: [PATCH 07/26] test(android): complete fill deadline clock --- .../src/__tests__/fill-verification.test.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index fceb169c86b..3e618cac5d5 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -37,9 +37,18 @@ const device: DeviceInfo = { booted: true, }; -function sampleBudget(samples: number): { remainingMs(): number } { +function sampleBudget(samples: number): { + remainingMs(): number; + elapsedMs(): number; + isExpired(): boolean; +} { let remaining = samples; - return { remainingMs: () => (remaining-- > 0 ? 150 : 0) }; + const remainingMs = () => (remaining-- > 0 ? 150 : 0); + return { + remainingMs, + elapsedMs: () => (samples - Math.max(remaining, 0)) * 150, + isExpired: () => remaining <= 0, + }; } beforeEach(async () => { From f3bacc0d81cef172a14d669365442c3290beffda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 16:53:21 +0100 Subject: [PATCH 08/26] test(android): preserve helper inspection in fill fixture --- .../src/__tests__/text-input-fill.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/platform-android/src/__tests__/text-input-fill.test.ts b/packages/platform-android/src/__tests__/text-input-fill.test.ts index 642cd69c2e3..86fe9919b6b 100644 --- a/packages/platform-android/src/__tests__/text-input-fill.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill.test.ts @@ -711,7 +711,13 @@ test('fillAndroid confirms a moved clear through one warm helper', async () => { exec: async (args, options) => { if (isDeleteKey(args)) typed = ''; if (isTextInput(args)) typed = args[3] ?? ''; - if (args.includes('--show-versioncode')) return provider.exec(args, options); + if ( + args.includes('--show-versioncode') || + (args[0] === 'shell' && args[1] === 'pm' && args[2] === 'path') || + args[0] === 'pull' + ) { + return provider.exec(args, options); + } if (args[0] === 'shell' && args[1] !== 'am') return adbResult(''); return await provider.exec(args, options); }, From a378cf344c1852261968ab3cd4170688b2a03b3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 17:42:09 +0100 Subject: [PATCH 09/26] fix(android): revalidate cached helper APK bytes --- .../src/__tests__/ime-helper.test.ts | 60 +++++++++++++++++++ .../src/helper-package-install.ts | 40 ++++++------- 2 files changed, 80 insertions(+), 20 deletions(-) diff --git a/packages/platform-android/src/__tests__/ime-helper.test.ts b/packages/platform-android/src/__tests__/ime-helper.test.ts index 507502127f8..ae3bd1b4860 100644 --- a/packages/platform-android/src/__tests__/ime-helper.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper.test.ts @@ -232,6 +232,13 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer } : { exitCode: 0, stdout: '', stderr: '' }; } + if (args.join(' ') === `shell pm path ${manifest.packageName}`) { + return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; + } + if (args[0] === 'pull' && args[2]) { + await fs.writeFile(args[2], 'helper-apk'); + return { exitCode: 0, stdout: '', stderr: '' }; + } if (isImeListCall(args)) { return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; } @@ -264,6 +271,59 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer assert.equal(installs, 2); }); +test('ensureAndroidImeHelper reinstalls a cached same-version replacement', async () => { + const tmpDir = await mkdtempForTest('ime-helper-replaced-'); + const apkPath = path.join(tmpDir, 'helper.apk'); + await fs.writeFile(apkPath, 'helper-apk'); + let installedBytes = ''; + let installs = 0; + const adb: AndroidAdbExecutor = async (args) => { + if (args.includes('--show-versioncode')) { + return installedBytes + ? { + exitCode: 0, + stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode}`, + stderr: '', + } + : { exitCode: 0, stdout: '', stderr: '' }; + } + if (args.join(' ') === `shell pm path ${manifest.packageName}`) { + return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; + } + if (args[0] === 'pull' && args[2]) { + await fs.writeFile(args[2], installedBytes); + return { exitCode: 0, stdout: '', stderr: '' }; + } + if (isImeListCall(args)) { + return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; + } + throw new Error(`unexpected adb call: ${args.join(' ')}`); + }; + const adbProvider: AndroidAdbProvider = { + exec: adb, + install: async () => { + installs += 1; + installedBytes = 'helper-apk'; + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }; + const ensure = () => + ensureAndroidImeHelper({ + adb, + adbProvider, + artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, + deviceKey: 'android:emulator-5554', + }); + + assert.equal((await ensure()).installed, true); + assert.equal((await ensure()).installed, false); + installedBytes = 'same-version-replacement'; + const repaired = await ensure(); + assert.equal(repaired.reason, 'mismatched'); + assert.equal(repaired.installed, true); + assert.equal(installs, 2); +}); + test('ensureAndroidImeHelper install timeout points at the OEM install dialog', async () => { const tmpDir = await mkdtempForTest('ime-helper-install-timeout-'); const apkPath = path.join(tmpDir, 'helper.apk'); diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts index 097af372cee..0f32610df3d 100644 --- a/packages/platform-android/src/helper-package-install.ts +++ b/packages/platform-android/src/helper-package-install.ts @@ -70,28 +70,28 @@ async function ensureAndroidHelperPackageInstalled(options: { helperLabel, } = options; const cacheKey = `${deviceKey}\0${packageName}\0${versionCode}\0${sha256}`; - if (cache.has(cacheKey)) { - // The cache skips the checksums, never the presence check: an emulator that is wiped or - // restored from a snapshot keeps its serial but may no longer have the helper. - const installedVersionCode = await readInstalledAndroidPackageVersionCode(adb, packageName); - if (installedVersionCode === versionCode) { - return { - packageName, - versionCode, - installedSha256: sha256, - installed: false, - reason: 'current', - }; - } + const cachedState = cache.has(cacheKey) + ? await inspectInstalledAndroidHelper({ adb, adbProvider, packageName, versionCode, sha256 }) + : undefined; + if (cachedState?.reason === 'current') { + return { + packageName, + versionCode, + ...cachedState, + installed: false, + reason: 'current', + }; } await verifyAndroidHelperApkChecksum(apkPath, sha256, helperLabel); - const state = await inspectInstalledAndroidHelper({ - adb, - adbProvider, - packageName, - versionCode, - sha256, - }); + const state = + cachedState ?? + (await inspectInstalledAndroidHelper({ + adb, + adbProvider, + packageName, + versionCode, + sha256, + })); if (state.reason === 'current') { cache.add(cacheKey); From f8a7d17541b99e89eb5e2f3c00bc6c895ad7bc92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 18:02:27 +0100 Subject: [PATCH 10/26] fix(android): preserve complete captures and warm helper sessions --- .../snapshothelper/AccessibilityTreeXml.java | 10 +++++++++- .../snapshothelper/AccessibilityTreeXmlTest.java | 6 +++--- .../src/__tests__/snapshot-helper.test.ts | 16 +++++++++++++++- .../src/snapshot-helper-install.ts | 16 ++++++++++++++++ website/docs/docs/commands.md | 2 +- website/docs/docs/snapshots.md | 9 ++++++--- 6 files changed, 50 insertions(+), 9 deletions(-) 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 711226efb2f..056fbe73bb4 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 @@ -184,7 +184,15 @@ static void appendAppAttribute( xml.append(prefix); int consumed = appendEscaped(xml, value, escapedBudget); xml.append('"'); - if (consumed < value.length()) stats.truncated = true; + if (consumed < value.length()) { + String clippedMarker = " " + name + "-clipped=\"true\""; + if (escapedBudget < MAX_APP_ATTRIBUTE_CHARS + || xml.length() + clippedMarker.length() > MAX_XML_CHARS) { + stats.truncated = true; + } else { + xml.append(clippedMarker); + } + } } private static void appendNonNegativeAttribute(StringBuilder xml, String name, int value) { diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index df5490f0691..19b0fb99609 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -19,11 +19,11 @@ private static void assertAppAttributeBoundsEscapedOutput() { StringBuilder xml = new StringBuilder(); AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); AccessibilityTreeXml.appendAppAttribute(xml, "text", value, stats); - if (xml.length() > 64 * 1024 + " text=\"\"".length()) { + if (xml.length() > 64 * 1024 + " text=\"\" text-clipped=\"true\"".length()) { throw new AssertionError("Escaped app attribute exceeded its serialized limit"); } - if (!stats.truncated || !xml.toString().endsWith("\"")) { - throw new AssertionError("Escaped app attribute must report truncation and stay well formed"); + if (stats.truncated || !xml.toString().endsWith(" text-clipped=\"true\"")) { + throw new AssertionError("Clipped value must stay distinct from missing nodes and stay well formed"); } } diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index deb96b8906e..ead5154bc56 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import { promises as fs } from 'node:fs'; import path from 'node:path'; -import { beforeEach, test } from 'vitest'; +import { beforeEach, test, vi } from 'vitest'; import { captureAndroidSnapshotWithHelper, parseAndroidSnapshotHelperOutput, @@ -20,6 +20,8 @@ import type { } from '../snapshot-helper-types.ts'; import type { AndroidAdbProvider } from '../adb-executor.ts'; import { resetAndroidSnapshotHelperRetirements } from '../snapshot-helper-retirement.ts'; +import * as sessionLifecycle from '../snapshot-helper-session-lifecycle.ts'; +import type { AndroidSnapshotHelperSession } from '../snapshot-helper-session-lifecycle.ts'; import { mkdtempForTest } from './test-utils/android-host-test-setup.ts'; const manifest: AndroidSnapshotHelperManifest = { @@ -441,6 +443,16 @@ test('ensureAndroidSnapshotHelper revalidates a cached same-version helper diges artifact, deviceKey: 'android:emulator-5554', }); + const liveSession = vi + .spyOn(sessionLifecycle, 'getLiveAndroidSnapshotHelperSession') + .mockResolvedValue({ + helper: { + packageName: localManifest.packageName, + helperVersionCode: localManifest.versionCode, + sha256: localManifest.sha256, + }, + } as AndroidSnapshotHelperSession); + const callsBeforeMemoHit = calls.length; const cached = await ensureAndroidSnapshotHelper({ adb, artifact, @@ -451,8 +463,10 @@ test('ensureAndroidSnapshotHelper revalidates a cached same-version helper diges assert.equal(cached.reason, 'current'); assert.equal(cached.installed, false); assert.equal(cached.installedVersionCode, localManifest.versionCode); + assert.equal(calls.length, callsBeforeMemoHit); assert.equal(calls.filter((args) => args[0] === 'install').length, 1); + liveSession.mockRestore(); installedBytes = 'same-version-replacement'; const replaced = await ensureAndroidSnapshotHelper({ adb, diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 3019baddd01..1beffe84511 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -16,6 +16,7 @@ import type { AndroidSnapshotHelperInstallPolicy, AndroidSnapshotHelperInstallResult, } from './snapshot-helper-types.ts'; +import { getLiveAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; const installedSnapshotHelpers = new Map(); @@ -81,6 +82,7 @@ function forgetInstalledSnapshotHelper(cacheKey: string | undefined): void { async function inspectCachedSnapshotHelper(options: { installCacheKey: string | undefined; + deviceKey: string | undefined; cachedVersionCode: number | undefined; installPolicy: AndroidSnapshotHelperInstallPolicy; inspectInstalled: boolean | undefined; @@ -93,12 +95,25 @@ async function inspectCachedSnapshotHelper(options: { }): Promise> | undefined> { if ( !options.installCacheKey || + !options.deviceKey || options.installPolicy === 'always' || options.inspectInstalled || options.cachedVersionCode === undefined ) { return undefined; } + const liveSession = await getLiveAndroidSnapshotHelperSession(options.deviceKey); + if ( + liveSession?.helper.packageName === options.packageName && + liveSession.helper.helperVersionCode === options.versionCode && + liveSession.helper.sha256 === options.sha256 + ) { + return { + reason: 'current', + installedVersionCode: options.cachedVersionCode, + installedSha256: options.sha256, + }; + } return await inspectInstalledAndroidHelper({ adb: options.adb, adbProvider: normalizeAdbProvider(options.adbProvider, options.adb), @@ -139,6 +154,7 @@ export async function ensureAndroidSnapshotHelper(options: { : undefined; const cachedInstalledState = await inspectCachedSnapshotHelper({ installCacheKey, + deviceKey: options.deviceKey, cachedVersionCode, installPolicy, inspectInstalled: options.inspectInstalled, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 552560b1298..ecf5676bcda 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -878,7 +878,7 @@ agent-device get attrs @e1 - `--raw` returns the full provider tree, including offscreen nodes and structural wrappers. See [iOS capture behavior](/docs/snapshots#ios-capture-behavior) and [Android capture behavior](/docs/snapshots#android-capture-behavior). - A source checkout must run `pnpm build:android` before Android verification, because Android snapshots install a bundled helper. -- `truncated: true` means the capture hit a backend node limit and the last elements are missing; see [Truncated captures](/docs/snapshots#truncated-captures). +- `truncated: true` means the capture hit a backend node limit or Android's total XML character budget, so later elements may be missing; see [Truncated captures](/docs/snapshots#truncated-captures). - For `viewport`, `--scope`, and `--actions`, see [Snapshots](/docs/snapshots). - `diff snapshot` compares with the previous snapshot in the session, then makes the new one the baseline. A snapshot read with different flags starts a new baseline instead of listing changes. diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index 677d51ac14a..053d4c2ba8b 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -203,9 +203,12 @@ agent-device snapshot -s @e12 ## Truncated captures -`truncated: true` means the Android snapshot helper or the iOS Simulator accessibility bridge hit its -5000-node limit, or the web provider hit its own bound. On Android the limit applies before any `-s` -scope. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with +`truncated: true` means the Android snapshot helper hit its 5000-node or total XML character +budget, the iOS Simulator accessibility bridge hit its 5000-node limit, or the web provider hit +its own bound. On Android the node limit applies before any `-s` scope. An Android node with a +value clipped at the 64 KiB escaped-attribute limit has a matching attribute such as +`text-clipped="true"` in raw XML; +that alone does not mean nodes are missing. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with `--raw`) the snapshot fails with a hint to scope it or take a screenshot instead. Every backend walks the tree in document order, so what gets cut is what comes last: footers, tab From 5ec69ce91dfb08052e05a28f15a51d07ba392f08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:31:08 +0100 Subject: [PATCH 11/26] fix(android): bound helper XML across windows and preserve fill text --- .../AccessibilityTreeCapture.java | 9 ++- .../snapshothelper/AccessibilityTreeXml.java | 68 +++++++++++++------ .../AccessibilityTreeXmlTest.java | 28 ++++++++ .../src/snapshot-helper-session-protocol.ts | 6 +- 4 files changed, 86 insertions(+), 25 deletions(-) diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java index e640ef1b99a..bec756f7810 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java @@ -62,10 +62,12 @@ private static Result captureOnce(UiAutomation automation, int maxDepth, int max ? null : stats.activeWindowMetadata.withIndex(windowCount); if (root != null + && AccessibilityTreeXml.remainingDocumentChars(xml) > 0 && AccessibilityCaptureStabilizer.canAppendActiveWindowFallback( windowCount, fallbackMetadata != null)) { AccessibilityTreeXml.appendNode( - xml, root, windowCount, 0, maxDepth, maxNodes, stats, fallbackMetadata); + xml, root, windowCount, 0, maxDepth, maxNodes, stats, fallbackMetadata, + xml.length() + AccessibilityTreeXml.remainingDocumentChars(xml)); windowCount += 1; stats.activeWindowRootMissing = false; } @@ -191,7 +193,7 @@ private static int appendInteractiveWindowRoots( } int windowCount = 0; for (int index = 0; index < windows.size(); index += 1) { - if (stats.nodeCount >= maxNodes) { + if (stats.nodeCount >= maxNodes || AccessibilityTreeXml.remainingDocumentChars(xml) <= 0) { stats.truncated = true; break; } @@ -222,7 +224,8 @@ private static int appendInteractiveWindowRoots( maxDepth, maxNodes, windowStats, - windowMetadata); + windowMetadata, + AccessibilityTreeXml.remainingDocumentChars(xml)); xml.append(windowXml); stats.copyFrom(windowStats); windowCount += 1; 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 056fbe73bb4..070236469b3 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 @@ -12,11 +12,16 @@ /** Serializes accessibility nodes using the helper's host-consumed XML contract. */ final class AccessibilityTreeXml { - private static final int MAX_XML_CHARS = 8 * 1024 * 1024; + static final int MAX_XML_CHARS = 8 * 1024 * 1024; private static final int MAX_APP_ATTRIBUTE_CHARS = 64 * 1024; + private static final int MAX_TEXT_ATTRIBUTE_CHARS = 6 * 64 * 1024; private AccessibilityTreeXml() {} + static int remainingDocumentChars(StringBuilder document) { + return MAX_XML_CHARS - document.length() - "".length(); + } + @SuppressWarnings("deprecation") static void appendNode( StringBuilder xml, @@ -26,8 +31,9 @@ static void appendNode( int maxDepth, int maxNodes, Stats stats, - WindowMetadata windowMetadata) { - if (stats.nodeCount >= maxNodes || xml.length() >= MAX_XML_CHARS) { + WindowMetadata windowMetadata, + int maxXmlChars) { + if (stats.nodeCount >= maxNodes || xml.length() >= maxXmlChars) { stats.truncated = true; return; } @@ -42,7 +48,7 @@ static void appendNode( } CharSequence text = node.getText(); if (text != null) { - appendAppAttribute(xml, "text", text, stats); + appendTextAttribute(xml, text, stats, maxXmlChars); } // 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 @@ -51,18 +57,24 @@ static void appendNode( appendAttribute(xml, "hint-showing", Boolean.toString(node.isShowingHintText())); // The hint itself, whether or not the field is showing it: `text` holds the hint only while // the field is empty, so a filled field's placeholder is readable nowhere else. - appendAppAttribute(xml, "hint", node.getHintText(), stats); + appendAppAttribute( + xml, "hint", node.getHintText(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); } appendAttribute(xml, "editable", Boolean.toString(node.isEditable())); // Accessibility selection offsets, not a measurement of the value's length. Read-only // selectable text exposes a selection too, so they do not depend on `editable`; -1 = unavailable. appendNonNegativeAttribute(xml, "selection-start", node.getTextSelectionStart()); appendNonNegativeAttribute(xml, "selection-end", node.getTextSelectionEnd()); - appendAppAttribute(xml, "resource-id", node.getViewIdResourceName(), stats); - appendAppAttribute(xml, "class", node.getClassName(), stats); - appendAppAttribute(xml, "package", node.getPackageName(), stats); - appendAppAttribute(xml, "content-desc", node.getContentDescription(), stats); - appendAppAttribute(xml, "role-description", roleDescription(node), stats); + appendAppAttribute( + xml, "resource-id", node.getViewIdResourceName(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "class", node.getClassName(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "package", node.getPackageName(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "content-desc", node.getContentDescription(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + appendAppAttribute( + xml, "role-description", roleDescription(node), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); appendTrueAttribute(xml, "heading", isHeading(node)); appendAttribute(xml, "visible-to-user", Boolean.toString(node.isVisibleToUser())); appendDrawingOrderAttribute(xml, node); @@ -98,7 +110,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); + appendScreenReaderFacts(xml, node, stats, maxXmlChars); int childCount = depth >= maxDepth ? 0 : node.getChildCount(); if (depth >= maxDepth && node.getChildCount() > 0) { @@ -111,7 +123,7 @@ static void appendNode( xml.append(">"); int index = 0; - while (index < childCount && stats.nodeCount < maxNodes && xml.length() < MAX_XML_CHARS) { + while (index < childCount && stats.nodeCount < maxNodes && xml.length() < maxXmlChars) { int count = Math.min( AccessibilityReadBatch.MAX_READS, Math.min(childCount - index, maxNodes - stats.nodeCount)); int offset = 0; @@ -119,10 +131,12 @@ static void appendNode( new AccessibilityReadBatch<>( index, count, childIndex -> AccessibilityNodeReads.child(node, childIndex), AccessibilityNodeInfo::recycle)) { - for (; offset < count && stats.nodeCount < maxNodes && xml.length() < MAX_XML_CHARS; offset += 1) { + for (; offset < count && stats.nodeCount < maxNodes && xml.length() < maxXmlChars; offset += 1) { AccessibilityNodeInfo child = children.get(offset); if (child != null) { - appendNode(xml, child, index + offset, depth + 1, maxDepth, maxNodes, stats, null); + appendNode( + xml, child, index + offset, depth + 1, maxDepth, maxNodes, stats, null, + maxXmlChars); } } } @@ -173,10 +187,24 @@ private static void appendNonEmptyAttribute( static void appendAppAttribute( StringBuilder xml, String name, CharSequence value, Stats stats) { + appendAppAttribute(xml, name, value, stats, MAX_XML_CHARS, MAX_APP_ATTRIBUTE_CHARS); + } + + static void appendTextAttribute( + StringBuilder xml, CharSequence value, Stats stats, int maxXmlChars) { + appendAppAttribute(xml, "text", value, stats, maxXmlChars, MAX_TEXT_ATTRIBUTE_CHARS); + } + + private static void appendAppAttribute( + StringBuilder xml, + String name, + CharSequence value, + Stats stats, + int maxXmlChars, int maxAttributeChars) { if (value == null || value.length() == 0) return; String prefix = " " + name + "=\""; int escapedBudget = - Math.min(MAX_APP_ATTRIBUTE_CHARS, MAX_XML_CHARS - xml.length() - prefix.length() - 1); + Math.min(maxAttributeChars, maxXmlChars - xml.length() - prefix.length() - 1); if (escapedBudget <= 0) { stats.truncated = true; return; @@ -186,8 +214,8 @@ static void appendAppAttribute( xml.append('"'); if (consumed < value.length()) { String clippedMarker = " " + name + "-clipped=\"true\""; - if (escapedBudget < MAX_APP_ATTRIBUTE_CHARS - || xml.length() + clippedMarker.length() > MAX_XML_CHARS) { + if (escapedBudget < maxAttributeChars + || xml.length() + clippedMarker.length() > maxXmlChars) { stats.truncated = true; } else { xml.append(clippedMarker); @@ -257,7 +285,7 @@ static void appendLongClickableAttribute(StringBuilder xml, boolean longClickabl // its focus rules read. `checked` above already marks a checkable node. @SuppressWarnings("deprecation") private static void appendScreenReaderFacts( - StringBuilder xml, AccessibilityNodeInfo node, Stats stats) { + StringBuilder xml, AccessibilityNodeInfo node, Stats stats, int maxXmlChars) { appendTraversalLink(xml, "traversal-before", node.getTraversalBefore(), stats); appendTraversalLink(xml, "traversal-after", node.getTraversalAfter(), stats); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { @@ -269,7 +297,9 @@ private static void appendScreenReaderFacts( appendTrueAttribute( xml, "focus-action", hasAccessibilityAction(node, AccessibilityAction.ACTION_FOCUS)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - appendAppAttribute(xml, "state-description", node.getStateDescription(), stats); + appendAppAttribute( + xml, "state-description", node.getStateDescription(), stats, maxXmlChars, + MAX_APP_ATTRIBUTE_CHARS); } appendTrueAttribute(xml, "collection", node.getCollectionInfo() != null); appendTrueAttribute(xml, "range", node.getRangeInfo() != null); diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index 19b0fb99609..d82f9996a66 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -11,6 +11,8 @@ static void run() { assertLongClickable(true, " long-clickable=\"true\""); assertLongClickable(false, " long-clickable=\"false\""); assertAppAttributeBoundsEscapedOutput(); + assertTextAttributeAdmitsMaximumFill(); + assertWindowBudgetUsesDocumentLength(); } private static void assertAppAttributeBoundsEscapedOutput() { @@ -27,6 +29,32 @@ private static void assertAppAttributeBoundsEscapedOutput() { } } + private static void assertTextAttributeAdmitsMaximumFill() { + StringBuilder value = new StringBuilder(); + for (int index = 0; index < 64 * 1024; index += 1) value.append('"'); + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute(xml, value, stats, AccessibilityTreeXml.MAX_XML_CHARS); + if (stats.truncated || xml.indexOf("text-clipped") >= 0 + || xml.length() != " text=\"\"".length() + 6 * 64 * 1024) { + throw new AssertionError("Maximum admitted fill text must remain complete after XML escaping"); + } + } + + private static void assertWindowBudgetUsesDocumentLength() { + StringBuilder document = new StringBuilder(""); + while (AccessibilityTreeXml.remainingDocumentChars(document) > 16) { + document.append('x'); + } + StringBuilder nextWindow = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute( + nextWindow, "&".repeat(64), stats, AccessibilityTreeXml.remainingDocumentChars(document)); + if (!stats.truncated || nextWindow.length() > 16) { + throw new AssertionError("A second window must use only the document's remaining characters"); + } + } + private static void assertLongClickable(boolean longClickable, String expected) { StringBuilder xml = new StringBuilder(); AccessibilityTreeXml.appendLongClickableAttribute(xml, longClickable); diff --git a/packages/platform-android/src/snapshot-helper-session-protocol.ts b/packages/platform-android/src/snapshot-helper-session-protocol.ts index 7a168d22799..dc2b575c74e 100644 --- a/packages/platform-android/src/snapshot-helper-session-protocol.ts +++ b/packages/platform-android/src/snapshot-helper-session-protocol.ts @@ -43,9 +43,9 @@ export function allocateAndroidSnapshotHelperSessionPort(): Promise { // A 64 KiB `fill --text-stdin` value of JSON-escaped control characters encodes to 524,368 Base64 // bytes, and the action and request id follow; SessionPeerPolicy.java owns the full derivation. export const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_COMMAND_BYTES = 513 * 1024; -// AccessibilityTreeXml admits 8 MiB UTF-16 chars and limits an escaped app attribute to 64 KiB. -// UTF-8 needs at most three bytes per UTF-16 code unit, so 32 MiB admits every helper-legal tree -// plus its bounded final-node structural overshoot while still rejecting an unbounded peer. +// AccessibilityTreeXml budgets the whole hierarchy at 8 MiB UTF-16 chars, including windows. +// UTF-8 needs at most three bytes per UTF-16 code unit, so 32 MiB admits the tree plus its +// bounded final-node structural overshoot while still rejecting an unbounded peer. const ANDROID_SNAPSHOT_HELPER_SESSION_MAX_RESPONSE_BYTES = 32 * 1024 * 1024; /** From accbe073e2dbf156de4871f21f67b77b4dbb70ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:53:45 +0100 Subject: [PATCH 12/26] fix(android): revalidate warm helper installs and flag clipped text --- .../snapshothelper/AccessibilityTreeXml.java | 16 +++++++++++----- .../snapshothelper/AccessibilityTreeXmlTest.java | 11 +++++++++++ .../src/__tests__/snapshot-helper.test.ts | 6 +++--- .../src/__tests__/text-input-fill.test.ts | 12 ++++++++++++ .../platform-android/src/fill-diagnostics.ts | 3 ++- .../platform-android/src/fill-verification.ts | 14 ++++++++++++++ .../src/snapshot-helper-install.ts | 16 ---------------- packages/platform-android/src/ui-hierarchy.ts | 3 +++ 8 files changed, 56 insertions(+), 25 deletions(-) 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 070236469b3..29a344da780 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 @@ -210,16 +210,22 @@ private static void appendAppAttribute( return; } xml.append(prefix); + int valueStart = xml.length(); int consumed = appendEscaped(xml, value, escapedBudget); + String clippedMarker = " " + name + "-clipped=\"true\""; + if (consumed < value.length() + && escapedBudget < maxAttributeChars + && escapedBudget >= clippedMarker.length()) { + xml.setLength(valueStart); + consumed = appendEscaped(xml, value, escapedBudget - clippedMarker.length()); + } xml.append('"'); if (consumed < value.length()) { - String clippedMarker = " " + name + "-clipped=\"true\""; - if (escapedBudget < maxAttributeChars - || xml.length() + clippedMarker.length() > maxXmlChars) { - stats.truncated = true; - } else { + boolean markerFits = xml.length() + clippedMarker.length() <= maxXmlChars; + if (markerFits) { xml.append(clippedMarker); } + if (escapedBudget < maxAttributeChars || !markerFits) stats.truncated = true; } } diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index d82f9996a66..f2b4b77b0d3 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -12,6 +12,7 @@ static void run() { assertLongClickable(false, " long-clickable=\"false\""); assertAppAttributeBoundsEscapedOutput(); assertTextAttributeAdmitsMaximumFill(); + assertDocumentLimitedTextMarksClip(); assertWindowBudgetUsesDocumentLength(); } @@ -55,6 +56,16 @@ private static void assertWindowBudgetUsesDocumentLength() { } } + private static void assertDocumentLimitedTextMarksClip() { + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute(xml, "x".repeat(70 * 1024), stats, 64 * 1024); + if (!stats.truncated || !xml.toString().endsWith(" text-clipped=\"true\"") + || xml.length() > 64 * 1024) { + throw new AssertionError("Document-limited text must report its clip within the document budget"); + } + } + private static void assertLongClickable(boolean longClickable, String expected) { StringBuilder xml = new StringBuilder(); AccessibilityTreeXml.appendLongClickableAttribute(xml, longClickable); diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index ead5154bc56..f99230bff83 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -401,7 +401,7 @@ test('installing a same-version different-sha helper evicts the stale install me assert.deepEqual(installs, [apkPathB, apkPathA]); }); -test('ensureAndroidSnapshotHelper revalidates a cached same-version helper digest', async () => { +test('ensureAndroidSnapshotHelper revalidates a cached digest while a session stays live', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-cache-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -463,16 +463,16 @@ test('ensureAndroidSnapshotHelper revalidates a cached same-version helper diges assert.equal(cached.reason, 'current'); assert.equal(cached.installed, false); assert.equal(cached.installedVersionCode, localManifest.versionCode); - assert.equal(calls.length, callsBeforeMemoHit); + assert.ok(calls.length > callsBeforeMemoHit); assert.equal(calls.filter((args) => args[0] === 'install').length, 1); - liveSession.mockRestore(); installedBytes = 'same-version-replacement'; const replaced = await ensureAndroidSnapshotHelper({ adb, artifact, deviceKey: 'android:emulator-5554', }); + liveSession.mockRestore(); assert.equal(replaced.reason, 'mismatched'); assert.equal(replaced.installed, true); assert.equal(calls.filter((args) => args[0] === 'install').length, 2); diff --git a/packages/platform-android/src/__tests__/text-input-fill.test.ts b/packages/platform-android/src/__tests__/text-input-fill.test.ts index 86fe9919b6b..162bb9ff9b6 100644 --- a/packages/platform-android/src/__tests__/text-input-fill.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill.test.ts @@ -540,6 +540,18 @@ test('verifyAndroidFilledTextInHierarchy rejects near-complete prefixes', () => assert.equal(verification.actual, 'filed the expens'); }); +test('verifyAndroidFilledTextInHierarchy does not verify clipped text prefixes', () => { + const xml = androidInputXml({ text: 'filed the expense' }).replace( + 'text="filed the expense"', + 'text="filed the expense" text-clipped="true"', + ); + const verification = verifyAndroidFilledTextInHierarchy(xml, 10, 10, 'filed the expense'); + + assert.equal(verification.ok, false); + assert.equal(verification.reason, 'text_clipped'); + assert.equal(verification.actualInput?.textClipped, true); +}); + test('verifyAndroidFilledTextInHierarchy does not treat inputmethod substring as IME ownership', () => { const verification = verifyAndroidFilledTextInHierarchy( appPackageWithInputMethodSubstringHierarchy(), diff --git a/packages/platform-android/src/fill-diagnostics.ts b/packages/platform-android/src/fill-diagnostics.ts index 7cc9b5bda1d..c6c190735b9 100644 --- a/packages/platform-android/src/fill-diagnostics.ts +++ b/packages/platform-android/src/fill-diagnostics.ts @@ -2,6 +2,7 @@ import type { Rect } from '@agent-device/kernel/snapshot'; export type AndroidFillVerificationNode = { text: string | null; + textClipped?: boolean; className: string | null; resourceId: string | null; packageName: string | null; @@ -19,7 +20,7 @@ export type AndroidFillVerificationNode = { placeholder: string | null; }; -export type FillFailureReason = 'ime_capture' | 'masked_unverified' | 'text_mismatch'; +export type FillFailureReason = 'ime_capture' | 'masked_unverified' | 'text_clipped' | 'text_mismatch'; export type AndroidFillVerification = { ok: boolean; diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 982d5927ed3..813f0398d6a 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -361,6 +361,16 @@ function verifyAndroidFilledTextInObservation( }; } + if (inspection.actualInput?.textClipped) { + return { + ok: false, + actual: inspection.actualInput.text, + reason: 'text_clipped', + targetInput: inspection.targetInput, + actualInput: inspection.actualInput, + }; + } + return ( maskedAndroidFillVerification(inspection, expected) ?? textAndroidFillVerification(inspection, expected) @@ -403,6 +413,9 @@ export function androidFillFailureMessage(verification: AndroidFillVerification if (verification?.reason === 'masked_unverified') { return 'Android fill verification could not confirm masked text value'; } + if (verification?.reason === 'text_clipped') { + return 'Android fill verification could not confirm clipped text value'; + } return 'Android fill verification failed'; } @@ -626,6 +639,7 @@ function androidFillCandidateFromNode( const area = Math.max(1, node.rect.width * node.rect.height); return { text: text || null, + textClipped: node.textClipped === true, className: node.className, resourceId: node.resourceId, packageName: node.packageName, diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 1beffe84511..3019baddd01 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -16,7 +16,6 @@ import type { AndroidSnapshotHelperInstallPolicy, AndroidSnapshotHelperInstallResult, } from './snapshot-helper-types.ts'; -import { getLiveAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; const installedSnapshotHelpers = new Map(); @@ -82,7 +81,6 @@ function forgetInstalledSnapshotHelper(cacheKey: string | undefined): void { async function inspectCachedSnapshotHelper(options: { installCacheKey: string | undefined; - deviceKey: string | undefined; cachedVersionCode: number | undefined; installPolicy: AndroidSnapshotHelperInstallPolicy; inspectInstalled: boolean | undefined; @@ -95,25 +93,12 @@ async function inspectCachedSnapshotHelper(options: { }): Promise> | undefined> { if ( !options.installCacheKey || - !options.deviceKey || options.installPolicy === 'always' || options.inspectInstalled || options.cachedVersionCode === undefined ) { return undefined; } - const liveSession = await getLiveAndroidSnapshotHelperSession(options.deviceKey); - if ( - liveSession?.helper.packageName === options.packageName && - liveSession.helper.helperVersionCode === options.versionCode && - liveSession.helper.sha256 === options.sha256 - ) { - return { - reason: 'current', - installedVersionCode: options.cachedVersionCode, - installedSha256: options.sha256, - }; - } return await inspectInstalledAndroidHelper({ adb: options.adb, adbProvider: normalizeAdbProvider(options.adbProvider, options.adb), @@ -154,7 +139,6 @@ export async function ensureAndroidSnapshotHelper(options: { : undefined; const cachedInstalledState = await inspectCachedSnapshotHelper({ installCacheKey, - deviceKey: options.deviceKey, cachedVersionCode, installPolicy, inspectInstalled: options.inspectInstalled, diff --git a/packages/platform-android/src/ui-hierarchy.ts b/packages/platform-android/src/ui-hierarchy.ts index 94e0642b32e..b1bcbdf477b 100644 --- a/packages/platform-android/src/ui-hierarchy.ts +++ b/packages/platform-android/src/ui-hierarchy.ts @@ -25,6 +25,8 @@ export type { /** Parsed node metadata plus status/navigation subtree provenance when present. */ export type AndroidUiNodeMetadata = { text: string | null; + /** Helper-only: the `text` attribute contains only a prefix of the observed value. */ + textClipped?: boolean; desc: string | null; resourceId: string | null; packageName: string | null; @@ -165,6 +167,7 @@ function readNodeAttributes(node: string): Omit { }; return { text: getAttr('text'), + ...optionalBoolAttr('textClipped', 'text-clipped'), desc: getAttr('content-desc'), resourceId: getAttr('resource-id'), packageName: getAttr('package'), From d26a18759316ea4299fa48efb0fdbdcb9163ff69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 19:57:42 +0100 Subject: [PATCH 13/26] chore(android): format fill failure reason type --- packages/platform-android/src/fill-diagnostics.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/platform-android/src/fill-diagnostics.ts b/packages/platform-android/src/fill-diagnostics.ts index c6c190735b9..8515f28421a 100644 --- a/packages/platform-android/src/fill-diagnostics.ts +++ b/packages/platform-android/src/fill-diagnostics.ts @@ -20,7 +20,11 @@ export type AndroidFillVerificationNode = { placeholder: string | null; }; -export type FillFailureReason = 'ime_capture' | 'masked_unverified' | 'text_clipped' | 'text_mismatch'; +export type FillFailureReason = + | 'ime_capture' + | 'masked_unverified' + | 'text_clipped' + | 'text_mismatch'; export type AndroidFillVerification = { ok: boolean; From 5f1b9df3b0ab5178e893ee8e2b957036eb826e02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:16:32 +0100 Subject: [PATCH 14/26] test(android): accept valid wait deadline outcome --- test/integration/provider-scenarios/android-find.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/integration/provider-scenarios/android-find.test.ts b/test/integration/provider-scenarios/android-find.test.ts index 08aa5f78e91..52b689f949b 100644 --- a/test/integration/provider-scenarios/android-find.test.ts +++ b/test/integration/provider-scenarios/android-find.test.ts @@ -141,7 +141,14 @@ test('Provider-backed integration Android find flow covers refs, wait, ambiguity // The field's label repeats its typed value (no editable fact: the EditText class decides), // so only its identifier satisfies `wait text`. const typedWait = await daemon.callCommand('wait', ['text', 'Network', '100'], selection); - assert.equal(typedWait.json?.error?.data?.details?.reason, WAIT_REASONS.targetAbsent.reason); + const typedWaitFailure = typedWait.json?.error?.data; + assert.equal(typedWaitFailure?.code, 'COMMAND_FAILED'); + const waitReason = typedWaitFailure?.details?.reason; + assert.ok( + waitReason === WAIT_REASONS.targetAbsent.reason || + waitReason === WAIT_REASONS.deadlineExceeded.reason, + `unexpected wait reason: ${String(waitReason)}`, + ); assert.equal( assertRpcOk(await daemon.callCommand('wait', ['text', 'id/search', '100'], selection)).text, 'id/search', From a950ea5a15e040a8fd3e273244a786345a078814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:50:37 +0100 Subject: [PATCH 15/26] fix: address Android helper review findings --- .../AccessibilityTreeCapture.java | 7 ++-- .../snapshothelper/AccessibilityTreeXml.java | 35 ++++++++++++------ .../AccessibilityTreeXmlTest.java | 17 +++++++-- .../src/__tests__/fill-diagnostics.test.ts | 15 ++++++++ .../src/__tests__/fill-verification.test.ts | 36 +++++++++++++------ .../snapshot-helper-session.fixtures.ts | 6 ---- .../snapshot-helper-start-retry.test.ts | 9 +++-- .../src/__tests__/snapshot-helper.test.ts | 16 ++------- .../text-input-fill-helper-lifecycle.test.ts | 1 - .../src/__tests__/text-input-fill.test.ts | 9 +++++ .../platform-android/src/fill-diagnostics.ts | 10 +++--- .../platform-android/src/fill-verification.ts | 1 + .../src/helper-package-install.ts | 28 +++++++++------ .../src/snapshot-helper-install.ts | 25 +++++-------- .../provider-scenarios/android-find.test.ts | 30 ++++------------ .../composite-deadline.test.ts | 30 ++++------------ website/docs/docs/snapshots.md | 2 +- 17 files changed, 148 insertions(+), 129 deletions(-) diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java index bec756f7810..b380b240515 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeCapture.java @@ -62,7 +62,8 @@ private static Result captureOnce(UiAutomation automation, int maxDepth, int max ? null : stats.activeWindowMetadata.withIndex(windowCount); if (root != null - && AccessibilityTreeXml.remainingDocumentChars(xml) > 0 + && AccessibilityTreeXml.remainingDocumentChars(xml) + > AccessibilityTreeXml.NODE_SUFFIX_RESERVE_CHARS && AccessibilityCaptureStabilizer.canAppendActiveWindowFallback( windowCount, fallbackMetadata != null)) { AccessibilityTreeXml.appendNode( @@ -193,7 +194,9 @@ private static int appendInteractiveWindowRoots( } int windowCount = 0; for (int index = 0; index < windows.size(); index += 1) { - if (stats.nodeCount >= maxNodes || AccessibilityTreeXml.remainingDocumentChars(xml) <= 0) { + if (stats.nodeCount >= maxNodes + || AccessibilityTreeXml.remainingDocumentChars(xml) + <= AccessibilityTreeXml.NODE_SUFFIX_RESERVE_CHARS) { stats.truncated = true; break; } 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 29a344da780..29b06ff9ca8 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 @@ -15,6 +15,7 @@ final class AccessibilityTreeXml { static final int MAX_XML_CHARS = 8 * 1024 * 1024; private static final int MAX_APP_ATTRIBUTE_CHARS = 64 * 1024; private static final int MAX_TEXT_ATTRIBUTE_CHARS = 6 * 64 * 1024; + static final int NODE_SUFFIX_RESERVE_CHARS = 8 * MAX_APP_ATTRIBUTE_CHARS + 4096; private AccessibilityTreeXml() {} @@ -33,7 +34,8 @@ static void appendNode( Stats stats, WindowMetadata windowMetadata, int maxXmlChars) { - if (stats.nodeCount >= maxNodes || xml.length() >= maxXmlChars) { + if (stats.nodeCount >= maxNodes + || xml.length() + NODE_SUFFIX_RESERVE_CHARS >= maxXmlChars) { stats.truncated = true; return; } @@ -48,7 +50,7 @@ static void appendNode( } CharSequence text = node.getText(); if (text != null) { - appendTextAttribute(xml, text, stats, maxXmlChars); + appendTextAttribute(xml, text, stats, maxXmlChars - NODE_SUFFIX_RESERVE_CHARS); } // 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 @@ -58,7 +60,8 @@ static void appendNode( // The hint itself, whether or not the field is showing it: `text` holds the hint only while // the field is empty, so a filled field's placeholder is readable nowhere else. appendAppAttribute( - xml, "hint", node.getHintText(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + xml, "hint", node.getHintText(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); } appendAttribute(xml, "editable", Boolean.toString(node.isEditable())); // Accessibility selection offsets, not a measurement of the value's length. Read-only @@ -66,15 +69,20 @@ static void appendNode( appendNonNegativeAttribute(xml, "selection-start", node.getTextSelectionStart()); appendNonNegativeAttribute(xml, "selection-end", node.getTextSelectionEnd()); appendAppAttribute( - xml, "resource-id", node.getViewIdResourceName(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + xml, "resource-id", node.getViewIdResourceName(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); appendAppAttribute( - xml, "class", node.getClassName(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + xml, "class", node.getClassName(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); appendAppAttribute( - xml, "package", node.getPackageName(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + xml, "package", node.getPackageName(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); appendAppAttribute( - xml, "content-desc", node.getContentDescription(), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + xml, "content-desc", node.getContentDescription(), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); appendAppAttribute( - xml, "role-description", roleDescription(node), stats, maxXmlChars, MAX_APP_ATTRIBUTE_CHARS); + xml, "role-description", roleDescription(node), stats, + maxXmlChars - NODE_SUFFIX_RESERVE_CHARS, MAX_APP_ATTRIBUTE_CHARS); appendTrueAttribute(xml, "heading", isHeading(node)); appendAttribute(xml, "visible-to-user", Boolean.toString(node.isVisibleToUser())); appendDrawingOrderAttribute(xml, node); @@ -110,7 +118,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, maxXmlChars); + appendScreenReaderFacts(xml, node, stats, maxXmlChars - NODE_SUFFIX_RESERVE_CHARS); int childCount = depth >= maxDepth ? 0 : node.getChildCount(); if (depth >= maxDepth && node.getChildCount() > 0) { @@ -123,7 +131,8 @@ static void appendNode( xml.append(">"); int index = 0; - while (index < childCount && stats.nodeCount < maxNodes && xml.length() < maxXmlChars) { + while (index < childCount && stats.nodeCount < maxNodes + && xml.length() + NODE_SUFFIX_RESERVE_CHARS < maxXmlChars) { int count = Math.min( AccessibilityReadBatch.MAX_READS, Math.min(childCount - index, maxNodes - stats.nodeCount)); int offset = 0; @@ -131,7 +140,8 @@ static void appendNode( new AccessibilityReadBatch<>( index, count, childIndex -> AccessibilityNodeReads.child(node, childIndex), AccessibilityNodeInfo::recycle)) { - for (; offset < count && stats.nodeCount < maxNodes && xml.length() < maxXmlChars; offset += 1) { + for (; offset < count && stats.nodeCount < maxNodes + && xml.length() + NODE_SUFFIX_RESERVE_CHARS < maxXmlChars; offset += 1) { AccessibilityNodeInfo child = children.get(offset); if (child != null) { appendNode( @@ -210,6 +220,7 @@ private static void appendAppAttribute( return; } xml.append(prefix); + int attributeStart = xml.length() - prefix.length(); int valueStart = xml.length(); int consumed = appendEscaped(xml, value, escapedBudget); String clippedMarker = " " + name + "-clipped=\"true\""; @@ -224,6 +235,8 @@ private static void appendAppAttribute( boolean markerFits = xml.length() + clippedMarker.length() <= maxXmlChars; if (markerFits) { xml.append(clippedMarker); + } else { + xml.setLength(attributeStart); } if (escapedBudget < maxAttributeChars || !markerFits) stats.truncated = true; } diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index f2b4b77b0d3..6b7e6df24d3 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -13,6 +13,7 @@ static void run() { assertAppAttributeBoundsEscapedOutput(); assertTextAttributeAdmitsMaximumFill(); assertDocumentLimitedTextMarksClip(); + assertUnmarkedPartialTextIsOmitted(); assertWindowBudgetUsesDocumentLength(); } @@ -44,8 +45,11 @@ private static void assertTextAttributeAdmitsMaximumFill() { private static void assertWindowBudgetUsesDocumentLength() { StringBuilder document = new StringBuilder(""); - while (AccessibilityTreeXml.remainingDocumentChars(document) > 16) { - document.append('x'); + int fillerChars = AccessibilityTreeXml.MAX_XML_CHARS + - document.length() - "".length() - 16; + document.append("x".repeat(fillerChars)); + if (AccessibilityTreeXml.remainingDocumentChars(document) != 16) { + throw new AssertionError("Document setup must leave 16 remaining chars"); } StringBuilder nextWindow = new StringBuilder(); AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); @@ -66,6 +70,15 @@ private static void assertDocumentLimitedTextMarksClip() { } } + private static void assertUnmarkedPartialTextIsOmitted() { + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendTextAttribute(xml, "abcdef", stats, 10); + if (!stats.truncated || xml.length() != 0) { + throw new AssertionError("Partial text without room for a clip marker must be omitted"); + } + } + private static void assertLongClickable(boolean longClickable, String expected) { StringBuilder xml = new StringBuilder(); AccessibilityTreeXml.appendLongClickableAttribute(xml, longClickable); diff --git a/packages/platform-android/src/__tests__/fill-diagnostics.test.ts b/packages/platform-android/src/__tests__/fill-diagnostics.test.ts index 5b95c7bab04..6c1c4858eb8 100644 --- a/packages/platform-android/src/__tests__/fill-diagnostics.test.ts +++ b/packages/platform-android/src/__tests__/fill-diagnostics.test.ts @@ -55,6 +55,21 @@ test('buildFillFailureDetails keeps non-masked text diagnostics visible', () => assert.equal(details.actualInput?.text, 'search'); }); +test('clipped fill evidence never includes the submitted or partial text', () => { + const details = buildFillFailureDetails('private-submission', { + ok: false, + actual: 'private-sub', + reason: 'text_clipped', + targetInput: node({ text: 'private-sub', focused: true }), + actualInput: node({ text: 'private-sub', focused: true }), + }); + assert.equal(details.failureReason, 'text_clipped'); + assert.equal(details.expectedLength, 'private-submission'.length); + assert.equal(details.targetInput?.text, null); + assert.equal(details.actualInput?.text, null); + assert.doesNotMatch(JSON.stringify(details), /private-sub/); +}); + test('buildFillFailureDetails infers sensitivity from password nodes', () => { const details = buildFillFailureDetails('Secret123', { ok: false, diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index 3e618cac5d5..325b4ec758a 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -13,6 +13,7 @@ import './test-utils/android-host-test-setup.ts'; import assert from 'node:assert/strict'; import { underFakeTimers } from './test-utils/fake-timers.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { DeadlineClock } from '@agent-device/host-kit/retry'; import { withAndroidAdbProvider, type AndroidAdbProvider } from '../adb-executor.ts'; import type { AndroidFillVerificationNode } from '../fill-diagnostics.ts'; import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; @@ -37,17 +38,13 @@ const device: DeviceInfo = { booted: true, }; -function sampleBudget(samples: number): { - remainingMs(): number; - elapsedMs(): number; - isExpired(): boolean; -} { - let remaining = samples; - const remainingMs = () => (remaining-- > 0 ? 150 : 0); +function sampleBudget(samples: number): DeadlineClock { + const startedAt = Date.now(); + const budgetMs = samples * 150; return { - remainingMs, - elapsedMs: () => (samples - Math.max(remaining, 0)) * 150, - isExpired: () => remaining <= 0, + remainingMs: () => Math.max(0, budgetMs - (Date.now() - startedAt)), + elapsedMs: () => Date.now() - startedAt, + isExpired: () => Date.now() - startedAt >= budgetMs, }; } @@ -151,7 +148,24 @@ test('a value that never lands is a mismatch read from the last sample', async ( assert.equal(verification.ok, false); assert.equal(verification.reason, 'text_mismatch'); assert.equal(verification.actual, `Key echo ${session.captureCount()}`); - assert.equal(session.captureCount(), 11, 'initial sample plus the ten-sample poll budget'); +}); + +test('default verification stops at its 1500 ms deadline', async () => { + const session = createFillHelperSession({ + textForCapture: (captureIndex) => `Key echo ${captureIndex}`, + }); + const elapsedMs = await underFakeTimers(async () => { + const startedAt = Date.now(); + await withFillHelperProvider( + session.provider, + async () => + await verifyAndroidFilledText(device, 10, 10, 'chips', { + helperSessionScope: 'daemon-session', + }), + ); + return Date.now() - startedAt; + }); + assert.ok(elapsedMs >= 1500 && elapsedMs < 1700, `deadline elapsed ${elapsedMs} ms`); }); test('the pre-action target read shares the daemon-session helper with the samples', async () => { diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts index 5ce3a25a9e9..e445965d748 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -27,12 +27,6 @@ import type { AndroidAdbExecutor } from '../snapshot-helper-types.ts'; import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts'; import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; -export const ANDROID_HELPER_INSTALLED_VERSION_PROBE = { - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13003', - stderr: '', -}; - export class FakeAndroidProcess extends EventEmitter implements AndroidAdbProcess { stdin = new PassThrough(); stdout = new PassThrough(); diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 497cd830397..748d74a790c 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -24,9 +24,11 @@ import { isRefusedInstrumentationStart } from '../instrumentation-helper.ts'; import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import { - ANDROID_HELPER_INSTALLED_VERSION_PROBE, + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; +import { createSessionProvider, androidHelperInstrumentationOutput, androidHelperRuntimeProbeResult, @@ -106,7 +108,8 @@ function freshlyBootedHelper( provider: { exec: async (args) => { calls.push(args); - if (args.includes('--show-versioncode')) return ANDROID_HELPER_INSTALLED_VERSION_PROBE; + const installed = trustedInstalledSnapshotHelperResult(args); + if (installed) return installed; if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); if (!isOneShotRun(args)) return { exitCode: 0, stdout: '', stderr: '' }; const run = runs.shift() ?? CAPTURED_RUN; diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index f99230bff83..4ce8ee9a0c3 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import { promises as fs } from 'node:fs'; import path from 'node:path'; -import { beforeEach, test, vi } from 'vitest'; +import { beforeEach, test } from 'vitest'; import { captureAndroidSnapshotWithHelper, parseAndroidSnapshotHelperOutput, @@ -20,8 +20,6 @@ import type { } from '../snapshot-helper-types.ts'; import type { AndroidAdbProvider } from '../adb-executor.ts'; import { resetAndroidSnapshotHelperRetirements } from '../snapshot-helper-retirement.ts'; -import * as sessionLifecycle from '../snapshot-helper-session-lifecycle.ts'; -import type { AndroidSnapshotHelperSession } from '../snapshot-helper-session-lifecycle.ts'; import { mkdtempForTest } from './test-utils/android-host-test-setup.ts'; const manifest: AndroidSnapshotHelperManifest = { @@ -401,7 +399,7 @@ test('installing a same-version different-sha helper evicts the stale install me assert.deepEqual(installs, [apkPathB, apkPathA]); }); -test('ensureAndroidSnapshotHelper revalidates a cached digest while a session stays live', async () => { +test('ensureAndroidSnapshotHelper revalidates a cached installed digest', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-cache-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -443,15 +441,6 @@ test('ensureAndroidSnapshotHelper revalidates a cached digest while a session st artifact, deviceKey: 'android:emulator-5554', }); - const liveSession = vi - .spyOn(sessionLifecycle, 'getLiveAndroidSnapshotHelperSession') - .mockResolvedValue({ - helper: { - packageName: localManifest.packageName, - helperVersionCode: localManifest.versionCode, - sha256: localManifest.sha256, - }, - } as AndroidSnapshotHelperSession); const callsBeforeMemoHit = calls.length; const cached = await ensureAndroidSnapshotHelper({ adb, @@ -472,7 +461,6 @@ test('ensureAndroidSnapshotHelper revalidates a cached digest while a session st artifact, deviceKey: 'android:emulator-5554', }); - liveSession.mockRestore(); assert.equal(replaced.reason, 'mismatched'); assert.equal(replaced.installed, true); assert.equal(calls.filter((args) => args[0] === 'install').length, 2); diff --git a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts index b7722154432..3423419ad25 100644 --- a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts @@ -94,7 +94,6 @@ function createFillWorld( ) { return await persistent.exec(args, execOptions); } - if (args[0] === 'install') return { exitCode: 0, stdout: 'Success\n', stderr: '' }; if (args[0] === 'shell' && args[1] !== 'am') return { exitCode: 0, stdout: '', stderr: '' }; return await persistent.exec(args, execOptions); }, diff --git a/packages/platform-android/src/__tests__/text-input-fill.test.ts b/packages/platform-android/src/__tests__/text-input-fill.test.ts index 162bb9ff9b6..c7eabea16ff 100644 --- a/packages/platform-android/src/__tests__/text-input-fill.test.ts +++ b/packages/platform-android/src/__tests__/text-input-fill.test.ts @@ -12,6 +12,7 @@ import { withAndroidAdbProvider, type AndroidAdbExecutor } from '../adb-executor import { androidFillFailureDetails, androidFillFailureMessage, + buildAndroidFillUnconfirmedVerification, readAndroidTextAtPointInHierarchy, verifyAndroidFilledTextInHierarchy, } from '../fill-verification.ts'; @@ -550,6 +551,14 @@ test('verifyAndroidFilledTextInHierarchy does not verify clipped text prefixes', assert.equal(verification.ok, false); assert.equal(verification.reason, 'text_clipped'); assert.equal(verification.actualInput?.textClipped, true); + assert.equal( + buildAndroidFillUnconfirmedVerification( + 'filed the expense', + verification.targetInput, + verification, + ), + null, + ); }); test('verifyAndroidFilledTextInHierarchy does not treat inputmethod substring as IME ownership', () => { diff --git a/packages/platform-android/src/fill-diagnostics.ts b/packages/platform-android/src/fill-diagnostics.ts index 8515f28421a..c8d0e636337 100644 --- a/packages/platform-android/src/fill-diagnostics.ts +++ b/packages/platform-android/src/fill-diagnostics.ts @@ -79,11 +79,12 @@ export function buildFillFailureDetails( }; } - const sensitive = isSensitiveFillVerification(verification); + const clipped = verification.reason === 'text_clipped'; + const sensitive = clipped || isSensitiveFillVerification(verification); const common = { failureReason: verification.reason ?? 'text_mismatch', - targetInput: toFillDiagnosticNode(verification.targetInput), - actualInput: toFillDiagnosticNode(verification.actualInput), + targetInput: toFillDiagnosticNode(verification.targetInput, clipped), + actualInput: toFillDiagnosticNode(verification.actualInput, clipped), }; if (sensitive) { return { @@ -114,9 +115,10 @@ function isMaskedFillText(text: string | null | undefined): boolean { function toFillDiagnosticNode( node: AndroidFillVerificationNode | null, + forceRedact = false, ): FillDiagnosticDetailsNode | null { if (!node) return null; - const textRedacted = isSensitiveFillDiagnosticNode(node); + const textRedacted = forceRedact || isSensitiveFillDiagnosticNode(node); return { ...node, text: textRedacted ? null : node.text, diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 813f0398d6a..2bb77f97bd7 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -292,6 +292,7 @@ export function buildAndroidFillUnconfirmedVerification( // and the soft-success would also skip the second, bigger delete burst. requested.length === 0 || verification.reason === 'ime_capture' || + verification.reason === 'text_clipped' || isAndroidFillCommitDropped(verification, beforeTarget) || !beforeTarget || !afterTarget || diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts index 0f32610df3d..58f9b02ce59 100644 --- a/packages/platform-android/src/helper-package-install.ts +++ b/packages/platform-android/src/helper-package-install.ts @@ -29,6 +29,23 @@ export const ANDROID_HELPER_ADMISSION_REASONS = { newerUntrusted: { reason: 'android_helper_newer_untrusted' }, } as const satisfies ReasonTable<'android helper'>; +export function newerUntrustedAndroidHelperError( + packageName: string, + installedVersionCode: number, + versionCode: number, +): AppError { + return new AppError( + 'COMMAND_FAILED', + 'Installed Android helper is newer than the trusted artifact.', + { + reason: ANDROID_HELPER_ADMISSION_REASONS.newerUntrusted.reason, + packageName, + installedVersionCode, + versionCode, + }, + ); +} + /** * The one install seam every Android helper APK crosses, so an install timeout carries the * install-specific hint wherever a helper is pushed on. Non-timeout failures pass through @@ -104,16 +121,7 @@ async function ensureAndroidHelperPackageInstalled(options: { } if (state.installedVersionCode !== undefined && state.installedVersionCode > versionCode) { - throw new AppError( - 'COMMAND_FAILED', - 'Installed Android helper is newer than the trusted artifact.', - { - reason: ANDROID_HELPER_ADMISSION_REASONS.newerUntrusted.reason, - packageName, - installedVersionCode: state.installedVersionCode, - versionCode, - }, - ); + throw newerUntrustedAndroidHelperError(packageName, state.installedVersionCode, versionCode); } const result = await installAndroidHelperPackage(apkPath, { diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 3019baddd01..544282f2253 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -1,8 +1,8 @@ import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/errors'; import { - ANDROID_HELPER_ADMISSION_REASONS, inspectInstalledAndroidHelper, installAndroidHelperPackage, + newerUntrustedAndroidHelperError, verifyAndroidHelperApkChecksum, } from './helper-package-install.ts'; import { @@ -195,22 +195,6 @@ export async function ensureAndroidSnapshotHelper(options: { reason, }; } - if ( - installPolicy !== 'always' && - installedVersionCode !== undefined && - installedVersionCode > versionCode - ) { - throw new AppError( - 'COMMAND_FAILED', - 'Installed Android helper is newer than the trusted artifact.', - { - reason: ANDROID_HELPER_ADMISSION_REASONS.newerUntrusted.reason, - packageName, - installedVersionCode, - versionCode, - }, - ); - } if (installPolicy === 'current-only') { throw new AppError( 'COMMAND_FAILED', @@ -223,6 +207,13 @@ export async function ensureAndroidSnapshotHelper(options: { }, ); } + if ( + installPolicy !== 'always' && + installedVersionCode !== undefined && + installedVersionCode > versionCode + ) { + throw newerUntrustedAndroidHelperError(packageName, installedVersionCode, versionCode); + } let result: Awaited>; try { diff --git a/test/integration/provider-scenarios/android-find.test.ts b/test/integration/provider-scenarios/android-find.test.ts index 52b689f949b..a2a19ecb35c 100644 --- a/test/integration/provider-scenarios/android-find.test.ts +++ b/test/integration/provider-scenarios/android-find.test.ts @@ -1,7 +1,10 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-ime-helper.ts'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import type { AndroidAdbProvider } from '@agent-device/platform-android/mechanics'; import { WAIT_REASONS } from '@agent-device/contracts/wait'; import { FIND_NO_MATCH_HINT } from '@agent-device/selectors'; @@ -21,25 +24,19 @@ import { createProviderScenarioHarness } from './harness.ts'; test('Provider-backed integration Android find flow covers refs, wait, ambiguity, and first/last selection', async () => { const adbCalls: string[][] = []; let includeDuplicateAppsRow = false; - let snapshotHelperInstalled = false; const ime = createAndroidProviderShellState(); const adbProvider: AndroidAdbProvider = { snapshotHelperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, imeHelperArtifact: ANDROID_IME_HELPER_FIXTURE_ARTIFACT, exec: async (args) => { adbCalls.push([...args]); - if (args[0] === 'install') snapshotHelperInstalled = true; + const trustedSnapshotHelper = trustedInstalledSnapshotHelperResult(args); + if (trustedSnapshotHelper) return trustedSnapshotHelper; updateAndroidProviderImeShellState([...args], ime); if (args[0] === 'shell' && args[1] === 'input' && args[2] === 'text') { ime.searchText = String(args[3] ?? '').replaceAll('%s', ' '); } - return androidFindAdbResult( - [...args], - ime.searchText, - includeDuplicateAppsRow, - ime, - snapshotHelperInstalled, - ); + return androidFindAdbResult([...args], ime.searchText, includeDuplicateAppsRow, ime); }, }; const daemon = await createProviderScenarioHarness({ @@ -242,20 +239,7 @@ function androidFindAdbResult( searchText: string, includeDuplicateAppsRow: boolean, ime: ReturnType, - snapshotHelperInstalled: boolean, ): { stdout: string; stderr: string; exitCode: number } { - if ( - args.join(' ') === - 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.snapshothelper' - ) { - return snapshotHelperInstalled - ? { - stdout: `package:com.callstack.agentdevice.snapshothelper versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, - stderr: '', - exitCode: 0, - } - : { stdout: '', stderr: '', exitCode: 1 }; - } const imeResult = androidImeLifecycleAdbResult(args.join(' '), args, ime); if (imeResult) return imeResult; const imeAck = androidImeBroadcastAckResult(args); diff --git a/test/integration/provider-scenarios/composite-deadline.test.ts b/test/integration/provider-scenarios/composite-deadline.test.ts index 83250f0de5f..302958d906d 100644 --- a/test/integration/provider-scenarios/composite-deadline.test.ts +++ b/test/integration/provider-scenarios/composite-deadline.test.ts @@ -7,7 +7,10 @@ import type { AndroidAdbExecutorResult, AndroidAdbProvider, } from '@agent-device/platform-android/mechanics'; -import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import { createProviderScenarioHarness } from './harness.ts'; import { PROVIDER_SCENARIO_ANDROID } from './fixtures.ts'; import { respondToAndroidSettingsAdbCommand } from './android-world.ts'; @@ -24,27 +27,6 @@ type DeadlineAdbState = { searchText: string; }; -function trustedSnapshotHelperResponse( - args: readonly string[], -): AndroidAdbExecutorResult | undefined { - const packageName = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName; - if (args.join(' ') === `shell cmd package list packages --show-versioncode ${packageName}`) { - return { - exitCode: 0, - stdout: `package:${packageName} versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, - stderr: '', - }; - } - if (args.join(' ') === `shell pm path ${packageName}`) { - return { exitCode: 0, stdout: `package:/data/app/${packageName}/base.apk\n`, stderr: '' }; - } - if (args[0] === 'pull' && args[1] === `/data/app/${packageName}/base.apk` && args[2]) { - fs.copyFileSync(ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]); - return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; - } - return undefined; -} - function awaitGestureAbort(signal: AbortSignal): Promise { return new Promise((_resolve, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }); @@ -65,7 +47,7 @@ function deadlineAdbInfrastructureResponse( if (state.signal?.aborted) state.retired = true; return { exitCode: 0, stdout: '', stderr: '' }; } - const helperResponse = trustedSnapshotHelperResponse(args); + const helperResponse = trustedInstalledSnapshotHelperResult(args); if (helperResponse) return helperResponse; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') return { exitCode: 0, stdout: 'Starting: Intent', stderr: '' }; @@ -304,7 +286,7 @@ test('annotated replay capture aborts within its deadline without post-failure f if (!captureSignal) throw new Error('annotated replay capture lost the request signal'); return await awaitGestureAbort(captureSignal); } - const helperResponse = trustedSnapshotHelperResponse(args); + const helperResponse = trustedInstalledSnapshotHelperResult(args); if (helperResponse) return helperResponse; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') return { exitCode: 0, stdout: 'Starting: Intent', stderr: '' }; diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index 053d4c2ba8b..c4db5b864a4 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -206,7 +206,7 @@ agent-device snapshot -s @e12 `truncated: true` means the Android snapshot helper hit its 5000-node or total XML character budget, the iOS Simulator accessibility bridge hit its 5000-node limit, or the web provider hit its own bound. On Android the node limit applies before any `-s` scope. An Android node with a -value clipped at the 64 KiB escaped-attribute limit has a matching attribute such as +value clipped at the 384 KiB escaped-text limit (64 KiB for other attributes) has a matching attribute such as `text-clipped="true"` in raw XML; that alone does not mean nodes are missing. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with `--raw`) the snapshot fails with a hint to scope it or take a screenshot instead. From 4bd3b1a8762a3fdd2d540847678b88e35bba62a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 20:52:37 +0100 Subject: [PATCH 16/26] test(android): reuse trusted IME helper fixture --- .../src/__tests__/ime-lifecycle.test.ts | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts index eb7b2e6532c..20e66c71104 100644 --- a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts @@ -1,10 +1,13 @@ import assert from 'node:assert/strict'; -import fs, { promises as fsp } from 'node:fs'; +import { 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'; +import { + ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + trustedInstalledSnapshotHelperResult, +} from './test-utils/android-snapshot-helper.ts'; const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; const SETTINGS_KEY = 'agent_device_ime_helper_previous_ime'; @@ -159,17 +162,11 @@ function fakeDeviceState(initialIme: string) { const adb: AndroidAdbExecutor = async (args) => { if (args.includes('--show-versioncode')) 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 installedHelper = trustedInstalledSnapshotHelperResult(args, { + apkPath: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, + manifest: { packageName: 'com.callstack.agentdevice.imehelper', versionCode: 1 }, + }); + if (installedHelper) return installedHelper; const handler = handlers[args.slice(0, 3).join(' ')]; if (!handler) throw new Error(`unexpected adb call: ${args.join(' ')}`); return handler(args); From b791ee2ad17e364682db24829e9b69bfb792b3db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:00:35 +0100 Subject: [PATCH 17/26] fix(android): keep helper admission table private --- packages/platform-android/src/helper-package-install.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts index 58f9b02ce59..6f559e0ed54 100644 --- a/packages/platform-android/src/helper-package-install.ts +++ b/packages/platform-android/src/helper-package-install.ts @@ -24,7 +24,7 @@ import { export type { AndroidHelperInstallDecision, InstalledAndroidHelperState }; const ANDROID_HELPER_IDENTITY_TIMEOUT_MS = 10_000; -export const ANDROID_HELPER_ADMISSION_REASONS = { +const ANDROID_HELPER_ADMISSION_REASONS = { // The installed helper has a higher version than the bundled artifact and cannot be trusted. newerUntrusted: { reason: 'android_helper_newer_untrusted' }, } as const satisfies ReasonTable<'android helper'>; From 60e55bd37507d3ab30b274659b44ae770b7b491c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:02:21 +0100 Subject: [PATCH 18/26] test(android): assert default deadline without fake-clock drift --- .../src/__tests__/fill-verification.test.ts | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index 325b4ec758a..2f72edc6d63 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -8,12 +8,12 @@ // whether any of a commit reached the field, which both the soft-success guard and the IME rebind // share. -import { afterEach, beforeEach, test } from 'vitest'; +import { afterEach, beforeEach, test, vi } from 'vitest'; import './test-utils/android-host-test-setup.ts'; import assert from 'node:assert/strict'; import { underFakeTimers } from './test-utils/fake-timers.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { DeadlineClock } from '@agent-device/host-kit/retry'; +import { Deadline, type DeadlineClock } from '@agent-device/host-kit/retry'; import { withAndroidAdbProvider, type AndroidAdbProvider } from '../adb-executor.ts'; import type { AndroidFillVerificationNode } from '../fill-diagnostics.ts'; import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; @@ -150,22 +150,25 @@ test('a value that never lands is a mismatch read from the last sample', async ( assert.equal(verification.actual, `Key echo ${session.captureCount()}`); }); -test('default verification stops at its 1500 ms deadline', async () => { +test('default verification uses a 1500 ms deadline', async () => { const session = createFillHelperSession({ textForCapture: (captureIndex) => `Key echo ${captureIndex}`, }); - const elapsedMs = await underFakeTimers(async () => { - const startedAt = Date.now(); - await withFillHelperProvider( - session.provider, - async () => - await verifyAndroidFilledText(device, 10, 10, 'chips', { - helperSessionScope: 'daemon-session', - }), - ); - return Date.now() - startedAt; - }); - assert.ok(elapsedMs >= 1500 && elapsedMs < 1700, `deadline elapsed ${elapsedMs} ms`); + const fromTimeout = vi.spyOn(Deadline, 'fromTimeoutMs'); + try { + await underFakeTimers(async () => { + await withFillHelperProvider( + session.provider, + async () => + await verifyAndroidFilledText(device, 10, 10, 'chips', { + helperSessionScope: 'daemon-session', + }), + ); + }); + assert.equal(fromTimeout.mock.calls[0]?.[0], 1500); + } finally { + fromTimeout.mockRestore(); + } }); test('the pre-action target read shares the daemon-session helper with the samples', async () => { From 503229c3053b02a3f95c9cfa85a827d508e07a14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:10:21 +0100 Subject: [PATCH 19/26] test(android): keep late fill verification on real helper time --- .../src/__tests__/fill-verification.test.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index 2f72edc6d63..3d8bbc13f7a 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -115,15 +115,12 @@ test('a value the app renders late still verifies, as long as it lands before th textForCapture: (captureIndex) => (captureIndex <= 6 ? 'Key echo' : 'chips'), }); - const verification = await underFakeTimers( + const verification = await withFillHelperProvider( + session.provider, async () => - await withFillHelperProvider( - session.provider, - async () => - await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { - helperSessionScope: 'daemon-session', - }), - ), + await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { + helperSessionScope: 'daemon-session', + }), ); assert.equal(verification.ok, true); From fdf0502e57e902ab66cb49e864db085890cb70be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 21:56:41 +0100 Subject: [PATCH 20/26] fix(android): refuse clipped text reads and explain helper checks --- docs/agents/performance.md | 3 +++ .../src/fill-verification-text-read.test.ts | 14 ++++++++++++++ packages/platform-android/src/fill-verification.ts | 7 ++++--- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/agents/performance.md b/docs/agents/performance.md index f2ff5c0e1bc..ab4aef470b4 100644 --- a/docs/agents/performance.md +++ b/docs/agents/performance.md @@ -32,3 +32,6 @@ A fact is a value that a request needs. Remove a deliberate safety check only with maintainer agreement. Example: `snapshot-target.ts` checks a cached target's PID start time. +Snapshot helper admission pulls and hashes the installed base APK on each cached use. +Package version, path, size, and timestamps do not prove the bytes after a same-version replacement. +Locale execution hashes again before `app_process` because the APK can change after admission. diff --git a/packages/platform-android/src/fill-verification-text-read.test.ts b/packages/platform-android/src/fill-verification-text-read.test.ts index 898a5d7c618..1c0961d3214 100644 --- a/packages/platform-android/src/fill-verification-text-read.test.ts +++ b/packages/platform-android/src/fill-verification-text-read.test.ts @@ -26,6 +26,20 @@ test('a unique identity can still read a field that moved away from the recorded expect(readAndroidTextAtPointInHierarchy(xml, 10, 10, identity)).toBe('moved live'); }); +test('a clipped text value is not returned as complete from identity or point reads', () => { + const clipped = ``; + expect(readAndroidTextAtPointInHierarchy(clipped, 10, 10, identity)).toBeNull(); + expect(readAndroidTextAtPointInHierarchy(clipped, 10, 10)).toBeNull(); + expect( + readAndroidTextAtPointInHierarchy(clipped, 10, 10, { ...identity, identifier: 'missing' }), + ).toBeNull(); + expect( + readAndroidTextAtPointInHierarchy(clipped.replace('text-clipped="true"', ''), 10, 10, identity), + ).toBe('prefix'); +}); + test('a moved Compose container reads by its published button role', () => { const xml = ` diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 2bb77f97bd7..3b7dd325644 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -391,9 +391,10 @@ export function readAndroidTextAtPointInHierarchy( const candidate = androidFillCandidateFromNode(node, {}); return candidate ? [candidate] : []; }); - if (matches.length === 1 && candidates.length === 1) return candidates[0]!.text; + if (matches.length === 1 && candidates.length === 1) + return candidates[0]!.textClipped ? null : candidates[0]!.text; const atPoint = candidates.filter((candidate) => containsPoint(candidate.rect, x, y)); - if (atPoint.length === 1) return atPoint[0]!.text; + if (atPoint.length === 1) return atPoint[0]!.textClipped ? null : atPoint[0]!.text; } // Reads are point-targeted: a focused sibling may be a different app field or an IME // composing surface, so it must not override the node that contains the requested point. @@ -404,7 +405,7 @@ export function readAndroidTextAtPointInHierarchy( (target?.type && !androidRawClassMatchesPublishedType(pointTarget.className, target.type)) ) return null; - return pointTarget.text; + return pointTarget.textClipped ? null : pointTarget.text; } export function androidFillFailureMessage(verification: AndroidFillVerification | null): string { From d8efb52976be11a7abc6a95d3ba01c95f424abff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 30 Nov 2026 22:02:03 +0100 Subject: [PATCH 21/26] refactor(android): keep text reads and guidance within budgets --- docs/agents/performance.md | 12 ++----- .../platform-android/src/fill-verification.ts | 33 +++++++++++++------ 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/docs/agents/performance.md b/docs/agents/performance.md index ab4aef470b4..1f86ac19baf 100644 --- a/docs/agents/performance.md +++ b/docs/agents/performance.md @@ -1,21 +1,16 @@ # Control request cost -A fact is a value that a request needs. - ## Per-request paths - If a fact is constant for the process or known in the request, pass it. Do not start a host process, read a file tree, or hash code to get it. - Example: `readProcessLock` reads the lock owner without `ps` (#5193). - Start independent reads together. - Example: the snapshot router resolves a route-scoped target during the surface probe (#5197). - Read a fact once per request. If an action between two reads, such as dispatch or recovery, can change it, read it again. ## Cache - Cache a fact for the process lifetime only if it changes only with the installed version. - Example: the runner source fingerprint in `runner-cache-metadata.ts` (#5196). - Only if a missed same-size rewrite within one filesystem timestamp tick is acceptable, validate a source-checkout fact by file stat. Example: `packages/host-kit/src/code-signature-cache.ts`. - Give each cache an owner, a generation, and an invalidation rule. @@ -31,7 +26,6 @@ A fact is a value that a request needs. ## Safety checks Remove a deliberate safety check only with maintainer agreement. -Example: `snapshot-target.ts` checks a cached target's PID start time. -Snapshot helper admission pulls and hashes the installed base APK on each cached use. -Package version, path, size, and timestamps do not prove the bytes after a same-version replacement. -Locale execution hashes again before `app_process` because the APK can change after admission. +Snapshot helper admission hashes the installed APK on each cached use. +Version, path, size, and timestamps cannot prove unchanged bytes. +Locale hashes again before `app_process` to detect replacement after admission. diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 3b7dd325644..78987286d15 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -386,15 +386,8 @@ export function readAndroidTextAtPointInHierarchy( ): string | null { const observation = parseAndroidFillObservation(xml); if (target?.identifier) { - const matches = observation.nodes.filter((node) => androidNodeMatchesFillTarget(node, target)); - const candidates = matches.flatMap((node) => { - const candidate = androidFillCandidateFromNode(node, {}); - return candidate ? [candidate] : []; - }); - if (matches.length === 1 && candidates.length === 1) - return candidates[0]!.textClipped ? null : candidates[0]!.text; - const atPoint = candidates.filter((candidate) => containsPoint(candidate.rect, x, y)); - if (atPoint.length === 1) return atPoint[0]!.textClipped ? null : atPoint[0]!.text; + const identityCandidate = textCandidateByIdentity(observation, x, y, target); + if (identityCandidate) return completeAndroidText(identityCandidate); } // Reads are point-targeted: a focused sibling may be a different app field or an IME // composing surface, so it must not override the node that contains the requested point. @@ -405,7 +398,27 @@ export function readAndroidTextAtPointInHierarchy( (target?.type && !androidRawClassMatchesPublishedType(pointTarget.className, target.type)) ) return null; - return pointTarget.textClipped ? null : pointTarget.text; + return completeAndroidText(pointTarget); +} + +function textCandidateByIdentity( + observation: AndroidFillObservation, + x: number, + y: number, + target: ElementTextTarget, +): AndroidFillVerificationCandidate | null { + const matches = observation.nodes.filter((node) => androidNodeMatchesFillTarget(node, target)); + const candidates = matches.flatMap((node) => { + const candidate = androidFillCandidateFromNode(node, {}); + return candidate ? [candidate] : []; + }); + if (matches.length === 1 && candidates.length === 1) return candidates[0]!; + const atPoint = candidates.filter((candidate) => containsPoint(candidate.rect, x, y)); + return atPoint.length === 1 ? atPoint[0]! : null; +} + +function completeAndroidText(candidate: AndroidFillVerificationCandidate): string | null { + return candidate.textClipped ? null : candidate.text; } export function androidFillFailureMessage(verification: AndroidFillVerification | null): string { From 59a1e54a902a8ecaf53e12d684ad61c8d4202a94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:51:16 +0100 Subject: [PATCH 22/26] fix(android): reject clipped selector text and narrow helper scope --- docs/agents/performance.md | 9 +- .../selector-runtime-get-reads.test.ts | 47 +++++++ .../src/execution/selector-text-runtime.ts | 16 ++- packages/kernel/src/snapshot.ts | 2 + .../src/__tests__/ime-helper.test.ts | 81 ++---------- .../src/__tests__/ime-lifecycle.test.ts | 11 +- .../src/__tests__/input-actions.test.ts | 16 +-- .../src/__tests__/settings-locale.test.ts | 62 ++++----- .../snapshot-capture-failure-reason.test.ts | 12 +- .../src/__tests__/snapshot-capture.test.ts | 10 +- .../snapshot-helper-exit-result.test.ts | 14 +- .../snapshot-helper-session.fixtures.ts | 12 +- .../snapshot-helper-start-retry.test.ts | 9 +- .../src/__tests__/snapshot-helper.test.ts | 123 ++++++++++-------- .../__tests__/snapshot-quality-fixtures.ts | 14 +- .../src/__tests__/snapshot-results.test.ts | 29 +++-- .../src/__tests__/snapshot.test.ts | 51 +++++--- .../test-utils/android-snapshot-helper.ts | 46 +++---- .../test-utils/android-snapshot-test-world.ts | 13 +- .../__tests__/touch-helper-session.test.ts | 23 ++-- .../src/__tests__/touch-helper.fixtures.ts | 20 +-- .../ui-hierarchy-field-metadata.test.ts | 12 ++ .../src/helper-package-install.ts | 68 ++++------ .../src/snapshot-helper-install.ts | 67 ++-------- .../platform-android/src/ui-hierarchy-node.ts | 1 + packages/platform-android/src/ui-hierarchy.ts | 1 + ...android-snapshot-occlusion-context.test.ts | 10 +- .../test-utils/android-snapshot-helper.ts | 32 ----- .../android-fill-capture-evidence.test.ts | 14 +- .../provider-scenarios/android-find.test.ts | 16 +-- .../android-ime-lifecycle-world.ts | 14 +- .../composite-deadline.test.ts | 21 +-- website/docs/docs/error-reasons.md | 7 +- website/docs/docs/snapshots.md | 6 +- 34 files changed, 410 insertions(+), 479 deletions(-) diff --git a/docs/agents/performance.md b/docs/agents/performance.md index 1f86ac19baf..f2ff5c0e1bc 100644 --- a/docs/agents/performance.md +++ b/docs/agents/performance.md @@ -1,16 +1,21 @@ # Control request cost +A fact is a value that a request needs. + ## Per-request paths - If a fact is constant for the process or known in the request, pass it. Do not start a host process, read a file tree, or hash code to get it. + Example: `readProcessLock` reads the lock owner without `ps` (#5193). - Start independent reads together. + Example: the snapshot router resolves a route-scoped target during the surface probe (#5197). - Read a fact once per request. If an action between two reads, such as dispatch or recovery, can change it, read it again. ## Cache - Cache a fact for the process lifetime only if it changes only with the installed version. + Example: the runner source fingerprint in `runner-cache-metadata.ts` (#5196). - Only if a missed same-size rewrite within one filesystem timestamp tick is acceptable, validate a source-checkout fact by file stat. Example: `packages/host-kit/src/code-signature-cache.ts`. - Give each cache an owner, a generation, and an invalidation rule. @@ -26,6 +31,4 @@ ## Safety checks Remove a deliberate safety check only with maintainer agreement. -Snapshot helper admission hashes the installed APK on each cached use. -Version, path, size, and timestamps cannot prove unchanged bytes. -Locale hashes again before `app_process` to detect replacement after admission. +Example: `snapshot-target.ts` checks a cached target's PID start time. diff --git a/packages/daemon/src/execution/selector-runtime-get-reads.test.ts b/packages/daemon/src/execution/selector-runtime-get-reads.test.ts index b03c8dc454d..108d2381b1f 100644 --- a/packages/daemon/src/execution/selector-runtime-get-reads.test.ts +++ b/packages/daemon/src/execution/selector-runtime-get-reads.test.ts @@ -17,6 +17,7 @@ import { runInteraction } from '../__tests__/support/touch-interaction-runner.ts import { handleInteractionCommands } from './interaction/index.ts'; import { contextFromFlags, + makeAndroidSession, makeSession, makeStaleRefSession, } from './interaction/internal/__tests__/interaction-touch-fixtures.ts'; @@ -201,6 +202,52 @@ test('get text answers from the captured tree when the bound owner advertises no } }); +test('get text refuses a clipped Android field instead of returning its cached prefix', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'get-text-clipped-android'; + const session = makeAndroidSession(sessionName); + session.snapshot = { + nodes: attachRefs([ + { + index: 0, + depth: 0, + type: 'android.widget.EditText', + identifier: 'com.android.settings:id/name', + bundleId: 'com.android.settings', + label: 'partial value', + value: 'partial value', + textClipped: true, + rect: { x: 20, y: 40, width: 120, height: 80 }, + }, + ]), + createdAt: Date.now(), + backend: 'android-helper', + producer: 'android-helper', + }; + sessionStore.publish(sessionName, session); + + const response = await handleInteractionCommands({ + createCommandSurface: touchCreateCommandSurface, + req: { + token: 't', + session: sessionName, + command: 'get', + positionals: ['text', '@e1'], + flags: {}, + }, + sessionName, + sessionStore, + contextFromFlags, + ...getRuntimeBindings(), + }); + + expect(response?.ok).toBe(false); + if (response && !response.ok) { + expect(response.error.details).toMatchObject({ reason: 'android_text_clipped' }); + } + expect(mockReadTextAtPoint).toHaveBeenCalledOnce(); +}); + // ADR 0019 regression: `get` declares `device-runtime`, so an ELIGIBLE direct-iOS selector — // one the fast path would otherwise answer without a tree capture — must not reach the device // until the request has resolved, admitted, and bound. A refused admission means zero runner diff --git a/packages/daemon/src/execution/selector-text-runtime.ts b/packages/daemon/src/execution/selector-text-runtime.ts index 8bdafcfc80f..7ac207abce8 100644 --- a/packages/daemon/src/execution/selector-text-runtime.ts +++ b/packages/daemon/src/execution/selector-text-runtime.ts @@ -4,6 +4,7 @@ import type { ElementTextUnreadableReason, } from '@agent-device/contracts/element-text-runtime'; import { isIosFamily } from '@agent-device/kernel/device'; +import { AppError } from '@agent-device/kernel/errors'; import { runtimeExecutionFromContext } from '../core/snapshot-runtime-capture-input.ts'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; @@ -31,10 +32,10 @@ export async function readTextForNode(params: { const { device, node, flags, appBundleId, traceOutPath, surface, contextFromFlags } = params; const fallbackText = extractReadableText(node); const readTextAtPoint = params.readTextAtPoint; - if (!readTextAtPoint) return fallbackText; + if (!readTextAtPoint) return safeFallbackText(device, node, fallbackText); const center = resolveRectCenter(node.rect); if (!center) { - return fallbackText; + return safeFallbackText(device, node, fallbackText); } if (isIosFamily(device) && fallbackText && !prefersValueForReadableText(node.type ?? '')) { @@ -66,7 +67,16 @@ export async function readTextForNode(params: { platform: device.platform, }, }); - return fallbackText; + return safeFallbackText(device, node, fallbackText); +} + +function safeFallbackText(device: DeviceInfo, node: SnapshotNode, text: string): string { + if (device.platform === 'android' && node.textClipped) { + throw new AppError('COMMAND_FAILED', 'Android text value was clipped by the snapshot helper', { + reason: 'android_text_clipped', + }); + } + return text; } function classifiedFallbackReason(reason: ElementTextUnreadableReason): string { diff --git a/packages/kernel/src/snapshot.ts b/packages/kernel/src/snapshot.ts index cba6ab2cc14..69622b67ba7 100644 --- a/packages/kernel/src/snapshot.ts +++ b/packages/kernel/src/snapshot.ts @@ -321,6 +321,8 @@ export type RawSnapshotNode = { * so `text ?? label` is the text the view shows. */ text?: string; + /** Android helper reports that the visible text is only a prefix of the field value. */ + textClipped?: boolean; identifier?: string; rect?: Rect; enabled?: boolean; diff --git a/packages/platform-android/src/__tests__/ime-helper.test.ts b/packages/platform-android/src/__tests__/ime-helper.test.ts index ae3bd1b4860..1b93ec47d26 100644 --- a/packages/platform-android/src/__tests__/ime-helper.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper.test.ts @@ -119,7 +119,7 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a assert.deepEqual(installCalls, [{ apkPath, replace: true }]); }); -test('ensureAndroidImeHelper refuses a newer helper whose digest is not trusted', async () => { +test('ensureAndroidImeHelper skips install when a newer version is already present', async () => { const tmpDir = await mkdtempForTest('ime-helper-current-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -140,16 +140,15 @@ test('ensureAndroidImeHelper refuses a newer helper whose digest is not trusted' }, }; - await assert.rejects( - ensureAndroidImeHelper({ - adb, - adbProvider, - artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, - deviceKey: 'android:emulator-5554', - }), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'android_helper_newer_untrusted', - ); + const result = await ensureAndroidImeHelper({ + adb, + adbProvider, + artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, + deviceKey: 'android:emulator-5554', + }); + + assert.equal(result.installed, false); + assert.equal(result.reason, 'current'); }); test('ensureAndroidImeHelper returns from an install once the IME is registered', async () => { @@ -232,13 +231,6 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer } : { exitCode: 0, stdout: '', stderr: '' }; } - if (args.join(' ') === `shell pm path ${manifest.packageName}`) { - return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; - } - if (args[0] === 'pull' && args[2]) { - await fs.writeFile(args[2], 'helper-apk'); - return { exitCode: 0, stdout: '', stderr: '' }; - } if (isImeListCall(args)) { return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; } @@ -271,59 +263,6 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer assert.equal(installs, 2); }); -test('ensureAndroidImeHelper reinstalls a cached same-version replacement', async () => { - const tmpDir = await mkdtempForTest('ime-helper-replaced-'); - const apkPath = path.join(tmpDir, 'helper.apk'); - await fs.writeFile(apkPath, 'helper-apk'); - let installedBytes = ''; - let installs = 0; - const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { - return installedBytes - ? { - exitCode: 0, - stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode}`, - stderr: '', - } - : { exitCode: 0, stdout: '', stderr: '' }; - } - if (args.join(' ') === `shell pm path ${manifest.packageName}`) { - return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; - } - if (args[0] === 'pull' && args[2]) { - await fs.writeFile(args[2], installedBytes); - return { exitCode: 0, stdout: '', stderr: '' }; - } - if (isImeListCall(args)) { - return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; - } - throw new Error(`unexpected adb call: ${args.join(' ')}`); - }; - const adbProvider: AndroidAdbProvider = { - exec: adb, - install: async () => { - installs += 1; - installedBytes = 'helper-apk'; - return { exitCode: 0, stdout: '', stderr: '' }; - }, - }; - const ensure = () => - ensureAndroidImeHelper({ - adb, - adbProvider, - artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, - deviceKey: 'android:emulator-5554', - }); - - assert.equal((await ensure()).installed, true); - assert.equal((await ensure()).installed, false); - installedBytes = 'same-version-replacement'; - const repaired = await ensure(); - assert.equal(repaired.reason, 'mismatched'); - assert.equal(repaired.installed, true); - assert.equal(installs, 2); -}); - test('ensureAndroidImeHelper install timeout points at the OEM install dialog', async () => { const tmpDir = await mkdtempForTest('ime-helper-install-timeout-'); const apkPath = path.join(tmpDir, 'helper.apk'); diff --git a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts index 20e66c71104..6d37d8638c5 100644 --- a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts @@ -4,10 +4,6 @@ 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, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; const SETTINGS_KEY = 'agent_device_ime_helper_previous_ime'; @@ -109,7 +105,7 @@ function fakeDeviceState(initialIme: string) { function handleShowVersionCode(): FakeAdbResult { return installed - ? ok('package:com.callstack.agentdevice.imehelper versionCode:1') + ? ok('package:com.callstack.agentdevice.imehelper versionCode:19002') : { exitCode: 1, stdout: '', stderr: 'not found' }; } @@ -162,11 +158,6 @@ function fakeDeviceState(initialIme: string) { const adb: AndroidAdbExecutor = async (args) => { if (args.includes('--show-versioncode')) return handleShowVersionCode(); - const installedHelper = trustedInstalledSnapshotHelperResult(args, { - apkPath: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, - manifest: { packageName: 'com.callstack.agentdevice.imehelper', versionCode: 1 }, - }); - if (installedHelper) return installedHelper; const handler = handlers[args.slice(0, 3).join(' ')]; if (!handler) throw new Error(`unexpected adb call: ${args.join(' ')}`); return handler(args); diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index 9b96777cdaf..c31b6ff6426 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -19,10 +19,7 @@ import { withFakeAdb } from './test-utils/fake-adb.ts'; import { withAndroidAdbProvider } from '../adb-executor.ts'; import type { AndroidTouchInjector } from '../adb-executor.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import { ANDROID_TOUCH_HELPER_MANIFEST as HELPER_MANIFEST, androidTouchHelperResultRecord as helperRecord, @@ -69,11 +66,12 @@ function helperRouteAdb(window: { keyboard?: { x: number; y: number; width: number; height: number }; }) { return (args: string[]) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args, { - apkPath: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, - manifest: HELPER_MANIFEST, - }); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + stdout: `package:${HELPER_MANIFEST.packageName} versionCode:999999`, + stderr: '', + }; + } if (args.includes('viewport')) { const { keyboard, ...app } = window; return { diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts index be9f5e9ca28..fc4d360de38 100644 --- a/packages/platform-android/src/__tests__/settings-locale.test.ts +++ b/packages/platform-android/src/__tests__/settings-locale.test.ts @@ -199,22 +199,22 @@ test('settings locale runs app_process from the base APK whose digest it verifie const firstCalls = calls.length; helper.pulls.length = 0; await setAndroidSetting(device, 'locale', 'de-DE'); - // The cached decision rechecks package presence and digest before the locale owner hashes the - // base APK it is about to execute. - expect(calls.slice(firstCalls).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.pulls).toEqual([APK, APK]); + // The cached install decision skipped the package manager, yet the base APK was hashed. + expect(calls.slice(firstCalls).map((args) => args.join(' '))).not.toContain(VERSION_QUERY); + expect(helper.pulls).toEqual([APK]); expect(helper.launches).toEqual([APK, APK]); }); }); -test('settings locale refuses a newer installed helper before running its code', async () => { +test('settings locale refuses a newer installed helper APK whose digest the manifest does not name', async () => { await withHelperDevice( async ({ device, helper }) => { await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { - reason: 'android_helper_newer_untrusted', - installedVersionCode: VERSION_CODE + 1, + reason: 'locale-helper-apk-unverified', + dispatched: 'no', + apkPath: APK, }, }); expect(helper.launches).toEqual([]); @@ -223,29 +223,25 @@ test('settings locale refuses a newer installed helper before running its code', ); }); -test('a locale refusal keeps the snapshot install memo and makes the next helper use repair it', async () => { +test('a locale refusal keeps the snapshot install memo and makes the next locale call inspect the install', async () => { await withHelperDevice( async ({ calls, device, helper, artifact }) => { await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ details: { reason: 'locale-helper-apk-unverified' }, }); - // The snapshot install memo rechecks package presence before answering current. + // The snapshot install step answers from its memo without touching the device. const snapshotCalls: (readonly string[])[] = []; const install = await ensureAndroidSnapshotHelper({ adb: async (args) => { snapshotCalls.push(args); - return { - stdout: `package:${PACKAGE} versionCode:${VERSION_CODE}`, - stderr: '', - exitCode: 0, - }; + return { stdout: '', stderr: 'unexpected', exitCode: 1 }; }, artifact, deviceKey: `android:${device.id}`, }); - expect(install).toMatchObject({ reason: 'unverifiable', installed: true }); - expect(snapshotCalls.map((args) => args.join(' '))).toContain(VERSION_QUERY); + expect(install).toMatchObject({ reason: 'current', installed: false }); + expect(snapshotCalls).toEqual([]); const firstCall = calls.length; await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ @@ -254,11 +250,11 @@ test('a locale refusal keeps the snapshot install memo and makes the next helper expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); expect(helper.launches).toEqual([]); }, - { versionCode: undefined, installs: 'another-apk' }, + { versionCode: VERSION_CODE + 1, bytes: 'another-apk' }, ); }); -test('a concurrent locale call repairs a replaced helper while another call prepares it', async () => { +test('a locale call that saw no refusal keeps a refusal recorded while it prepared the helper', async () => { let pmPathFails = false; await withHelperDevice( async ({ calls, device, helper }) => { @@ -280,9 +276,9 @@ test('a concurrent locale call repairs a replaced helper while another call prep const callA = setAndroidSetting(device, 'locale', 'de-DE'); await preparing; - // Call B revalidates the cached install and repairs the replaced APK before dispatch. - await expect(setAndroidSetting(device, 'locale', 'de-DE')).resolves.toMatchObject({ - locale: 'de-DE', + // Call B refuses the APK and records a recheck. + await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({ + details: { reason: 'locale-helper-apk-unverified' }, }); // Call A resumes and fails on the transport, so it answers no refusal. @@ -307,24 +303,29 @@ test('a concurrent locale call repairs a replaced helper while another call prep ); }); -test('settings locale repairs a helper package replaced after a cached install decision', async () => { +test('settings locale refuses a helper package replaced after a cached install decision, then rechecks it', async () => { await withHelperDevice(async ({ calls, device, helper }) => { await setAndroidSetting(device, 'locale', 'en-IN'); let firstCall = calls.length; helper.apkPath = `/data/app/~~c3==/${PACKAGE}-d4==/base.apk`; helper.files.set(helper.apkPath, 'another-apk'); - await expect(setAndroidSetting(device, 'locale', 'de-DE')).resolves.toMatchObject({ - locale: 'de-DE', + await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { + reason: 'locale-helper-apk-unverified', + dispatched: 'no', + apkPath: helper.apkPath, + }, }); - expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.launches).toHaveLength(2); + expect(calls.slice(firstCall).map((args) => args.join(' '))).not.toContain(VERSION_QUERY); + expect(helper.launches).toHaveLength(1); // The genuine helper is back; the next locale command inspects the package again. helper.files.set(helper.apkPath, HELPER_BYTES); firstCall = calls.length; await setAndroidSetting(device, 'locale', 'de-DE'); expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.launches).toHaveLength(3); + expect(helper.launches).toHaveLength(2); }); }); @@ -371,7 +372,8 @@ test('settings locale refuses with dispatched no when pm path reports no base AP expect(helper.launches).toEqual([]); }, { - versionCode: VERSION_CODE, + // A newer versionCode lets the install step accept the package without reading its path. + versionCode: VERSION_CODE + 1, override: (args) => args.join(' ') === `shell pm path ${PACKAGE}` ? 'package:/data/app/split_config.arm64_v8a.apk\n' @@ -398,7 +400,7 @@ test('settings locale keeps the adb classification when pm path fails on the tra expect(helper.launches).toEqual([]); }, { - versionCode: VERSION_CODE, + versionCode: VERSION_CODE + 1, override: (args) => args.join(' ') === `shell pm path ${PACKAGE}` ? { stderr: 'error: device offline', exitCode: 1 } @@ -421,7 +423,7 @@ test('settings locale keeps the adb failure when the base APK cannot be pulled', expect(helper.launches).toEqual([]); }, { - versionCode: VERSION_CODE, + versionCode: VERSION_CODE + 1, // `pm path` names a base APK that the pull cannot read. override: (args) => args.join(' ') === `shell pm path ${PACKAGE}` diff --git a/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts b/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts index ba913765e83..bded0d90741 100644 --- a/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-capture-failure-reason.test.ts @@ -7,10 +7,7 @@ import type { AndroidAdbExecutor, AndroidAdbExecutorResult } from '../adb-execut import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import { isAndroidSnapshotTimeoutError } from '@agent-device/capture-kit/snapshot-timeout-policy'; import './test-utils/android-host-test-setup.ts'; @@ -58,7 +55,12 @@ function createHelperAdb( } function helperVersionResponse(args: readonly string[]): AndroidAdbExecutorResult | undefined { - return trustedInstalledSnapshotHelperResult(args); + if (!args.includes('--show-versioncode')) return undefined; + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stderr: '', + }; } function isHelperForceStop(args: readonly string[]): boolean { diff --git a/packages/platform-android/src/__tests__/snapshot-capture.test.ts b/packages/platform-android/src/__tests__/snapshot-capture.test.ts index 69d276a17bd..4f6cc026dd7 100644 --- a/packages/platform-android/src/__tests__/snapshot-capture.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-capture.test.ts @@ -16,7 +16,6 @@ import { androidSnapshotQualityDevice as device, androidSnapshotQualityHelperArtifact as helperArtifact, } from './snapshot-quality-fixtures.ts'; -import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; const SCREEN_XML = ''; @@ -71,8 +70,13 @@ function helperAdbServing( 'INSTRUMENTATION_CODE: 0', ].join('\n'); return async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (args.includes('instrument')) { return { exitCode: 0, stdout, stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts index 1e1a3e5b988..99a03b85c20 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-exit-result.test.ts @@ -30,10 +30,7 @@ import { isAndroidHelperRuntimeProbe, } from './snapshot-helper-session.fixtures.ts'; import { mkdtempForTest } from './test-utils/tmp-dir.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; beforeEach(async () => { resetAndroidSnapshotHelperRetirements(); @@ -106,8 +103,13 @@ function encodedPayload(xml: string): string { function helperFailingWith(run: FailedRun): AndroidAdbExecutor { return async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); if (isAndroidHelperRuntimeForceStop(args)) return { exitCode: 0, stdout: '', stderr: '' }; return { stderr: '', ...run }; diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts index e445965d748..1761c06bd6e 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -25,7 +25,12 @@ import { } from '../snapshot-helper-types.ts'; import type { AndroidAdbExecutor } from '../snapshot-helper-types.ts'; import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts'; -import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; + +export const ANDROID_HELPER_INSTALLED_VERSION_PROBE = { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', +}; export class FakeAndroidProcess extends EventEmitter implements AndroidAdbProcess { stdin = new PassThrough(); @@ -497,8 +502,9 @@ function persistentSnapshotExecResult( options: PersistentSnapshotHelperProviderOptions, args: readonly string[], ): ReturnType { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return Promise.resolve(installedHelper); + if (args.includes('--show-versioncode')) { + return Promise.resolve(ANDROID_HELPER_INSTALLED_VERSION_PROBE); + } // A current adb: it negotiated shell protocol v2, so a host exit status is the device's. if (args[0] === 'features') { return Promise.resolve({ exitCode: 0, stdout: 'cmd\nstat_v2\nshell_v2\n', stderr: '' }); diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 748d74a790c..497cd830397 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -24,11 +24,9 @@ import { isRefusedInstrumentationStart } from '../instrumentation-helper.ts'; import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; -import { + ANDROID_HELPER_INSTALLED_VERSION_PROBE, createSessionProvider, androidHelperInstrumentationOutput, androidHelperRuntimeProbeResult, @@ -108,8 +106,7 @@ function freshlyBootedHelper( provider: { exec: async (args) => { calls.push(args); - const installed = trustedInstalledSnapshotHelperResult(args); - if (installed) return installed; + if (args.includes('--show-versioncode')) return ANDROID_HELPER_INSTALLED_VERSION_PROBE; if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); if (!isOneShotRun(args)) return { exitCode: 0, stdout: '', stderr: '' }; const run = runs.shift() ?? CAPTURED_RUN; diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index 4ce8ee9a0c3..cc6e8ff8200 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -9,6 +9,7 @@ import { } from '../snapshot-helper-capture.ts'; import { ensureAndroidSnapshotHelper, + forgetAndroidSnapshotHelperInstall, resetAndroidSnapshotHelperInstallCache, } from '../snapshot-helper-install.ts'; import { AppError } from '@agent-device/kernel/errors'; @@ -172,7 +173,7 @@ test('parseAndroidSnapshotHelperOutput falls back to error type for null helper }); }); -test('ensureAndroidSnapshotHelper installs when missing and refuses an untrusted newer version', async () => { +test('ensureAndroidSnapshotHelper installs when missing and skips a newer version', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -198,18 +199,17 @@ test('ensureAndroidSnapshotHelper installs when missing and refuses an untrusted assert.equal(installed.reason, 'missing'); assert.deepEqual(calls[1], ['install', '-r', apkPath]); - await assert.rejects( - ensureAndroidSnapshotHelper({ - adb: async () => ({ - exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', - stderr: '', - }), - artifact: { apkPath, manifest: localManifest }, + const skipped = await ensureAndroidSnapshotHelper({ + adb: async () => ({ + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', }), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'android_helper_newer_untrusted', - ); + artifact: { apkPath, manifest: localManifest }, + }); + + assert.equal(skipped.installed, false); + assert.equal(skipped.reason, 'current'); }); test('ensureAndroidSnapshotHelper tags a device-side install rejection distinctly from artifact resolution', async () => { @@ -399,7 +399,7 @@ test('installing a same-version different-sha helper evicts the stale install me assert.deepEqual(installs, [apkPathB, apkPathA]); }); -test('ensureAndroidSnapshotHelper revalidates a cached installed digest', async () => { +test('ensureAndroidSnapshotHelper caches successful install checks per device and helper version', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-cache-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -408,29 +408,10 @@ test('ensureAndroidSnapshotHelper revalidates a cached installed digest', async sha256: sha256Text('helper-apk'), }; const calls: (readonly string[])[] = []; - let installedVersionCode: number | undefined; - let installedBytes = ''; const adb: AndroidAdbExecutor = async (args) => { calls.push(args); if (args.includes('--show-versioncode')) { - return installedVersionCode === undefined - ? { exitCode: 1, stdout: '', stderr: 'not found' } - : { - exitCode: 0, - stdout: `package:${localManifest.packageName} versionCode:${installedVersionCode}`, - stderr: '', - }; - } - if (args.join(' ') === `shell pm path ${localManifest.packageName}`) { - return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; - } - if (args[0] === 'pull' && args[2]) { - await fs.writeFile(args[2], installedBytes); - return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; - } - if (args[0] === 'install') { - installedVersionCode = localManifest.versionCode; - installedBytes = 'helper-apk'; + return { exitCode: 1, stdout: '', stderr: 'not found' }; } return { exitCode: 0, stdout: '', stderr: '' }; }; @@ -441,7 +422,7 @@ test('ensureAndroidSnapshotHelper revalidates a cached installed digest', async artifact, deviceKey: 'android:emulator-5554', }); - const callsBeforeMemoHit = calls.length; + await fs.rm(apkPath); const cached = await ensureAndroidSnapshotHelper({ adb, artifact, @@ -452,18 +433,38 @@ test('ensureAndroidSnapshotHelper revalidates a cached installed digest', async assert.equal(cached.reason, 'current'); assert.equal(cached.installed, false); assert.equal(cached.installedVersionCode, localManifest.versionCode); - assert.ok(calls.length > callsBeforeMemoHit); - assert.equal(calls.filter((args) => args[0] === 'install').length, 1); + assert.deepEqual(calls, [ + [ + 'shell', + 'cmd', + 'package', + 'list', + 'packages', + '--show-versioncode', + localManifest.packageName, + ], + ['install', '-r', apkPath], + ]); - installedBytes = 'same-version-replacement'; - const replaced = await ensureAndroidSnapshotHelper({ + await fs.writeFile(apkPath, 'helper-apk'); + await ensureAndroidSnapshotHelper({ adb, artifact, + deviceKey: 'android:device-2', + }); + assert.equal(calls.length, 4); + + forgetAndroidSnapshotHelperInstall({ deviceKey: 'android:emulator-5554', + packageName: localManifest.packageName, + versionCode: localManifest.versionCode, }); - assert.equal(replaced.reason, 'mismatched'); - assert.equal(replaced.installed, true); - assert.equal(calls.filter((args) => args[0] === 'install').length, 2); + await ensureAndroidSnapshotHelper({ + adb, + artifact, + deviceKey: 'android:emulator-5554', + }); + assert.equal(calls.length, 6); }); test('ensureAndroidSnapshotHelper always policy bypasses cached install result', async () => { @@ -488,15 +489,11 @@ test('ensureAndroidSnapshotHelper always policy bypasses cached install result', }; const artifact = { apkPath, manifest: localManifest }; - await assert.rejects( - ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:emulator-5554', - }), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'android_helper_newer_untrusted', - ); + const cached = await ensureAndroidSnapshotHelper({ + adb, + artifact, + deviceKey: 'android:emulator-5554', + }); const forced = await ensureAndroidSnapshotHelper({ adb, artifact, @@ -504,12 +501,30 @@ test('ensureAndroidSnapshotHelper always policy bypasses cached install result', installPolicy: 'always', }); + assert.equal(cached.reason, 'current'); assert.equal(forced.reason, 'forced'); assert.equal(forced.installed, true); - assert.deepEqual( - calls.filter((args) => args[0] === 'install'), - [['install', '-r', apkPath]], - ); + assert.deepEqual(calls, [ + [ + 'shell', + 'cmd', + 'package', + 'list', + 'packages', + '--show-versioncode', + localManifest.packageName, + ], + [ + 'shell', + 'cmd', + 'package', + 'list', + 'packages', + '--show-versioncode', + localManifest.packageName, + ], + ['install', '-r', apkPath], + ]); }); test('shared Android helper verifier rejects snapshot helper checksum mismatch', async () => { diff --git a/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts b/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts index 695e62ea1bd..c7f3434204a 100644 --- a/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts @@ -1,8 +1,5 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import type { AndroidAdbExecutor } from '../snapshot-helper.ts'; export const androidSnapshotQualityDevice: DeviceInfo = { @@ -15,10 +12,15 @@ export const androidSnapshotQualityDevice: DeviceInfo = { export const androidSnapshotQualityHelperArtifact = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT; +const installedHelperProbe = { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', +}; + export function androidSnapshotQualityHelperAdb(xml: string): AndroidAdbExecutor { return async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) return installedHelperProbe; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/snapshot-results.test.ts b/packages/platform-android/src/__tests__/snapshot-results.test.ts index e2389a4ba8f..21d82352d86 100644 --- a/packages/platform-android/src/__tests__/snapshot-results.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-results.test.ts @@ -22,8 +22,10 @@ import { AppError } from '@agent-device/kernel/errors'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; import { type AndroidAdbExecutor } from '../snapshot-helper.ts'; -import { androidHelperInstrumentationOutput as helperOutput } from './snapshot-helper-session.fixtures.ts'; -import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; +import { + androidHelperInstrumentationOutput as helperOutput, + ANDROID_HELPER_INSTALLED_VERSION_PROBE as installedHelperProbe, +} from './snapshot-helper-session.fixtures.ts'; import { mockSleep, @@ -43,8 +45,13 @@ afterEach(async () => { test('snapshotAndroid emits helper failure diagnostics', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') return { exitCode: 0, stdout: '', stderr: '' }; return { exitCode: 1, stdout: '', stderr: 'helper unavailable' }; @@ -189,8 +196,7 @@ test('snapshotAndroid fails closed after unparseable helper output', async () => const calls: (readonly string[])[] = []; const helperAdb: AndroidAdbExecutor = async (args) => { calls.push(args); - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) return installedHelperProbe; if (args.includes('instrument')) return { exitCode: 0, stdout: '', stderr: '' }; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; @@ -244,9 +250,14 @@ test('snapshotAndroid re-probes helper install after helper capture failure', as let versionProbeCount = 0; let instrumentAttempts = 0; const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) versionProbeCount += 1; - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + versionProbeCount += 1; + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (args.includes('instrument')) { instrumentAttempts += 1; if (instrumentAttempts === 1) { diff --git a/packages/platform-android/src/__tests__/snapshot.test.ts b/packages/platform-android/src/__tests__/snapshot.test.ts index b29d7c78390..e1e4f79ecf4 100644 --- a/packages/platform-android/src/__tests__/snapshot.test.ts +++ b/packages/platform-android/src/__tests__/snapshot.test.ts @@ -27,6 +27,7 @@ import { androidHelperInstrumentationOutput as helperOutput, createPersistentSnapshotHelperProvider, isAndroidHelperRuntimeForceStop as isHelperRuntimeReset, + ANDROID_HELPER_INSTALLED_VERSION_PROBE as installedHelperProbe, androidSystemWindowOnlyXml, type FakeAndroidProcess, } from './snapshot-helper-session.fixtures.ts'; @@ -44,7 +45,6 @@ import { captureDiagnostics, resetSnapshotTestState, } from './test-utils/android-snapshot-test-world.ts'; -import { trustedInstalledSnapshotHelperResult } from './test-utils/android-snapshot-helper.ts'; beforeEach(resetSnapshotTestState); @@ -205,8 +205,13 @@ test('snapshotAndroid uses the injected helper artifact', async () => { const timeouts: Array = []; const helperAdb: AndroidAdbExecutor = async (args, options) => { timeouts.push(options?.timeoutMs); - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (args.includes('instrument')) { return { exitCode: 0, @@ -228,14 +233,13 @@ test('snapshotAndroid uses the injected helper artifact', async () => { assert.equal(result.androidSnapshot.installReason, 'current'); assert.equal(result.androidSnapshot.captureMode, 'interactive-windows'); assert.equal(result.androidSnapshot.windowCount, 1); - assert.deepEqual(timeouts, [5000, 10000, 10000, 30000]); + assert.deepEqual(timeouts, [5000, 30000]); assert.equal(mockRunCmd.mock.calls.length, 0); }); test('snapshotAndroid reports helper-side truncation on the public snapshot result', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) return installedHelperProbe; if (args.includes('instrument')) { return { exitCode: 0, @@ -264,8 +268,7 @@ test('snapshotAndroid reports helper-side truncation on the public snapshot resu test('snapshotAndroid discloses unavailable sibling order for API 23 helper trees', async () => { const captured: string[] = []; const helperAdb: AndroidAdbExecutor = async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) return installedHelperProbe; if (args.includes('instrument')) { const xml = captured.shift(); if (!xml) throw new Error('unexpected extra capture'); @@ -288,8 +291,13 @@ test('snapshotAndroid discloses unavailable sibling order for API 23 helper tree test('snapshotAndroid emits helper phase diagnostics', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (args.includes('instrument')) { return { exitCode: 0, @@ -325,8 +333,13 @@ test('snapshotAndroid resolves helper adb through scoped provider', async () => snapshotHelperArtifact: helperArtifact, exec: async (args) => { adbCalls.push(args); - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (isAndroidSdkVersionCommand(args)) { return { exitCode: 0, stdout: '35', stderr: '' }; } @@ -355,7 +368,7 @@ test('snapshotAndroid resolves helper adb through scoped provider', async () => assert.equal(result.androidSnapshot.helperVersion, helperArtifact.manifest.version); assert.deepEqual( adbCalls.map((args) => args[0]), - ['shell', 'shell', 'pull', 'shell'], + ['shell', 'shell'], ); assert.equal(mockRunCmd.mock.calls.length, 0); }); @@ -582,8 +595,13 @@ test('snapshotAndroid fails closed when the helper fails', async () => { const adbCalls: (readonly string[])[] = []; const helperAdb: AndroidAdbExecutor = async (args) => { adbCalls.push(args); - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stderr: '', + }; + } if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } @@ -606,8 +624,7 @@ test('snapshotAndroid fails closed when helper returns only system windows', asy const helperXml = androidSystemWindowOnlyXml(); const helperAdb: AndroidAdbExecutor = async (args) => { adbCalls.push(args); - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) return installedHelperProbe; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts b/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts index 9341e8a7525..fc75575b560 100644 --- a/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts +++ b/packages/platform-android/src/__tests__/test-utils/android-snapshot-helper.ts @@ -1,6 +1,5 @@ import { fileURLToPath } from 'node:url'; -import fs from 'node:fs'; -import type { AndroidAdbExecutor, AndroidAdbExecutorResult } from '../../adb-executor.ts'; +import type { AndroidAdbExecutor } from '../../adb-executor.ts'; import type { AndroidSnapshotHelperArtifact } from '../../snapshot-helper-types.ts'; const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; @@ -27,38 +26,18 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti }, }; -export function trustedInstalledSnapshotHelperResult( - args: readonly string[], - artifact: { - apkPath: string; - manifest: { packageName: string; versionCode: number }; - } = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, -): AndroidAdbExecutorResult | undefined { - const packageName = artifact.manifest.packageName; - if (args.includes('--show-versioncode') && args.includes(packageName)) { - return { - exitCode: 0, - stdout: `package:${packageName} versionCode:${artifact.manifest.versionCode}\n`, - stderr: '', - }; - } - if (args.join(' ') === `shell pm path ${packageName}`) { - return { exitCode: 0, stdout: `package:/data/app/${packageName}/base.apk\n`, stderr: '' }; - } - if (args[0] === 'pull' && args[1] === `/data/app/${packageName}/base.apk` && args[2]) { - fs.copyFileSync(artifact.apkPath, args[2]); - return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; - } - return undefined; -} - export function createAndroidSnapshotHelperExecutor(options: { readonly exec: AndroidAdbExecutor; readonly captureXml: () => string | Promise; }): AndroidAdbExecutor { return async (args, execOptions) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (isAndroidSnapshotHelperVersionProbe(args)) { + return { + exitCode: 0, + stdout: `package:${SNAPSHOT_HELPER_PACKAGE} versionCode:999999`, + stderr: '', + }; + } if (isAndroidSnapshotHelperCapture(args)) { return { exitCode: 0, @@ -90,12 +69,17 @@ function androidSnapshotHelperOutput(xml: string): string { ].join('\n'); } +function isAndroidSnapshotHelperVersionProbe(args: readonly string[]): boolean { + return args.includes('--show-versioncode') && args.includes(SNAPSHOT_HELPER_PACKAGE); +} + export function androidSnapshotHelperScriptResponse( args: readonly string[], captureXml: () => string, ): string | undefined { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper.stdout; + if (isAndroidSnapshotHelperVersionProbe(args)) { + return `package:${SNAPSHOT_HELPER_PACKAGE} versionCode:999999`; + } if (isAndroidSnapshotHelperCapture(args)) return androidSnapshotHelperOutput(captureXml()); return undefined; } diff --git a/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts b/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts index 0b5509bd76b..798a41539fc 100644 --- a/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts +++ b/packages/platform-android/src/__tests__/test-utils/android-snapshot-test-world.ts @@ -10,13 +10,11 @@ import { resetAndroidSnapshotHelperInstallCache } from '../../snapshot-helper-in import { resetAndroidSnapshotHelperSessions } from '../../snapshot-helper-session-lifecycle.ts'; import type { AndroidAdbExecutor } from '../../snapshot-helper.ts'; import { mkdtempForTest } from './android-host-test-setup.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './android-snapshot-helper.ts'; import { androidHelperInstrumentationOutput as helperOutput, isAndroidHelperRuntimeForceStop as isHelperRuntimeReset, + ANDROID_HELPER_INSTALLED_VERSION_PROBE as installedHelperProbe, } from '../snapshot-helper-session.fixtures.ts'; export const VALID_PNG = Buffer.from( @@ -56,8 +54,7 @@ export function createHelperAdb( handlers: Partial>, ): AndroidAdbExecutor { return async (args, options) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (isHelperVersionProbe(args)) return installedHelperProbe; if (isHelperRuntimeReset(args)) { return { exitCode: 0, stdout: '', stderr: '' }; } @@ -68,6 +65,10 @@ export function createHelperAdb( }; } +function isHelperVersionProbe(args: readonly string[]): boolean { + return args.includes('--show-versioncode'); +} + function helperAdbOperation(args: readonly string[]): 'instrument' | 'activity' | undefined { if (args.includes('instrument')) return 'instrument'; return args.includes('dumpsys') && args.includes('activity') ? 'activity' : undefined; diff --git a/packages/platform-android/src/__tests__/touch-helper-session.test.ts b/packages/platform-android/src/__tests__/touch-helper-session.test.ts index 9a3528ce919..b66d24e6a1c 100644 --- a/packages/platform-android/src/__tests__/touch-helper-session.test.ts +++ b/packages/platform-android/src/__tests__/touch-helper-session.test.ts @@ -28,10 +28,7 @@ import { executeAndroidTouchHelperPlan, readAndroidTouchHelperViewportReading, } from '../touch-helper.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import { ANDROID_TOUCH_HELPER_MANIFEST as manifest, androidTouchHelperResultRecord as resultRecord, @@ -375,8 +372,13 @@ test('a provider artifact that mismatches the live session helper stops it and r // Artifact B is already current on the device, so no install happens: the session started // by artifact A must be invalidated by the helper-identity guard, not the install path. exec: async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args, providerArtifact); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: `package:${providerArtifact.manifest.packageName} versionCode:999999`, + stderr: '', + }; + } instrumentArgs = [...args]; return { exitCode: 0, @@ -441,8 +443,13 @@ test('a same-version artifact with a different sha stops the live session and ru // A is reported already current by versionCode, so no install occurs: only the sha in the // session helper identity can reveal that the live session runs B's binary. exec: async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args, artifactA); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: `package:${artifactA.manifest.packageName} versionCode:999999`, + stderr: '', + }; + } instrumentArgs = [...args]; return { exitCode: 0, diff --git a/packages/platform-android/src/__tests__/touch-helper.fixtures.ts b/packages/platform-android/src/__tests__/touch-helper.fixtures.ts index 67eaf59f71b..f5cd36e57fd 100644 --- a/packages/platform-android/src/__tests__/touch-helper.fixtures.ts +++ b/packages/platform-android/src/__tests__/touch-helper.fixtures.ts @@ -3,10 +3,6 @@ import { buildGesturePlan } from '@agent-device/gestures/gesture-plan'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { AndroidAdbExecutor } from '../adb-executor.ts'; import type { AndroidLongPressTouchPlan } from '../touch-plan-lowering.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from './test-utils/android-snapshot-helper.ts'; // The one-shot touch helper path now runs through the snapshot-helper APK/runner // (issue #1275 consolidation), so these fixtures mirror the snapshot helper's @@ -67,14 +63,18 @@ export function flingPlan() { ); } -// Wraps an executor that presents the trusted fixture APK as already installed. +// Wraps an executor that answers the shared install-decision probe as "already +// current" (a much newer installed versionCode) so tests can focus on the +// gesture/viewport call that follows without also faking an install flow. export function currentVersionAdb(handleInstrument: AndroidAdbExecutor): AndroidAdbExecutor { return async (args, options) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args, { - apkPath: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, - manifest: ANDROID_TOUCH_HELPER_MANIFEST, - }); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: `package:${ANDROID_TOUCH_HELPER_MANIFEST.packageName} versionCode:999999`, + stderr: '', + }; + } return handleInstrument(args, options); }; } diff --git a/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts b/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts index 8b05994af3a..9db2cff4cee 100644 --- a/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts +++ b/packages/platform-android/src/__tests__/ui-hierarchy-field-metadata.test.ts @@ -21,6 +21,18 @@ test.each([false, true])( }, ); +test.each([false, true])('clipped text remains marked on a complete tree (raw=%s)', (raw) => { + const tree = parseUiHierarchyTree(``); + const { nodes, truncated } = buildUiHierarchySnapshot(tree, undefined, { raw }); + expect(truncated).not.toBe(true); + expect(nodes.find((node) => node.identifier === 'field')).toMatchObject({ + value: 'partial value', + textClipped: true, + }); +}); + test('selection offsets survive on a read-only selectable node (independent of editable)', () => { const tree = parseUiHierarchyTree(`; - -export function newerUntrustedAndroidHelperError( - packageName: string, - installedVersionCode: number, - versionCode: number, -): AppError { - return new AppError( - 'COMMAND_FAILED', - 'Installed Android helper is newer than the trusted artifact.', - { - reason: ANDROID_HELPER_ADMISSION_REASONS.newerUntrusted.reason, - packageName, - installedVersionCode, - versionCode, - }, - ); -} /** * The one install seam every Android helper APK crosses, so an install timeout carries the @@ -87,28 +66,28 @@ async function ensureAndroidHelperPackageInstalled(options: { helperLabel, } = options; const cacheKey = `${deviceKey}\0${packageName}\0${versionCode}\0${sha256}`; - const cachedState = cache.has(cacheKey) - ? await inspectInstalledAndroidHelper({ adb, adbProvider, packageName, versionCode, sha256 }) - : undefined; - if (cachedState?.reason === 'current') { - return { - packageName, - versionCode, - ...cachedState, - installed: false, - reason: 'current', - }; + if (cache.has(cacheKey)) { + // The cache skips the checksums, never the presence check: an emulator that is wiped or + // restored from a snapshot keeps its serial but may no longer have the helper. + const installedVersionCode = await readInstalledAndroidPackageVersionCode(adb, packageName); + if (installedVersionCode !== undefined && installedVersionCode >= versionCode) { + return { + packageName, + versionCode, + installedSha256: sha256, + installed: false, + reason: 'current', + }; + } } await verifyAndroidHelperApkChecksum(apkPath, sha256, helperLabel); - const state = - cachedState ?? - (await inspectInstalledAndroidHelper({ - adb, - adbProvider, - packageName, - versionCode, - sha256, - })); + const state = await inspectInstalledAndroidHelper({ + adb, + adbProvider, + packageName, + versionCode, + sha256, + }); if (state.reason === 'current') { cache.add(cacheKey); @@ -120,10 +99,6 @@ async function ensureAndroidHelperPackageInstalled(options: { }; } - if (state.installedVersionCode !== undefined && state.installedVersionCode > versionCode) { - throw newerUntrustedAndroidHelperError(packageName, state.installedVersionCode, versionCode); - } - const result = await installAndroidHelperPackage(apkPath, { provider: adbProvider, replace: true, @@ -167,6 +142,7 @@ export async function inspectInstalledAndroidHelper(options: { installedVersionCode, reason: ANDROID_HELPER_INSTALL_STATE_REASONS.outdated.reason, }; + if (installedVersionCode > versionCode) return { installedVersionCode, reason: 'current' }; try { const installedSha256 = await readInstalledAndroidPackageSha256( diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 544282f2253..a4a020de001 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -2,7 +2,6 @@ import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/err import { inspectInstalledAndroidHelper, installAndroidHelperPackage, - newerUntrustedAndroidHelperError, verifyAndroidHelperApkChecksum, } from './helper-package-install.ts'; import { @@ -79,36 +78,6 @@ function forgetInstalledSnapshotHelper(cacheKey: string | undefined): void { } } -async function inspectCachedSnapshotHelper(options: { - installCacheKey: string | undefined; - cachedVersionCode: number | undefined; - installPolicy: AndroidSnapshotHelperInstallPolicy; - inspectInstalled: boolean | undefined; - adb: AndroidAdbExecutor; - adbProvider: AndroidAdbProvider | AndroidAdbExecutor | undefined; - packageName: string; - versionCode: number; - sha256: string; - signal: AbortSignal | undefined; -}): Promise> | undefined> { - if ( - !options.installCacheKey || - options.installPolicy === 'always' || - options.inspectInstalled || - options.cachedVersionCode === undefined - ) { - return undefined; - } - return await inspectInstalledAndroidHelper({ - adb: options.adb, - adbProvider: normalizeAdbProvider(options.adbProvider, options.adb), - packageName: options.packageName, - versionCode: options.versionCode, - sha256: options.sha256, - signal: options.signal, - }); -} - export async function ensureAndroidSnapshotHelper(options: { adb: AndroidAdbExecutor; adbProvider?: AndroidAdbProvider | AndroidAdbExecutor; @@ -137,29 +106,21 @@ export async function ensureAndroidSnapshotHelper(options: { const cachedVersionCode = installCacheKey ? installedSnapshotHelpers.get(installCacheKey) : undefined; - const cachedInstalledState = await inspectCachedSnapshotHelper({ - installCacheKey, - cachedVersionCode, - installPolicy, - inspectInstalled: options.inspectInstalled, - adb, - adbProvider: options.adbProvider, - packageName, - versionCode, - sha256, - signal: options.signal, - }); - if (cachedInstalledState?.reason === 'current') { + if ( + installCacheKey && + installPolicy !== 'always' && + !options.inspectInstalled && + cachedVersionCode !== undefined + ) { return { packageName, versionCode, - installedVersionCode: cachedInstalledState.installedVersionCode, - installedSha256: cachedInstalledState.installedSha256, + installedVersionCode: cachedVersionCode, + installedSha256: sha256, installed: false, reason: 'current', }; } - if (cachedInstalledState) forgetInstalledSnapshotHelper(installCacheKey); await verifyAndroidHelperApkChecksum(artifact.apkPath, sha256, 'Android snapshot helper'); const installedState = installPolicy === 'always' @@ -173,15 +134,14 @@ export async function ensureAndroidSnapshotHelper(options: { reason: 'forced' as const, installedSha256: undefined, } - : (cachedInstalledState ?? - (await inspectInstalledAndroidHelper({ + : await inspectInstalledAndroidHelper({ adb, adbProvider: normalizeAdbProvider(options.adbProvider, adb), packageName, versionCode, sha256, signal: options.signal, - }))); + }); const { installedVersionCode, installedSha256, reason } = installedState; if (reason === 'current') { @@ -207,13 +167,6 @@ export async function ensureAndroidSnapshotHelper(options: { }, ); } - if ( - installPolicy !== 'always' && - installedVersionCode !== undefined && - installedVersionCode > versionCode - ) { - throw newerUntrustedAndroidHelperError(packageName, installedVersionCode, versionCode); - } let result: Awaited>; try { diff --git a/packages/platform-android/src/ui-hierarchy-node.ts b/packages/platform-android/src/ui-hierarchy-node.ts index c1d7a30ef81..930271871a7 100644 --- a/packages/platform-android/src/ui-hierarchy-node.ts +++ b/packages/platform-android/src/ui-hierarchy-node.ts @@ -8,6 +8,7 @@ type AndroidPassiveNodeFacts = Pick< RawSnapshotNode, | 'contentDescription' | 'text' + | 'textClipped' | 'enabled' | 'selected' | 'heading' diff --git a/packages/platform-android/src/ui-hierarchy.ts b/packages/platform-android/src/ui-hierarchy.ts index b1bcbdf477b..7791f376a40 100644 --- a/packages/platform-android/src/ui-hierarchy.ts +++ b/packages/platform-android/src/ui-hierarchy.ts @@ -356,6 +356,7 @@ function normalizeAndroidUiHierarchyNode( passiveFacts: { contentDescription: attrs.desc && attrs.desc !== label ? attrs.desc : undefined, text: label && !attrs.text ? '' : undefined, + textClipped: attrs.textClipped, enabled: attrs.enabled, selected: attrs.selected, heading: attrs.heading, diff --git a/src/__tests__/android-snapshot-occlusion-context.test.ts b/src/__tests__/android-snapshot-occlusion-context.test.ts index 4cd5f5a3ce7..29525e0a8aa 100644 --- a/src/__tests__/android-snapshot-occlusion-context.test.ts +++ b/src/__tests__/android-snapshot-occlusion-context.test.ts @@ -14,7 +14,6 @@ import { coveredAndroidReplacementNodeIndexes } from '@agent-device/capture-kit/ import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, androidSnapshotHelperOutput, - trustedInstalledSnapshotHelperResult, } from './test-utils/android-snapshot-helper.ts'; import '../platform-runtime-android-adb-host.ts'; @@ -69,8 +68,13 @@ test('scoped Android captures retain broad off-wire context for daemon occlusion function oneShotHelper(xml: string): AndroidAdbExecutor { return async (args) => { - const installedHelper = trustedInstalledSnapshotHelperResult(args); - if (installedHelper) return installedHelper; + if (args.includes('--show-versioncode')) { + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stderr: '', + }; + } if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'force-stop') { return { exitCode: 0, stdout: '', stderr: '' }; } diff --git a/src/__tests__/test-utils/android-snapshot-helper.ts b/src/__tests__/test-utils/android-snapshot-helper.ts index 6c390c1408f..55d38858977 100644 --- a/src/__tests__/test-utils/android-snapshot-helper.ts +++ b/src/__tests__/test-utils/android-snapshot-helper.ts @@ -1,5 +1,4 @@ import type { AndroidSnapshotHelperArtifact } from '@agent-device/platform-android/mechanics'; -import fs from 'node:fs'; import { fileURLToPath } from 'node:url'; const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; @@ -26,37 +25,6 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti }, }; -export function trustedInstalledSnapshotHelperResult( - args: readonly string[], -): { exitCode: number; stdout: string; stderr: string } | undefined { - if ( - args.join(' ') === - `shell cmd package list packages --show-versioncode ${SNAPSHOT_HELPER_PACKAGE}` - ) { - return { - exitCode: 0, - stdout: `package:${SNAPSHOT_HELPER_PACKAGE} versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, - stderr: '', - }; - } - if (args.join(' ') === `shell pm path ${SNAPSHOT_HELPER_PACKAGE}`) { - return { - exitCode: 0, - stdout: `package:/data/app/${SNAPSHOT_HELPER_PACKAGE}/base.apk\n`, - stderr: '', - }; - } - if ( - args[0] === 'pull' && - args[1] === `/data/app/${SNAPSHOT_HELPER_PACKAGE}/base.apk` && - args[2] - ) { - fs.copyFileSync(SNAPSHOT_HELPER_FIXTURE_APK_PATH, args[2]); - return { exitCode: 0, stdout: '1 file pulled\n', stderr: '' }; - } - return undefined; -} - export function androidSnapshotHelperOutput( xml: string, options: { pixelDensity?: number } = {}, diff --git a/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts b/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts index 8cc55a6f315..0b34d51ac46 100644 --- a/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts +++ b/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts @@ -9,10 +9,7 @@ import type { AndroidAdbProvider, } from '@agent-device/platform-android/mechanics'; import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-ime-helper.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import { androidImeLifecycleAdbResult, createAndroidProviderShellState, @@ -457,11 +454,7 @@ function createAdbProvider(device: Device): AndroidAdbProvider { if (key.startsWith('shell am instrument ')) device.events.push('capture:one-shot'); if (key.startsWith('shell input ')) device.events.push(key); updateAndroidProviderImeShellState(args, ime); - return ( - trustedInstalledSnapshotHelperResult(args) ?? - androidImeLifecycleAdbResult(key, args, ime) ?? - ok(adbStdout(key)) - ); + return androidImeLifecycleAdbResult(key, args, ime) ?? ok(adbStdout(key)); }, spawn: (args) => startHelperSession(device, args), }; @@ -472,6 +465,9 @@ function adbStdout(key: string): string { if (key.startsWith('shell dumpsys window')) { return `mCurrentFocus=Window{42 u0 ${APP}/.Settings}\n`; } + if (key.includes('--show-versioncode com.callstack.agentdevice.snapshothelper')) { + return `package:com.callstack.agentdevice.snapshothelper versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`; + } return ''; } diff --git a/test/integration/provider-scenarios/android-find.test.ts b/test/integration/provider-scenarios/android-find.test.ts index a2a19ecb35c..15228f7ff95 100644 --- a/test/integration/provider-scenarios/android-find.test.ts +++ b/test/integration/provider-scenarios/android-find.test.ts @@ -1,10 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-ime-helper.ts'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import type { AndroidAdbProvider } from '@agent-device/platform-android/mechanics'; import { WAIT_REASONS } from '@agent-device/contracts/wait'; import { FIND_NO_MATCH_HINT } from '@agent-device/selectors'; @@ -30,8 +27,6 @@ test('Provider-backed integration Android find flow covers refs, wait, ambiguity imeHelperArtifact: ANDROID_IME_HELPER_FIXTURE_ARTIFACT, exec: async (args) => { adbCalls.push([...args]); - const trustedSnapshotHelper = trustedInstalledSnapshotHelperResult(args); - if (trustedSnapshotHelper) return trustedSnapshotHelper; updateAndroidProviderImeShellState([...args], ime); if (args[0] === 'shell' && args[1] === 'input' && args[2] === 'text') { ime.searchText = String(args[3] ?? '').replaceAll('%s', ' '); @@ -138,14 +133,7 @@ test('Provider-backed integration Android find flow covers refs, wait, ambiguity // The field's label repeats its typed value (no editable fact: the EditText class decides), // so only its identifier satisfies `wait text`. const typedWait = await daemon.callCommand('wait', ['text', 'Network', '100'], selection); - const typedWaitFailure = typedWait.json?.error?.data; - assert.equal(typedWaitFailure?.code, 'COMMAND_FAILED'); - const waitReason = typedWaitFailure?.details?.reason; - assert.ok( - waitReason === WAIT_REASONS.targetAbsent.reason || - waitReason === WAIT_REASONS.deadlineExceeded.reason, - `unexpected wait reason: ${String(waitReason)}`, - ); + assert.equal(typedWait.json?.error?.data?.details?.reason, WAIT_REASONS.targetAbsent.reason); assert.equal( assertRpcOk(await daemon.callCommand('wait', ['text', 'id/search', '100'], selection)).text, 'id/search', diff --git a/test/integration/provider-scenarios/android-ime-lifecycle-world.ts b/test/integration/provider-scenarios/android-ime-lifecycle-world.ts index 84798d8bb80..9ef2cac415b 100644 --- a/test/integration/provider-scenarios/android-ime-lifecycle-world.ts +++ b/test/integration/provider-scenarios/android-ime-lifecycle-world.ts @@ -1,6 +1,3 @@ -import fs from 'node:fs'; -import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-ime-helper.ts'; - type AndroidImeAdbResult = { stdout: string; stderr: string; @@ -95,19 +92,14 @@ export function androidImeLifecycleAdbResult( if ( key === 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.imehelper' ) { + // A newer provider-installed helper takes the actual durable activation/recovery path without + // adding an unrelated helper-installation fixture to each scenario. return { - stdout: `package:${IME_PACKAGE} versionCode:${ANDROID_IME_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`, + stdout: 'package:com.callstack.agentdevice.imehelper versionCode:999999\n', stderr: '', exitCode: 0, }; } - if (key === `shell pm path ${IME_PACKAGE}`) { - return { stdout: `package:/data/app/${IME_PACKAGE}/base.apk\n`, stderr: '', exitCode: 0 }; - } - if (args[0] === 'pull' && args[1] === `/data/app/${IME_PACKAGE}/base.apk` && args[2]) { - fs.copyFileSync(ANDROID_IME_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]); - return { stdout: '1 file pulled\n', stderr: '', exitCode: 0 }; - } if (!state) return undefined; if (argsStartWith(args, ['shell', 'settings', 'get', 'secure']) && args[4]) { return { diff --git a/test/integration/provider-scenarios/composite-deadline.test.ts b/test/integration/provider-scenarios/composite-deadline.test.ts index 302958d906d..ef2487f230b 100644 --- a/test/integration/provider-scenarios/composite-deadline.test.ts +++ b/test/integration/provider-scenarios/composite-deadline.test.ts @@ -7,10 +7,7 @@ import type { AndroidAdbExecutorResult, AndroidAdbProvider, } from '@agent-device/platform-android/mechanics'; -import { - ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - trustedInstalledSnapshotHelperResult, -} from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import { createProviderScenarioHarness } from './harness.ts'; import { PROVIDER_SCENARIO_ANDROID } from './fixtures.ts'; import { respondToAndroidSettingsAdbCommand } from './android-world.ts'; @@ -47,8 +44,12 @@ function deadlineAdbInfrastructureResponse( if (state.signal?.aborted) state.retired = true; return { exitCode: 0, stdout: '', stderr: '' }; } - const helperResponse = trustedInstalledSnapshotHelperResult(args); - if (helperResponse) return helperResponse; + if (args.includes('--show-versioncode')) + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stderr: '', + }; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') return { exitCode: 0, stdout: 'Starting: Intent', stderr: '' }; return undefined; @@ -286,8 +287,12 @@ test('annotated replay capture aborts within its deadline without post-failure f if (!captureSignal) throw new Error('annotated replay capture lost the request signal'); return await awaitGestureAbort(captureSignal); } - const helperResponse = trustedInstalledSnapshotHelperResult(args); - if (helperResponse) return helperResponse; + if (args.includes('--show-versioncode')) + return { + exitCode: 0, + stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stderr: '', + }; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') return { exitCode: 0, stdout: 'Starting: Intent', stderr: '' }; return respondToAndroidSettingsAdbCommand([...args], '', '', {}); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index e356c24174b..a4678f54ca9 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -486,12 +486,6 @@ These reasons can come from more than one command. | --- | --- | | `managed-device-transport-mismatch` | The call aimed a managed adb transport at another device, target, or server. | -### Android helper - -| Reason | Meaning | -| --- | --- | -| `android_helper_newer_untrusted` | The installed helper has a higher version than the bundled artifact and cannot be trusted. | - ### Android helper install | Reason | Meaning | @@ -524,6 +518,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `android_text_clipped` | The snapshot helper returned only a prefix of the field text, and a live read could not provide the full value. | | `android_shell_text_unsupported` | The adb-shell fallback carries ASCII text only; a helper or provider channel is needed. | | `android_ime_helper_no_ack` | The test IME helper gave no evidence it attempted the dispatch, so nothing is proven typed. | | `android_ime_helper_dispatch_rejected` | The test IME helper answered that it rejected the dispatch, so nothing was typed. | diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index c4db5b864a4..c8bd7659c6a 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -206,9 +206,9 @@ agent-device snapshot -s @e12 `truncated: true` means the Android snapshot helper hit its 5000-node or total XML character budget, the iOS Simulator accessibility bridge hit its 5000-node limit, or the web provider hit its own bound. On Android the node limit applies before any `-s` scope. An Android node with a -value clipped at the 384 KiB escaped-text limit (64 KiB for other attributes) has a matching attribute such as -`text-clipped="true"` in raw XML; -that alone does not mean nodes are missing. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with +value clipped at the 384 KiB escaped-text limit (64 KiB for other attributes) has +`textClipped: true` on the snapshot node. The tree remains complete, but `get text` rejects that +partial value. The Apple runner does not return a partial tree: above its limit (50,000 nodes, or 5,000 with `--raw`) the snapshot fails with a hint to scope it or take a screenshot instead. Every backend walks the tree in document order, so what gets cut is what comes last: footers, tab From 530e259a4b3640ae63a7d12c65bf14c96f71031e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:29:24 +0100 Subject: [PATCH 23/26] fix(android): classify clipped selector fallback before diagnostics --- .../runtime/snapshot-unchanged.test.ts | 1 + .../capture/runtime/snapshot-unchanged.ts | 1 + .../command-surface/src/interaction/index.ts | 2 ++ .../__tests__/selector-text-runtime.test.ts | 26 ++++++++++++++++++- .../selector-runtime-get-reads.test.ts | 4 +-- .../src/execution/selector-text-runtime.ts | 12 ++++++--- website/docs/docs/commands.md | 1 + website/docs/docs/error-reasons.md | 8 +++++- 8 files changed, 48 insertions(+), 7 deletions(-) diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts index d937b6db39a..9fac7cdb097 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.test.ts @@ -76,6 +76,7 @@ test.each>([ { identifier: 'create' }, { contentDescription: 'Create a draft' }, { text: '' }, + { textClipped: true }, { enabled: false }, { selected: true }, { checked: true }, diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts index b98fefae212..5d79f51041c 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-unchanged.ts @@ -120,6 +120,7 @@ const PRESENTATION_SCALAR_FIELDS = { value: true, contentDescription: true, text: true, + textClipped: true, identifier: true, enabled: true, editable: true, diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index bc88d209637..dd519808354 100644 --- a/packages/command-surface/src/interaction/index.ts +++ b/packages/command-surface/src/interaction/index.ts @@ -652,6 +652,8 @@ const getCommandFacet = defineCommandFacet({ text: { summary: 'Read element text or attributes', searchHint: 'value label', + cliDetail: + 'On Android, get text refuses a clipped field value with reason android_text_clipped when the live read cannot provide complete text. The snapshot can still be complete; inspect textClipped on the node.', }, metadata: metadata('get'), run: (client, input) => client.interactions.get(toGetOptions(input)), diff --git a/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts b/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts index 492ad368548..bf95b17f6e7 100644 --- a/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/selector-text-runtime.test.ts @@ -7,6 +7,12 @@ import { } from '@agent-device/contracts/element-text-runtime'; import { readTextForNode } from '../selector-text-runtime.ts'; +const diagnostic = vi.hoisted(() => ({ emitDiagnostic: vi.fn() })); +vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => ({ + ...(await importOriginal()), + emitDiagnostic: diagnostic.emitDiagnostic, +})); + /** * Bound at the seam the handler consumes (the runtime's `readTextAtPoint` operation), never at * `-device/device-selection/dispatch-resolve`: `get` is migrated, so the live read reaches this fake through the request @@ -34,7 +40,10 @@ const baseParams = { }; describe('readTextForNode', () => { - beforeEach(() => readTextAtPoint.mockClear()); + beforeEach(() => { + readTextAtPoint.mockClear(); + diagnostic.emitDiagnostic.mockClear(); + }); it('returns snapshot text without a live read for non-editable nodes', async () => { const text = await readTextForNode({ @@ -109,6 +118,21 @@ describe('readTextForNode', () => { node: node({ type: 'textfield', value: 'snap' }), }); expect(text).toBe('snap'); + expect(diagnostic.emitDiagnostic).toHaveBeenCalledWith( + expect.objectContaining({ phase: 'interaction_read_fallback' }), + ); + }); + + it('refuses a clipped Android prefix before reporting a fallback', async () => { + readTextAtPoint.mockResolvedValueOnce({ status: 'unreadable', reason: 'no-text-at-point' }); + await expect( + readTextForNode({ + ...baseParams, + device: { platform: 'android' } as never, + node: node({ type: 'android.widget.EditText', value: 'prefix', textClipped: true }), + }), + ).rejects.toMatchObject({ details: { reason: 'android_text_clipped' } }); + expect(diagnostic.emitDiagnostic).not.toHaveBeenCalled(); }); it('classifies a blank live read as no-text-at-point rather than reading blank text', async () => { diff --git a/packages/daemon/src/execution/selector-runtime-get-reads.test.ts b/packages/daemon/src/execution/selector-runtime-get-reads.test.ts index 108d2381b1f..6fe8a8d1690 100644 --- a/packages/daemon/src/execution/selector-runtime-get-reads.test.ts +++ b/packages/daemon/src/execution/selector-runtime-get-reads.test.ts @@ -221,8 +221,8 @@ test('get text refuses a clipped Android field instead of returning its cached p }, ]), createdAt: Date.now(), - backend: 'android-helper', - producer: 'android-helper', + backend: 'android', + producer: 'android-uiautomator', }; sessionStore.publish(sessionName, session); diff --git a/packages/daemon/src/execution/selector-text-runtime.ts b/packages/daemon/src/execution/selector-text-runtime.ts index 7ac207abce8..28620c04d92 100644 --- a/packages/daemon/src/execution/selector-text-runtime.ts +++ b/packages/daemon/src/execution/selector-text-runtime.ts @@ -4,7 +4,7 @@ import type { ElementTextUnreadableReason, } from '@agent-device/contracts/element-text-runtime'; import { isIosFamily } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { runtimeExecutionFromContext } from '../core/snapshot-runtime-capture-input.ts'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; @@ -19,6 +19,11 @@ import { resolveRectCenter } from '@agent-device/kernel/rect-center'; export type ReadElementTextAtPoint = ElementTextRuntimeOperations['readTextAtPoint']; +const SELECTOR_TEXT_READ_REASONS = { + // The Android helper returned only a prefix, and the live read did not supply the full value. + clipped: { reason: 'android_text_clipped', commands: ['find'] }, +} as const satisfies ReasonTable<'get'>; + export async function readTextForNode(params: { device: DeviceInfo; node: SnapshotNode; @@ -57,6 +62,7 @@ export async function readTextForNode(params: { execution: runtimeExecutionFromContext(context), }); if (outcome.status === 'read') return outcome.text; + const fallback = safeFallbackText(device, node, fallbackText); emitDiagnostic({ level: 'warn', phase: 'interaction_read_fallback', @@ -67,13 +73,13 @@ export async function readTextForNode(params: { platform: device.platform, }, }); - return safeFallbackText(device, node, fallbackText); + return fallback; } function safeFallbackText(device: DeviceInfo, node: SnapshotNode, text: string): string { if (device.platform === 'android' && node.textClipped) { throw new AppError('COMMAND_FAILED', 'Android text value was clipped by the snapshot helper', { - reason: 'android_text_clipped', + reason: SELECTOR_TEXT_READ_REASONS.clipped.reason, }); } return text; diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index ecf5676bcda..77af9de6b43 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -875,6 +875,7 @@ agent-device get text @e1 agent-device get attrs @e1 ``` +- On Android, `get text` fails with `android_text_clipped` when the snapshot has only a field-value prefix and a live read cannot provide the complete text. Check the node's `textClipped` flag; the tree itself can still be complete. - `--raw` returns the full provider tree, including offscreen nodes and structural wrappers. See [iOS capture behavior](/docs/snapshots#ios-capture-behavior) and [Android capture behavior](/docs/snapshots#android-capture-behavior). - A source checkout must run `pnpm build:android` before Android verification, because Android snapshots install a bundled helper. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index a4678f54ca9..ce7d5305c99 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -117,6 +117,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `android_text_clipped` | The Android helper returned only a prefix, and the live read did not supply the full value. | | `find_snapshot_unreadable` | The capture came back sparse, so no selector could be resolved against it. | ### `fold` @@ -151,6 +152,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `GESTURE_TRAJECTORY_NON_FINITE` | A trajectory sample carries a non-finite coordinate. | | `GESTURE_TRAJECTORY_OUT_OF_BOUNDS` | A trajectory sample leaves the viewport, so the contact would press outside the screen, or a two-finger path cannot keep its contacts the minimum span apart inside it. | +### `get` + +| Reason | Meaning | +| --- | --- | +| `android_text_clipped` | The Android helper returned only a prefix, and the live read did not supply the full value. | + ### `home` | Reason | Meaning | @@ -518,7 +525,6 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | -| `android_text_clipped` | The snapshot helper returned only a prefix of the field text, and a live read could not provide the full value. | | `android_shell_text_unsupported` | The adb-shell fallback carries ASCII text only; a helper or provider channel is needed. | | `android_ime_helper_no_ack` | The test IME helper gave no evidence it attempted the dispatch, so nothing is proven typed. | | `android_ime_helper_dispatch_rejected` | The test IME helper answered that it rejected the dispatch, so nothing was typed. | From 34cfb921e7361c587439d852ff2284d5e6bd4397 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:55:58 +0100 Subject: [PATCH 24/26] fix(android): attribute clipped text read reason to get --- packages/daemon/src/execution/selector-text-runtime.ts | 2 +- website/docs/docs/error-reasons.md | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/daemon/src/execution/selector-text-runtime.ts b/packages/daemon/src/execution/selector-text-runtime.ts index 28620c04d92..885a366bc49 100644 --- a/packages/daemon/src/execution/selector-text-runtime.ts +++ b/packages/daemon/src/execution/selector-text-runtime.ts @@ -21,7 +21,7 @@ export type ReadElementTextAtPoint = ElementTextRuntimeOperations['readTextAtPoi const SELECTOR_TEXT_READ_REASONS = { // The Android helper returned only a prefix, and the live read did not supply the full value. - clipped: { reason: 'android_text_clipped', commands: ['find'] }, + clipped: { reason: 'android_text_clipped', commands: ['get'] }, } as const satisfies ReasonTable<'get'>; export async function readTextForNode(params: { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index ce7d5305c99..e3a89daa61d 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -117,7 +117,6 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | -| `android_text_clipped` | The Android helper returned only a prefix, and the live read did not supply the full value. | | `find_snapshot_unreadable` | The capture came back sparse, so no selector could be resolved against it. | ### `fold` From d9323acf2f5a4a9e2dcd86104da1a051b2482d6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 10:57:45 +0100 Subject: [PATCH 25/26] fix(android): omit clipped non-text helper attributes --- .../snapshothelper/AccessibilityTreeXml.java | 5 +++++ .../snapshothelper/AccessibilityTreeXmlTest.java | 10 ++++++++++ 2 files changed, 15 insertions(+) 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 29b06ff9ca8..5556ffad784 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 @@ -232,6 +232,11 @@ private static void appendAppAttribute( } xml.append('"'); if (consumed < value.length()) { + if (!name.equals("text")) { + xml.setLength(attributeStart); + stats.truncated = true; + return; + } boolean markerFits = xml.length() + clippedMarker.length() <= maxXmlChars; if (markerFits) { xml.append(clippedMarker); diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java index 6b7e6df24d3..05e01e20823 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/AccessibilityTreeXmlTest.java @@ -11,6 +11,7 @@ static void run() { assertLongClickable(true, " long-clickable=\"true\""); assertLongClickable(false, " long-clickable=\"false\""); assertAppAttributeBoundsEscapedOutput(); + assertClippedDescriptionIsOmitted(); assertTextAttributeAdmitsMaximumFill(); assertDocumentLimitedTextMarksClip(); assertUnmarkedPartialTextIsOmitted(); @@ -31,6 +32,15 @@ private static void assertAppAttributeBoundsEscapedOutput() { } } + private static void assertClippedDescriptionIsOmitted() { + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.Stats stats = new AccessibilityTreeXml.Stats(); + AccessibilityTreeXml.appendAppAttribute(xml, "content-desc", "x".repeat(70 * 1024), stats); + if (!stats.truncated || xml.length() != 0) { + throw new AssertionError("Clipped descriptions must not look complete to the host"); + } + } + private static void assertTextAttributeAdmitsMaximumFill() { StringBuilder value = new StringBuilder(); for (int index = 0; index < 64 * 1024; index += 1) value.append('"'); From 7e9c0c4e674eb46f5d43f840d0f46e2cd24b890c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 11:32:34 +0100 Subject: [PATCH 26/26] test(android): pin fill verification polling budget --- .../src/__tests__/fill-verification.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/platform-android/src/__tests__/fill-verification.test.ts b/packages/platform-android/src/__tests__/fill-verification.test.ts index 3d8bbc13f7a..7330376d9c6 100644 --- a/packages/platform-android/src/__tests__/fill-verification.test.ts +++ b/packages/platform-android/src/__tests__/fill-verification.test.ts @@ -115,12 +115,15 @@ test('a value the app renders late still verifies, as long as it lands before th textForCapture: (captureIndex) => (captureIndex <= 6 ? 'Key echo' : 'chips'), }); - const verification = await withFillHelperProvider( - session.provider, + const verification = await underFakeTimers( async () => - await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { - helperSessionScope: 'daemon-session', - }), + await withFillHelperProvider( + session.provider, + async () => + await verifyAndroidFilledTextWithDeadline(device, 10, 10, 'chips', sampleBudget(10), { + helperSessionScope: 'daemon-session', + }), + ), ); assert.equal(verification.ok, true); @@ -145,6 +148,7 @@ test('a value that never lands is a mismatch read from the last sample', async ( assert.equal(verification.ok, false); assert.equal(verification.reason, 'text_mismatch'); assert.equal(verification.actual, `Key echo ${session.captureCount()}`); + assert.ok(session.captureCount() >= 10, 'verification polls through the full sample budget'); }); test('default verification uses a 1500 ms deadline', async () => {