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..20beebd1062 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 { + /** Longest text emitted whole; longer app text keeps this prefix and adds `text-clipped`. */ + static final int MAX_TEXT_CHARS = 64 * 1024; + private AccessibilityTreeXml() {} @SuppressWarnings("deprecation") @@ -39,7 +42,7 @@ static void appendNode( } CharSequence text = node.getText(); if (text != null) { - appendAttribute(xml, "text", text); + appendTextAttribute(xml, text); } // getText() returns the HINT for an empty field on modern Android, so `text` alone cannot // distinguish a cleared field from one whose value equals its hint; only this flag can @@ -213,6 +216,19 @@ private static void appendWindowMetadata(StringBuilder xml, WindowMetadata metad } } + static void appendTextAttribute(StringBuilder xml, CharSequence text) { + if (text.length() <= MAX_TEXT_CHARS) { + appendAttribute(xml, "text", text); + return; + } + int end = + Character.isHighSurrogate(text.charAt(MAX_TEXT_CHARS - 1)) + ? MAX_TEXT_CHARS - 1 + : MAX_TEXT_CHARS; + appendAttribute(xml, "text", text.subSequence(0, end)); + appendAttribute(xml, "text-clipped", "true"); + } + private static void appendAttribute(StringBuilder xml, String name, CharSequence value) { String stringValue = value == null ? "" : value.toString(); xml.append(' '); 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..5a5fff65d3a 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,28 @@ static void run() { " window-bounds=\"[-2147483648,-1][0,2147483647]\""); assertLongClickable(true, " long-clickable=\"true\""); assertLongClickable(false, " long-clickable=\"false\""); + assertTextClipping(); + } + + private static void assertTextClipping() { + String complete = "x".repeat(AccessibilityTreeXml.MAX_TEXT_CHARS); + StringBuilder xml = new StringBuilder(); + AccessibilityTreeXml.appendTextAttribute(xml, complete); + if (!xml.toString().equals(" text=\"" + complete + "\"")) { + throw new AssertionError("Text at the limit must stay complete and unmarked"); + } + xml.setLength(0); + AccessibilityTreeXml.appendTextAttribute(xml, complete + "y"); + if (!xml.toString().equals(" text=\"" + complete + "\" text-clipped=\"true\"")) { + throw new AssertionError("Text past the limit must keep its prefix and mark the clip"); + } + String split = "x".repeat(AccessibilityTreeXml.MAX_TEXT_CHARS - 1) + "\uD83D\uDE00"; + String prefix = split.substring(0, AccessibilityTreeXml.MAX_TEXT_CHARS - 1); + xml.setLength(0); + AccessibilityTreeXml.appendTextAttribute(xml, split); + if (!xml.toString().equals(" text=\"" + prefix + "\" text-clipped=\"true\"")) { + throw new AssertionError("A clip must not split a surrogate pair"); + } } private static void assertLongClickable(boolean longClickable, String expected) { 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-runtime/src/commands/interaction/runtime/selector-is.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-is.ts index d11bbee1be0..1621f3116e5 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-is.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-is.ts @@ -22,6 +22,7 @@ import { type SelectorSnapshotOptions, captureSelectorSnapshot, observationReadFailure, + refuseClippedText, } from './selector-read-shared.ts'; import { deriveSelectorCapturePolicy } from './selector-capture-policy.ts'; import { absenceCaptureOptionRefusal } from '@agent-device/selectors/absence-observation'; @@ -156,6 +157,7 @@ async function resolveAssertedPredicate( }, }); } + if (predicate === 'text') refuseClippedText(outcome.node); const result = evaluateIsPredicate({ predicate, node: outcome.node, diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-read-shared.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-read-shared.ts index b6f3ad446bb..c7b39a549c1 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read-shared.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read-shared.ts @@ -124,11 +124,24 @@ export async function captureSelectorSnapshot( return { sessionName, session, snapshot }; } +/** A clipped text is only a prefix, so no text read or assertion may use it as the value. */ +export function refuseClippedText(node: Pick): void { + if (node.textClipped !== true) return; + throw new AppError( + 'COMMAND_FAILED', + 'The element text is clipped, so its full value is unknown', + { + reason: INTERACTION_ERROR_REASONS.textClipped.reason, + }, + ); +} + export async function readText( runtime: AgentDeviceRuntime, capture: CapturedSnapshot, node: SnapshotNode, ): Promise { + refuseClippedText(node); if (runtime.backend.readText) { const result = await runtime.backend.readText( toBackendContext(runtime, { diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts index 6e4fbce82d3..d6cb202aff3 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts @@ -39,6 +39,32 @@ test('runtime get reads text from a selector target', async () => { ]); }); +test('runtime get text and is text refuse a clipped node and accept the complete one', async () => { + const complete = selectorReadSnapshot(); + const clipped = makeSnapshotState([{ ...complete.nodes[0]!, textClipped: true }]); + const read = (snapshot: typeof complete) => + createSelectorDevice(snapshot).selectors.get({ + session: 'default', + property: 'text', + target: { kind: 'selector', selector: 'label=Continue' }, + }); + + const assertText = (snapshot: typeof complete) => + createSelectorDevice(snapshot).selectors.is({ + session: 'default', + predicate: 'text', + selector: 'label=Continue', + expectedText: 'Continue', + }); + const isClipped = (error: unknown) => + error instanceof AppError && error.details?.reason === 'text_clipped'; + + assert.equal((await read(complete)).kind, 'text'); + await assertText(complete); + await assert.rejects(read(clipped), isClipped); + await assert.rejects(assertText(clipped), isClipped); +}); + test('runtime get selector target captures fresh snapshot without a stored session snapshot', async () => { const snapshot = selectorReadSnapshot(); const sessions = createMemorySessionStore([{ name: 'default' }]); diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index bc88d209637..934ec49e4b6 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: + 'get text refuses a node marked textClipped with reason text_clipped: Android snapshots keep only a prefix of very long text.', }, metadata: metadata('get'), run: (client, input) => client.interactions.get(toGetOptions(input)), @@ -666,6 +668,8 @@ const isCommandFacet = defineCommandFacet({ text: { summary: 'Check a UI predicate on a selector', searchHint: 'assert enabled', + cliDetail: + 'is text refuses a node marked textClipped with reason text_clipped: a clipped prefix cannot prove the full value.', }, metadata: metadata('is'), run: (client, input) => client.interactions.is(input as IsOptions), diff --git a/packages/kernel/src/snapshot.ts b/packages/kernel/src/snapshot.ts index cba6ab2cc14..f7932e36ad4 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; + /** The Android helper capped the text, so `label` and `value` hold only its prefix. */ + 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 1b93ec47d26..48b7dfd9298 100644 --- a/packages/platform-android/src/__tests__/ime-helper.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper.test.ts @@ -88,7 +88,7 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a replace?: boolean; }> = []; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } if (isImeListCall(args)) { @@ -119,24 +119,30 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a assert.deepEqual(installCalls, [{ apkPath, replace: true }]); }); -test('ensureAndroidImeHelper skips install when a newer version is already present', async () => { - const tmpDir = await mkdtempForTest('ime-helper-current-'); +test('ensureAndroidImeHelper replaces a newer installed version with the trusted artifact', async () => { + const tmpDir = await mkdtempForTest('ime-helper-newer-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); + const calls: string[] = []; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, - stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode + 1}`, + stdout: `Package [${manifest.packageName}] (0):\n versionCode=${manifest.versionCode + 1}`, stderr: '', }; } - throw new Error(`unexpected adb call: ${args.join(' ')}`); + if (isImeListCall(args)) { + return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; + } + calls.push(args.join(' ')); + return { exitCode: 0, stdout: '', stderr: '' }; }; const adbProvider: AndroidAdbProvider = { exec: adb, - install: async () => { - throw new Error('install should not be called when a newer version is present'); + install: async (installApkPath) => { + calls.push(`install ${installApkPath}`); + return { exitCode: 0, stdout: '', stderr: '' }; }, }; @@ -147,8 +153,9 @@ test('ensureAndroidImeHelper skips install when a newer version is already prese deviceKey: 'android:emulator-5554', }); - assert.equal(result.installed, false); - assert.equal(result.reason, 'current'); + assert.equal(result.installed, true); + assert.equal(result.reason, 'newer'); + assert.deepEqual(calls.slice(0, 2), [`uninstall ${PACKAGE}`, `install ${apkPath}`]); }); test('ensureAndroidImeHelper returns from an install once the IME is registered', async () => { @@ -157,7 +164,7 @@ test('ensureAndroidImeHelper returns from an install once the IME is registered' await fs.writeFile(apkPath, 'helper-apk'); let imeListCalls = 0; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, stdout: '', stderr: '' }; } if (isImeListCall(args)) { @@ -188,7 +195,7 @@ test('ensureAndroidImeHelper returns the install when the registration listing t const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, stdout: '', stderr: '' }; } if (isImeListCall(args)) { @@ -222,15 +229,19 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer await fs.writeFile(apkPath, 'helper-apk'); let present = false; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return present ? { exitCode: 0, - stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode}`, + stdout: `Package [${manifest.packageName}] (0):\n versionCode=${manifest.versionCode}`, stderr: '', } : { exitCode: 0, stdout: '', stderr: '' }; } + if (args.join(' ') === `shell pm path ${PACKAGE}`) { + const stdout = present ? `package:/data/app/${PACKAGE}-1/base.apk\n` : ''; + return { exitCode: present ? 0 : 1, stdout, stderr: '' }; + } if (isImeListCall(args)) { return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; } @@ -244,6 +255,10 @@ test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer present = true; return { exitCode: 0, stdout: '', stderr: '' }; }, + pull: async (_remotePath, localPath) => { + await fs.writeFile(localPath, 'helper-apk'); + return { exitCode: 0, stdout: '', stderr: '' }; + }, }; const ensure = () => ensureAndroidImeHelper({ @@ -268,7 +283,7 @@ test('ensureAndroidImeHelper install timeout points at the OEM install dialog', const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } throw new Error(`unexpected adb call: ${args.join(' ')}`); diff --git a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts index 6d37d8638c5..ef0df3d952e 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] (0):\n versionCode=1') : { exitCode: 1, stdout: '', stderr: 'not found' }; } @@ -157,7 +158,18 @@ function fakeDeviceState(initialIme: string) { }; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) return handleShowVersionCode(); + if (args.join(' ').includes('dumpsys package')) return handleShowVersionCode(); + if (args.join(' ') === 'shell pm path com.callstack.agentdevice.imehelper') { + return ok('package:/data/app/com.callstack.agentdevice.imehelper/base.apk\n'); + } + if ( + args[0] === 'pull' && + args[1] === '/data/app/com.callstack.agentdevice.imehelper/base.apk' && + args[2] + ) { + fs.copyFileSync(ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]); + return ok('1 file pulled\n'); + } const handler = handlers[args.slice(0, 3).join(' ')]; if (!handler) throw new Error(`unexpected adb call: ${args.join(' ')}`); return handler(args); diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index c31b6ff6426..484ba8d19ff 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -55,7 +55,7 @@ afterEach(async () => { }); /** - * Answers one helper session: the version probe says "current" so no install is faked, the viewport + * Answers one helper session: the version probe reports a newer helper, so the helper reinstalls, the viewport * read reports `window` plus an optional IME window, and the gesture accepts whatever it is given. */ function helperRouteAdb(window: { @@ -66,9 +66,9 @@ function helperRouteAdb(window: { keyboard?: { x: number; y: number; width: number; height: number }; }) { return (args: string[]) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { - stdout: `package:${HELPER_MANIFEST.packageName} versionCode:999999`, + stdout: `Package [${HELPER_MANIFEST.packageName}] (0):\n versionCode=999999`, stderr: '', }; } diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts index fc4d360de38..58de3ddddc4 100644 --- a/packages/platform-android/src/__tests__/settings-locale.test.ts +++ b/packages/platform-android/src/__tests__/settings-locale.test.ts @@ -2,31 +2,19 @@ import crypto from 'node:crypto'; import { promises as fs } from 'node:fs'; import path from 'node:path'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { beforeEach, expect, test, vi } from 'vitest'; -import { prepareAndroidAutomationHelper } from '../automation-helper-artifact.ts'; +import { beforeEach, expect, test } from 'vitest'; import { setAndroidSetting } from '../settings.ts'; -import { - ensureAndroidSnapshotHelper, - resetAndroidSnapshotHelperInstallCache, -} from '../snapshot-helper-install.ts'; +import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import type { AndroidSnapshotHelperArtifact } from '../snapshot-helper-types.ts'; import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; import { withFakeAdb, type FakeAdbResponse } from './test-utils/fake-adb.ts'; import { mkdtempForTest } from './test-utils/tmp-dir.ts'; -vi.mock('../automation-helper-artifact.ts', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - prepareAndroidAutomationHelper: vi.fn(actual.prepareAndroidAutomationHelper), - }; -}); - const PACKAGE = 'com.callstack.agentdevice.snapshothelper'; const VERSION_CODE = 13003; const HELPER_BYTES = 'helper-apk'; const APK = `/data/app/~~a1==/${PACKAGE}-b2==/base.apk`; -const VERSION_QUERY = `shell cmd package list packages --show-versioncode ${PACKAGE}`; +const VERSION_QUERY = `shell dumpsys package ${PACKAGE}`; const LOCALE_COMMAND = /^shell env '?CLASSPATH=([^'\s]+)'? app_process \/system\/bin \S+\.SystemLocaleCommand (\S+)$/; @@ -89,7 +77,7 @@ async function withHelperDevice( if (flat === VERSION_QUERY) { return helper.versionCode === undefined ? { stderr: '', exitCode: 1 } - : `package:${PACKAGE} versionCode:${helper.versionCode}\n`; + : `Package [${PACKAGE}] (0):\n versionCode=${helper.versionCode}\n`; } if (flat === `shell pm path ${PACKAGE}`) { // A split comes first: only the base APK holds the helper classes. @@ -206,126 +194,50 @@ test('settings locale runs app_process from the base APK whose digest it verifie }); }); -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: 'locale-helper-apk-unverified', - dispatched: 'no', - apkPath: APK, - }, - }); - expect(helper.launches).toEqual([]); - }, - { versionCode: VERSION_CODE + 1, bytes: 'another-apk' }, - ); -}); - -test('a locale refusal keeps the snapshot install memo and makes the next locale call inspect the install', async () => { +test('settings locale replaces a newer installed helper before it runs the helper class', 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 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: '', stderr: 'unexpected', exitCode: 1 }; - }, - artifact, - deviceKey: `android:${device.id}`, - }); - expect(install).toMatchObject({ reason: 'current', installed: false }); - expect(snapshotCalls).toEqual([]); - - const firstCall = calls.length; - await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({ - details: { reason: 'locale-helper-apk-unverified' }, + async ({ calls, device, helper }) => { + await expect(setAndroidSetting(device, 'locale', 'en-IN')).resolves.toMatchObject({ + locale: 'en-IN', }); - expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); - expect(helper.launches).toEqual([]); + expect(calls.map((args) => args.join(' '))).toContain(`uninstall ${PACKAGE}`); + expect(helper.files.get(APK)).toEqual(HELPER_BYTES); + expect(helper.launches).toEqual([APK]); }, { versionCode: VERSION_CODE + 1, bytes: 'another-apk' }, ); }); -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 }) => { - await setAndroidSetting(device, 'locale', 'en-IN'); - // A same-version APK with another digest replaces the helper behind the warm memo. - helper.files.set(APK, 'another-apk'); - - // Call A reads no refusal, then waits inside helper preparation. - let resume!: () => void; - const paused = new Promise((resolve) => (resume = resolve)); - let entered!: () => void; - const preparing = new Promise((resolve) => (entered = resolve)); - const actual = vi.mocked(prepareAndroidAutomationHelper).getMockImplementation()!; - vi.mocked(prepareAndroidAutomationHelper).mockImplementationOnce(async (...args) => { - entered(); - await paused; - return await actual(...args); - }); - 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 A resumes and fails on the transport, so it answers no refusal. - pmPathFails = true; - resume(); - await expect(callA).rejects.toMatchObject({ details: { adbFailure: 'device_offline' } }); - pmPathFails = false; +test('a locale refusal drops the install memo so the next locale call repairs the helper', async () => { + await withHelperDevice(async ({ calls, device, helper }) => { + await setAndroidSetting(device, 'locale', 'en-IN'); + // Other bytes appear at the verified path, behind the warm install memo. + helper.files.set(APK, 'another-apk'); + await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({ + details: { reason: 'locale-helper-apk-unverified', dispatched: 'no' }, + }); - // The next locale call still inspects the install, which reinstalls the helper. - const firstCall = calls.length; - await expect(setAndroidSetting(device, 'locale', 'de-DE')).resolves.toMatchObject({ - locale: 'de-DE', - }); - expect(calls.slice(firstCall).map((args) => args.join(' '))).toContain(VERSION_QUERY); - }, - { - override: (args) => - pmPathFails && args.join(' ') === `shell pm path ${PACKAGE}` - ? { stderr: 'error: device offline', exitCode: 1 } - : undefined, - }, - ); + const firstCall = calls.length; + 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).toEqual([APK, APK]); + }); }); -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; + const 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(' '))).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(2); + expect(helper.files.get(helper.apkPath)).toEqual(HELPER_BYTES); + expect(helper.launches).toEqual([APK, helper.apkPath]); }); }); @@ -372,7 +284,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. + // A newer versionCode is replaced before any digest read, so only the locale step reads the path. versionCode: VERSION_CODE + 1, 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-clickability.test.ts b/packages/platform-android/src/__tests__/snapshot-clickability.test.ts index 8204f38d8ce..508a7cff40a 100644 --- a/packages/platform-android/src/__tests__/snapshot-clickability.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-clickability.test.ts @@ -10,7 +10,10 @@ import { buildUiHierarchySnapshot, parseUiHierarchyTree } from '../ui-hierarchy. import { buildAndroidSnapshotClickabilityEvidence } from '../snapshot-clickability.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { AndroidAdbExecutor } from '../snapshot-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 { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; import { androidSnapshotPublicationInput } from '../snapshot-capture.ts'; @@ -126,13 +129,8 @@ test('the regular projection keeps the clickability facts off the node', () => { test('snapshotAndroid captures the hierarchy once and publishes the clickability it retains', async () => { let hierarchyCaptures = 0; 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: '' }; } 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-install.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-install.test.ts index d3f31e17a98..f5607894a44 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-install.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-install.test.ts @@ -62,7 +62,7 @@ test('an exec-shaped helper install timeout names the dialog, not a wedged adb s // install crosses the legacy exec fallback. const apkPath = await writeHelperApk('snapshot-helper-install-timeout-exec-'); const exec: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } if (args[0] === 'install') throw adbInstallTimeout(); @@ -132,7 +132,7 @@ async function writeHelperApk(prefix: string): Promise { function missingPackageProvider(install: AndroidAdbInstaller): AndroidAdbProvider { return { exec: async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } throw new Error(`unexpected adb call: ${args.join(' ')}`); 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..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 @@ -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(32 * 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..20280605d89 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] (0):\n 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-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 497cd830397..a2afdb778ef 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 @@ -106,7 +106,8 @@ function freshlyBootedHelper( provider: { exec: async (args) => { calls.push(args); - if (args.includes('--show-versioncode')) return ANDROID_HELPER_INSTALLED_VERSION_PROBE; + if (args.join(' ').includes('dumpsys package')) + 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 cc6e8ff8200..54790700c76 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 replaces a newer version', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); @@ -184,7 +184,7 @@ test('ensureAndroidSnapshotHelper installs when missing and skips a newer versio const calls: (readonly string[])[] = []; const adb: AndroidAdbExecutor = async (args) => { calls.push(args); - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } return { exitCode: 0, stdout: '', stderr: '' }; @@ -199,17 +199,29 @@ 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: '', - }), + // A newer versionCode is not the trusted artifact, and `install -r` cannot downgrade it. + const newerCalls: (readonly string[])[] = []; + const replaced = await ensureAndroidSnapshotHelper({ + adb: async (args) => { + newerCalls.push(args); + return args.join(' ').includes('dumpsys package') + ? { + exitCode: 0, + stdout: + 'Package [com.callstack.agentdevice.snapshothelper] (0):\n versionCode=13004', + stderr: '', + } + : { exitCode: 0, stdout: '', stderr: '' }; + }, artifact: { apkPath, manifest: localManifest }, }); - assert.equal(skipped.installed, false); - assert.equal(skipped.reason, 'current'); + assert.equal(replaced.installed, true); + assert.equal(replaced.reason, 'newer'); + assert.deepEqual(newerCalls.slice(1, 3), [ + ['uninstall', localManifest.packageName], + ['install', '-r', apkPath], + ]); }); test('ensureAndroidSnapshotHelper tags a device-side install rejection distinctly from artifact resolution', async () => { @@ -217,7 +229,7 @@ test('ensureAndroidSnapshotHelper tags a device-side install rejection distinctl const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } if (args[0] === 'install') { @@ -256,7 +268,7 @@ test('ensureAndroidSnapshotHelper tags a rejected provider install without losin hint: 'The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.', }); const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } throw new Error(`unexpected adb call: ${args.join(' ')}`); @@ -296,10 +308,10 @@ test('ensureAndroidSnapshotHelper replaces same-version helper when APK bytes di }; const installs: string[] = []; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, - stdout: `package:${localManifest.packageName} versionCode:${localManifest.versionCode}`, + stdout: `Package [${localManifest.packageName}] (0):\n versionCode=${localManifest.versionCode}`, stderr: '', }; } @@ -343,15 +355,17 @@ test('installing a same-version different-sha helper evicts the stale install me let installedBytes = 'helper-apk-a'; const installs: string[] = []; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, - stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode}`, + stdout: `Package [${manifest.packageName}] (0):\n versionCode=${manifest.versionCode}`, stderr: '', }; } if (args[0] === 'shell' && args[1] === 'pm' && args[2] === 'path') { - return { exitCode: 0, stdout: 'package:/data/app/helper/base.apk\n', stderr: '' }; + // Android 8.0 and later give each install a new random directory. + const directory = `helper-${installs.length}`; + return { exitCode: 0, stdout: `package:/data/app/${directory}/base.apk\n`, stderr: '' }; } throw new Error(`unexpected adb call: ${args.join(' ')}`); }; @@ -399,103 +413,100 @@ 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 () => { - const tmpDir = await mkdtempForTest('snapshot-helper-install-cache-'); - const apkPath = path.join(tmpDir, 'helper.apk'); - await fs.writeFile(apkPath, 'helper-apk'); - const localManifest = { - ...manifest, - sha256: sha256Text('helper-apk'), - }; - const calls: (readonly string[])[] = []; +/** A device with the trusted helper installed at `installedPath()`, and the adb calls it saw. */ +function installedHelperDevice(packageName: string, installedPath: () => string) { + const calls: string[] = []; const adb: AndroidAdbExecutor = async (args) => { - calls.push(args); - if (args.includes('--show-versioncode')) { - return { exitCode: 1, stdout: '', stderr: 'not found' }; + calls.push(args.join(' ')); + if (args.join(' ').includes('dumpsys package')) { + return { + exitCode: 0, + stdout: `Package [${packageName}] (0):\n versionCode=${manifest.versionCode}`, + stderr: '', + }; + } + if (args.join(' ') === `shell pm path ${packageName}`) { + return { exitCode: 0, stdout: `package:${installedPath()}\n`, stderr: '' }; } return { exitCode: 0, stdout: '', stderr: '' }; }; - const artifact = { apkPath, manifest: localManifest }; + const adbProvider: AndroidAdbProvider = { + exec: adb, + pull: async (remotePath, localPath) => { + calls.push(`pull ${remotePath}`); + await fs.writeFile(localPath, 'helper-apk'); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + install: async (apkPath) => { + calls.push(`install ${apkPath}`); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }; + return { adb, adbProvider, calls }; +} - const installed = await ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:emulator-5554', - }); +test('ensureAndroidSnapshotHelper admits a warm helper by its verified APK path alone', async () => { + const tmpDir = await mkdtempForTest('snapshot-helper-install-cache-'); + const apkPath = path.join(tmpDir, 'helper.apk'); + await fs.writeFile(apkPath, 'helper-apk'); + const artifact = { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }; + const { packageName, versionCode } = artifact.manifest; + let installedPath = '/data/app/helper-1/base.apk'; + const { adb, adbProvider, calls } = installedHelperDevice(packageName, () => installedPath); + const ensure = () => + ensureAndroidSnapshotHelper({ adb, adbProvider, artifact, deviceKey: 'android:emulator-5554' }); + const versionProbe = `shell dumpsys package ${packageName}`; + const pathProbe = `shell pm path ${packageName}`; + + assert.equal((await ensure()).reason, 'current'); + assert.deepEqual(calls, [versionProbe, pathProbe, `pull ${installedPath}`]); + + // The warm admission neither hashes the host APK nor pulls the device APK. + calls.length = 0; await fs.rm(apkPath); - const cached = await ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:emulator-5554', - }); - - assert.equal(installed.reason, 'missing'); - 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], - ]); + const warm = await ensure(); + assert.equal(warm.reason, 'current'); + assert.equal(warm.installedVersionCode, versionCode); + assert.deepEqual(calls, [pathProbe]); + // A helper at another path is not the verified install, so it is inspected again. await fs.writeFile(apkPath, 'helper-apk'); - await ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:device-2', - }); - assert.equal(calls.length, 4); + installedPath = '/data/app/helper-2/base.apk'; + calls.length = 0; + await ensure(); + assert.deepEqual(calls, [pathProbe, versionProbe, pathProbe, `pull ${installedPath}`]); + calls.length = 0; forgetAndroidSnapshotHelperInstall({ deviceKey: 'android:emulator-5554', - packageName: localManifest.packageName, - versionCode: localManifest.versionCode, + packageName, + versionCode, }); - await ensureAndroidSnapshotHelper({ - adb, - artifact, - deviceKey: 'android:emulator-5554', - }); - assert.equal(calls.length, 6); + await ensure(); + assert.deepEqual(calls, [versionProbe, pathProbe, `pull ${installedPath}`]); }); test('ensureAndroidSnapshotHelper always policy bypasses cached install result', async () => { const tmpDir = await mkdtempForTest('snapshot-helper-install-always-'); const apkPath = path.join(tmpDir, 'helper.apk'); await fs.writeFile(apkPath, 'helper-apk'); - const localManifest = { - ...manifest, - sha256: sha256Text('helper-apk'), - }; - const calls: (readonly string[])[] = []; - const adb: AndroidAdbExecutor = async (args) => { - calls.push(args); - if (args.includes('--show-versioncode')) { - return { - exitCode: 0, - stdout: `package:${localManifest.packageName} versionCode:${localManifest.versionCode + 1}`, - stderr: '', - }; - } - return { exitCode: 0, stdout: '', stderr: '' }; - }; - const artifact = { apkPath, manifest: localManifest }; + const artifact = { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }; + const { packageName } = artifact.manifest; + const { adb, adbProvider, calls } = installedHelperDevice( + packageName, + () => '/data/app/helper-1/base.apk', + ); const cached = await ensureAndroidSnapshotHelper({ adb, + adbProvider, artifact, deviceKey: 'android:emulator-5554', }); + calls.length = 0; const forced = await ensureAndroidSnapshotHelper({ adb, + adbProvider, artifact, deviceKey: 'android:emulator-5554', installPolicy: 'always', @@ -504,27 +515,7 @@ test('ensureAndroidSnapshotHelper always policy bypasses cached install result', 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, [`shell dumpsys package ${packageName}`, `install ${apkPath}`]); }); test('shared Android helper verifier rejects snapshot helper checksum mismatch', async () => { @@ -565,10 +556,10 @@ test('ensureAndroidSnapshotHelper uninstalls and retries when signatures differ' const result = await ensureAndroidSnapshotHelper({ adb: async (args) => { calls.push(args); - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:1', + stdout: 'Package [com.callstack.agentdevice.snapshothelper] (0):\n versionCode=1', stderr: '', }; } @@ -603,7 +594,7 @@ test('ensureAndroidSnapshotHelper uses provider install capability with a replac await fs.writeFile(apkPath, 'helper-apk'); const installCalls: Array<{ apkPath: string; replace?: boolean }> = []; const adb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 1, stdout: '', stderr: 'not found' }; } throw new Error(`unexpected adb call: ${args.join(' ')}`); @@ -638,10 +629,10 @@ test('ensureAndroidSnapshotHelper retry install also uses provider install capab let installAttempts = 0; const adb: AndroidAdbExecutor = async (args) => { adbCalls.push(args); - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:1', + stdout: 'Package [com.callstack.agentdevice.snapshothelper] (0):\n versionCode=1', stderr: '', }; } @@ -674,14 +665,16 @@ test('ensureAndroidSnapshotHelper retry install also uses provider install capab assert.deepEqual(adbCalls[1], ['uninstall', 'com.callstack.agentdevice.snapshothelper']); }); -test('captureAndroidSnapshotWithHelper gives adb command overhead beyond helper timeout', async () => { +test('captureAndroidSnapshotWithHelper gives adb command overhead and an output cap', async () => { let commandTimeoutMs: number | undefined; + let maxBuffer: number | undefined; await captureAndroidSnapshotWithHelper({ adb: async (args, options) => { if (args[0] === 'shell' && args[1] === 'rm') { return { exitCode: 0, stdout: '', stderr: '' }; } commandTimeoutMs = options?.timeoutMs; + maxBuffer = options?.maxBuffer; return { exitCode: 0, stdout: helperOutput({ @@ -699,6 +692,8 @@ test('captureAndroidSnapshotWithHelper gives adb command overhead beyond helper }); assert.equal(commandTimeoutMs, 13000); + // The app under test controls the helper output, so the host bounds what it buffers. + assert.equal(maxBuffer, 32 * 1024 * 1024); }); test('captureAndroidSnapshotWithHelper wraps unparseable failed output with adb details', 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..14bd6446d1c 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' }; @@ -117,7 +110,7 @@ test('snapshotAndroid gives an actionable hint when the helper artifact is missi test('snapshotAndroid distinguishes a device-side install rejection from a missing build artifact', async () => { const helperAdb: AndroidAdbExecutor = async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { // No installed package reported, so ensureAndroidSnapshotHelper treats the // helper as missing and attempts a real install. return { exitCode: 0, stdout: '', stderr: '' }; @@ -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.join(' ').includes('dumpsys package')) 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-transient-capture.test.ts b/packages/platform-android/src/__tests__/snapshot-transient-capture.test.ts index b76e1d8f5ed..b2242b56266 100644 --- a/packages/platform-android/src/__tests__/snapshot-transient-capture.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-transient-capture.test.ts @@ -45,7 +45,7 @@ function openSettleWindow(): { settleBy: number } { } function isHelperVersionProbe(args: readonly string[]): boolean { - return args.includes('--show-versioncode'); + return args.join(' ').includes('dumpsys package'); } test('a transient capture releases a helper session it had to start', async () => { 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..cf2e547deac 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 type { AndroidAdbExecutor, AndroidAdbExecutorResult } from '../../adb-executor.ts'; +import { trustedInstalledSnapshotHelperResult as installedHelperResult } from '@agent-device/test-kit'; import type { AndroidSnapshotHelperArtifact } from '../../snapshot-helper-types.ts'; const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; @@ -26,18 +27,20 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti }, }; +export function trustedInstalledSnapshotHelperResult( + args: readonly string[], + artifact: Parameters[1] = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, +): AndroidAdbExecutorResult | undefined { + return installedHelperResult(args, artifact); +} + 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 +72,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..fc06067f27d 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.join(' ').includes('dumpsys package') || + 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__/text-input-fill.test.ts b/packages/platform-android/src/__tests__/text-input-fill.test.ts index 642cd69c2e3..ed8e6bb30b6 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,36 @@ test('verifyAndroidFilledTextInHierarchy rejects near-complete prefixes', () => assert.equal(verification.actual, 'filed the expens'); }); +test('a clipped text prefix does not verify an equal-length fill or answer a text read', () => { + const complete = androidInputXml({ text: 'filed the expense' }); + const clipped = complete.replace( + 'text="filed the expense"', + 'text="filed the expense" text-clipped="true"', + ); + + assert.equal(verifyAndroidFilledTextInHierarchy(complete, 10, 10, 'filed the expense').ok, true); + const clippedVerification = verifyAndroidFilledTextInHierarchy( + clipped, + 10, + 10, + 'filed the expense', + ); + assert.equal(clippedVerification.ok, false); + assert.equal(clippedVerification.actual, null); + assert.equal(readAndroidTextAtPointInHierarchy(complete, 10, 10), 'filed the expense'); + assert.equal(readAndroidTextAtPointInHierarchy(clipped, 10, 10), null); +}); + +test('a clipped text prefix verifies a longer expected value only when it is that value prefix', () => { + const clipped = androidInputXml({ text: 'abcde' }).replace( + 'text="abcde"', + 'text="abcde" text-clipped="true"', + ); + + assert.equal(verifyAndroidFilledTextInHierarchy(clipped, 10, 10, 'abcdefgh').ok, true); + assert.equal(verifyAndroidFilledTextInHierarchy(clipped, 10, 10, 'abcxefgh').ok, false); +}); + test('verifyAndroidFilledTextInHierarchy does not treat inputmethod substring as IME ownership', () => { const verification = verifyAndroidFilledTextInHierarchy( appPackageWithInputMethodSubstringHierarchy(), @@ -711,7 +741,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.join(' ').includes('dumpsys package') || + (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); }, 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..9e4e1c61db4 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); }; } @@ -84,10 +84,10 @@ export function currentVersionAdb(handleInstrument: AndroidAdbExecutor): Android // replaces the APK (install.installed === true) before the wrapped call runs. export function outdatedVersionAdb(handleInstrument: AndroidAdbExecutor): AndroidAdbExecutor { return async (args, options) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { return { exitCode: 0, - stdout: `package:${ANDROID_TOUCH_HELPER_MANIFEST.packageName} versionCode:1`, + stdout: `Package [${ANDROID_TOUCH_HELPER_MANIFEST.packageName}] (0):\n versionCode=1`, stderr: '', }; } diff --git a/packages/platform-android/src/__tests__/touch-helper.test.ts b/packages/platform-android/src/__tests__/touch-helper.test.ts index c5ea73e46ad..8c2bcbbca31 100644 --- a/packages/platform-android/src/__tests__/touch-helper.test.ts +++ b/packages/platform-android/src/__tests__/touch-helper.test.ts @@ -305,11 +305,11 @@ test('a provider-supplied snapshotHelperArtifact overrides the bundled artifact // gestures must install and run the provider's helper, same as snapshots do, never the // bundled artifact resolver. exec: async (args) => { - if (args.includes('--show-versioncode')) { + if (args.join(' ').includes('dumpsys package')) { probeArgs = [...args]; return { exitCode: 0, - stdout: `package:${providerArtifact.manifest.packageName} versionCode:1`, + stdout: `Package [${providerArtifact.manifest.packageName}] (0):\n versionCode=1`, stderr: '', }; } 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(`; /** Shared helper APK install/version-check/checksum lifecycle. */ ensureHelperInstalled( - config: Readonly<{ cache: Set; installTimeoutMs: number; helperLabel: string }>, + config: Readonly<{ cache: Map; installTimeoutMs: number; helperLabel: string }>, request: Readonly<{ adb: AndroidAdbExecutor; adbProvider: AndroidAdbProvider; diff --git a/packages/platform-android/src/adb-transport.ts b/packages/platform-android/src/adb-transport.ts index 95b1cda8ab2..2eeb1633dd3 100644 --- a/packages/platform-android/src/adb-transport.ts +++ b/packages/platform-android/src/adb-transport.ts @@ -22,6 +22,8 @@ export type AndroidAdbExecutorOptions = { allowFailure?: boolean; timeoutMs?: number; binaryStdout?: boolean; + /** Max stdout/stderr bytes the process may write before the transport fails the call. */ + maxBuffer?: number; stdin?: string | Buffer; signal?: AbortSignal; env?: Record; @@ -50,8 +52,6 @@ type AndroidAdbStdioOption = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; export type AndroidAdbSpawnOptions = Omit & { cwd?: string; detached?: boolean; - /** Max stdout/stderr bytes for synchronous runs (default Node ~1MB). */ - maxBuffer?: number; stdio?: | AndroidAdbStdioOption | Array; diff --git a/packages/platform-android/src/automation-helper-artifact.ts b/packages/platform-android/src/automation-helper-artifact.ts index 8c0b4bf9816..42a6e194c12 100644 --- a/packages/platform-android/src/automation-helper-artifact.ts +++ b/packages/platform-android/src/automation-helper-artifact.ts @@ -47,7 +47,6 @@ export function androidAutomationHelperIdentity(artifact: AndroidSnapshotHelperA export async function prepareAndroidAutomationHelper( device: DeviceInfo, signal?: AbortSignal, - options: { inspectInstalled?: boolean } = {}, ): Promise { signal?.throwIfAborted(); const adbProvider = resolveAndroidAdbProvider(device); @@ -69,7 +68,6 @@ export async function prepareAndroidAutomationHelper( adbProvider, artifact, deviceKey, - inspectInstalled: options.inspectInstalled, timeoutMs: HELPER_INSTALL_TIMEOUT_MS, signal, }), diff --git a/packages/platform-android/src/fill-verification.ts b/packages/platform-android/src/fill-verification.ts index 30b801317c1..7280580dc97 100644 --- a/packages/platform-android/src/fill-verification.ts +++ b/packages/platform-android/src/fill-verification.ts @@ -29,6 +29,8 @@ export type { AndroidFillVerification } from './fill-diagnostics.ts'; type AndroidFillVerificationCandidate = AndroidFillVerificationNode & { editText: boolean; + /** The helper capped `text`, so it is a prefix and never a complete value. */ + textClipped: boolean; }; type AndroidTextAtPointInspection = { @@ -341,6 +343,31 @@ function verifyAndroidFilledTextInObservation( }; } + if (inspection.actualInput?.textClipped) { + const clippedText = inspection.actualInput.text ?? ''; + // A value longer than the helper's text clip is observable only as its prefix. + if ( + !inspection.actualInput.hintShowing && + expected.length > clippedText.length && + expected.startsWith(clippedText) + ) { + return { + ok: true, + actual: clippedText, + reason: 'text_mismatch', + targetInput: inspection.targetInput, + actualInput: inspection.actualInput, + }; + } + // The clipped prefix is neither the value nor safe to echo into the failure. + return { + ok: false, + actual: null, + reason: 'text_mismatch', + targetInput: inspection.targetInput, + actualInput: { ...inspection.actualInput, text: null }, + }; + } return ( maskedAndroidFillVerification(inspection, expected) ?? textAndroidFillVerification(inspection, expected) @@ -360,9 +387,9 @@ 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 completeText(candidates[0]!); const atPoint = candidates.filter((candidate) => containsPoint(candidate.rect, x, y)); - if (atPoint.length === 1) return atPoint[0]!.text; + if (atPoint.length === 1) return completeText(atPoint[0]!); } // 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. @@ -373,7 +400,11 @@ export function readAndroidTextAtPointInHierarchy( (target?.type && !androidRawClassMatchesPublishedType(pointTarget.className, target.type)) ) return null; - return pointTarget.text; + return completeText(pointTarget); +} + +function completeText(candidate: AndroidFillVerificationCandidate): string | null { + return candidate.textClipped ? null : candidate.text; } export function androidFillFailureMessage(verification: AndroidFillVerification | null): string { @@ -621,6 +652,7 @@ function androidFillCandidateFromNode( }), area, editText: isEditTextClass(node.className ?? ''), + textClipped: node.textClipped === true, hintShowing: node.hintShowing === true, placeholder: node.hint ?? null, }; diff --git a/packages/platform-android/src/helper-artifacts.ts b/packages/platform-android/src/helper-artifacts.ts index 55a6ad80865..87d1feddab1 100644 --- a/packages/platform-android/src/helper-artifacts.ts +++ b/packages/platform-android/src/helper-artifacts.ts @@ -62,6 +62,8 @@ export const ANDROID_HELPER_INSTALL_STATE_REASONS = { missing: { reason: 'missing' }, // The installed helper's versionCode is below the bundled artifact's. outdated: { reason: 'outdated' }, + // The installed helper's versionCode is above the bundled artifact's, so it is not the trusted build. + newer: { reason: 'newer' }, // The installed helper matches the artifact's versionCode but not its APK checksum. mismatched: { reason: 'mismatched' }, // The installed helper's APK checksum could not be read, so its currency stays unproven. @@ -81,6 +83,7 @@ export type InstalledAndroidHelperState = | { reason: | AndroidHelperInstallStateRows['outdated']['reason'] + | AndroidHelperInstallStateRows['newer']['reason'] | AndroidHelperInstallStateRows['unverifiable']['reason']; installedVersionCode: number; installedSha256?: never; @@ -90,7 +93,7 @@ export type InstalledAndroidHelperState = installedVersionCode: number; installedSha256: string; } - | { reason: 'current'; installedVersionCode: number; installedSha256?: string }; + | { reason: 'current'; installedVersionCode: number; installedSha256: string; apkPath: string }; // --- Manifest field validators, shared by every helper's manifest parser --------------------- diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts index 7a5c7c461b6..e9ab89e0b2a 100644 --- a/packages/platform-android/src/helper-package-install.ts +++ b/packages/platform-android/src/helper-package-install.ts @@ -48,7 +48,7 @@ async function ensureAndroidHelperPackageInstalled(options: { versionCode: number; apkPath: string; sha256: string; - cache: Set; + cache: Map; deviceKey: string; installTimeoutMs: number; helperLabel: string; @@ -66,20 +66,22 @@ 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 !== undefined && installedVersionCode >= versionCode) { - return { - packageName, - versionCode, - installedSha256: sha256, - installed: false, - reason: 'current', - }; - } + const verifiedApkPath = cache.get(cacheKey); + // The memo skips the checksums, never the path check: a wiped, restored, or reinstalled helper + // no longer lives at the verified path. + if ( + verifiedApkPath !== undefined && + (await readAndroidHelperBaseApkPath(adb, packageName)) === verifiedApkPath + ) { + return { + packageName, + versionCode, + installedSha256: sha256, + installed: false, + reason: 'current', + }; } + cache.delete(cacheKey); await verifyAndroidHelperApkChecksum(apkPath, sha256, helperLabel); const state = await inspectInstalledAndroidHelper({ adb, @@ -90,15 +92,21 @@ async function ensureAndroidHelperPackageInstalled(options: { }); if (state.reason === 'current') { - cache.add(cacheKey); + cache.set(cacheKey, state.apkPath); return { packageName, versionCode, - ...state, + installedVersionCode: state.installedVersionCode, + installedSha256: state.installedSha256, installed: false, + reason: state.reason, }; } + // `install -r` refuses a versionCode downgrade, so a newer helper is removed first. + if (state.reason === ANDROID_HELPER_INSTALL_STATE_REASONS.newer.reason) { + await adb(['uninstall', packageName], { allowFailure: true, timeoutMs: installTimeoutMs }); + } const result = await installAndroidHelperPackage(apkPath, { provider: adbProvider, replace: true, @@ -112,7 +120,6 @@ async function ensureAndroidHelperPackageInstalled(options: { reason: state.reason, }); } - cache.add(cacheKey); return { packageName, versionCode, @@ -121,6 +128,24 @@ async function ensureAndroidHelperPackageInstalled(options: { }; } +/** + * The installed helper's base APK path. Android 8.0 and later give each install a new random + * directory, so an unchanged path after a verified install names the same APK bytes. + */ +export async function readAndroidHelperBaseApkPath( + adb: AndroidAdbExecutor, + packageName: string, + signal?: AbortSignal, + timeoutMs = ANDROID_HELPER_IDENTITY_TIMEOUT_MS, +): Promise { + const result = await runAdbShell(adb, ['pm', 'path', packageName], { + allowFailure: true, + timeoutMs, + signal, + }); + return result.exitCode === 0 ? readBaseApkPath(result.stdout) : undefined; +} + export async function inspectInstalledAndroidHelper(options: { adb: AndroidAdbExecutor; adbProvider: AndroidAdbProvider; @@ -130,7 +155,7 @@ export async function inspectInstalledAndroidHelper(options: { signal?: AbortSignal; }): Promise { const { adb, adbProvider, packageName, versionCode, sha256, signal } = options; - const installedVersionCode = await readInstalledAndroidPackageVersionCode( + const installedVersionCode = await readInstalledAndroidHelperVersionCode( adb, packageName, signal, @@ -142,23 +167,23 @@ export async function inspectInstalledAndroidHelper(options: { installedVersionCode, reason: ANDROID_HELPER_INSTALL_STATE_REASONS.outdated.reason, }; - if (installedVersionCode > versionCode) return { installedVersionCode, reason: 'current' }; + if (installedVersionCode > versionCode) + return { installedVersionCode, reason: ANDROID_HELPER_INSTALL_STATE_REASONS.newer.reason }; try { - const installedSha256 = await readInstalledAndroidPackageSha256( + const { apkPath, installedSha256 } = await readInstalledAndroidPackageApk( adb, adbProvider, packageName, signal, ); - return { - installedVersionCode, - installedSha256, - reason: - installedSha256 === sha256 - ? 'current' - : ANDROID_HELPER_INSTALL_STATE_REASONS.mismatched.reason, - }; + return installedSha256 === sha256 + ? { installedVersionCode, installedSha256, apkPath, reason: 'current' } + : { + installedVersionCode, + installedSha256, + reason: ANDROID_HELPER_INSTALL_STATE_REASONS.mismatched.reason, + }; } catch { signal?.throwIfAborted(); return { @@ -203,7 +228,7 @@ export function makeEnsureAndroidHelperInstalled< manifest: { packageName: string; versionCode: number; sha256: string }; }, >(params: { - cache: Set; + cache: Map; installTimeoutMs: number; helperLabel: string; }): (options: { @@ -228,39 +253,42 @@ export function makeEnsureAndroidHelperInstalled< }; } -async function readInstalledAndroidPackageVersionCode( +/** + * The installed versionCode from `dumpsys package`, which every supported Android level answers. + * `pm list packages --show-versioncode` is absent before Android 8.0. + */ +export async function readInstalledAndroidHelperVersionCode( adb: AndroidAdbExecutor, packageName: string, signal?: AbortSignal, + timeoutMs = 5_000, ): Promise { - const result = await runAdbShell( - adb, - ['cmd', 'package', 'list', 'packages', '--show-versioncode', packageName], - { allowFailure: true, timeoutMs: 5_000, signal }, - ); + const result = await runAdbShell(adb, ['dumpsys', 'package', packageName], { + allowFailure: true, + timeoutMs, + signal, + }); if (result.exitCode !== 0) return undefined; const match = new RegExp( - `package:${escapeRegExp(packageName)}(?:\\s|$).*versionCode:(\\d+)`, - ).exec(`${result.stdout}\n${result.stderr}`); + `Package \\[${escapeRegExp(packageName)}\\][\\s\\S]*?\\bversionCode=(\\d+)`, + ).exec(result.stdout); return match ? Number(match[1]) : undefined; } -async function readInstalledAndroidPackageSha256( +async function readInstalledAndroidPackageApk( adb: AndroidAdbExecutor, adbProvider: AndroidAdbProvider, packageName: string, signal?: AbortSignal, -): Promise { - const pathResult = await runAdbShell(adb, ['pm', 'path', packageName], { - allowFailure: true, - timeoutMs: ANDROID_HELPER_IDENTITY_TIMEOUT_MS, - signal, - }); - const remotePath = readBaseApkPath(`${pathResult.stdout}\n${pathResult.stderr}`); - if (pathResult.exitCode !== 0 || !remotePath) { +): Promise<{ apkPath: string; installedSha256: string }> { + const remotePath = await readAndroidHelperBaseApkPath(adb, packageName, signal); + if (!remotePath) { throw new AppError('COMMAND_FAILED', 'Could not resolve installed Android helper APK'); } - return await readAndroidDeviceFileSha256(adbProvider, remotePath, signal); + return { + apkPath: remotePath, + installedSha256: await readAndroidDeviceFileSha256(adbProvider, remotePath, signal), + }; } /** The SHA-256 of one file on the device, pulled to a private temp directory and hashed there. */ diff --git a/packages/platform-android/src/ime-helper.ts b/packages/platform-android/src/ime-helper.ts index 97836fc16e7..b15880ac6a5 100644 --- a/packages/platform-android/src/ime-helper.ts +++ b/packages/platform-android/src/ime-helper.ts @@ -190,7 +190,7 @@ function parseAndroidImeHelperManifest(value: unknown): AndroidImeHelperManifest }; } -const installedImeHelpers = new Set(); +const installedImeHelpers = new Map(); export async function ensureAndroidImeHelper(options: { adb: AndroidAdbExecutor; diff --git a/packages/platform-android/src/settings-locale.ts b/packages/platform-android/src/settings-locale.ts index 53997647631..5d2b3467e27 100644 --- a/packages/platform-android/src/settings-locale.ts +++ b/packages/platform-android/src/settings-locale.ts @@ -19,13 +19,6 @@ const ANDROID_LOCALE_REASONS = { /** The helper class that runs as the shell user through `app_process`; see its Javadoc. */ const SYSTEM_LOCALE_COMMAND = 'com.callstack.agentdevice.snapshothelper.SystemLocaleCommand'; -/** - * The latest locale refusal of the helper APK, by snapshot-helper device key. The next locale - * command there inspects the install instead of trusting the shared install memo, which other - * helper commands keep using. - */ -const refusedLocaleInstalls = new Map(); - /** Android 8.0 gives each install a random directory, so a verified base APK path names one APK. */ const LOCALE_MIN_SDK = 26; @@ -44,17 +37,7 @@ export async function setAndroidLocale( await requireLocaleApiLevel(device, signal); const requested = state === SETTING_RESET_STATE ? await readAndroidDefaultLocale(device) : state; const { prepareAndroidAutomationHelper } = await import('./automation-helper-artifact.ts'); - const { getAndroidSnapshotHelperSessionDeviceKey } = - await import('./snapshot-helper-retirement.ts'); - const deviceKey = getAndroidSnapshotHelperSessionDeviceKey(device); - const refusal = refusedLocaleInstalls.get(deviceKey); - const prepared = await prepareAndroidAutomationHelper(device, signal, { - inspectInstalled: refusal !== undefined, - }); - // Only the inspected refusal is answered: a newer one keeps its recheck. - if (refusal !== undefined && refusedLocaleInstalls.get(deviceKey) === refusal) { - refusedLocaleInstalls.delete(deviceKey); - } + const prepared = await prepareAndroidAutomationHelper(device, signal); const apkPath = await readVerifiedHelperApkPath(device, prepared, signal); signal?.throwIfAborted(); const result = await runAndroidShell( @@ -120,9 +103,9 @@ async function requireLocaleApiLevel(device: DeviceInfo, signal?: AbortSignal): /** * The helper's base APK, which `app_process` loads as the shell user. The install step may trust - * a cached decision or a higher installed versionCode, so this path proves its own bytes: the file - * that runs is the one whose SHA-256 matches the trusted manifest. Every failure here precedes the - * locale write, so it states `dispatched: no` and names a helper install that preparation completed. + * a cached decision, so this path proves its own bytes: the file that runs is the one whose + * SHA-256 matches the trusted manifest. Every failure here precedes the locale write, so it states + * `dispatched: no` and names a helper install that preparation completed. */ async function readVerifiedHelperApkPath( device: DeviceInfo, @@ -134,6 +117,7 @@ async function readVerifiedHelperApkPath( ): Promise { const { readBaseApkPath, readAndroidDeviceFileSha256 } = await import('./helper-package-install.ts'); + const { forgetAndroidSnapshotHelperInstall } = await import('./snapshot-helper-install.ts'); const { packageName, sha256: expectedSha256 } = prepared.artifact.manifest; const notDispatched = (error: unknown): unknown => { if (!(error instanceof AppError)) return error; @@ -147,14 +131,19 @@ async function readVerifiedHelperApkPath( return discloseDispatch(error, 'no'); }; const refuse = (message: string, details: Record): unknown => { - refusedLocaleInstalls.set(prepared.deviceKey, Symbol('locale helper refusal')); + // The next command inspects the install instead of trusting the memo. + forgetAndroidSnapshotHelperInstall({ + deviceKey: prepared.deviceKey, + packageName, + versionCode: prepared.artifact.manifest.versionCode, + }); return notDispatched( new AppError('COMMAND_FAILED', message, { ...details, deviceId: device.id, packageName, reason: ANDROID_LOCALE_REASONS.helperApkUnverified.reason, - hint: `Retry the command so agent-device inspects and reinstalls its helper. If the device keeps a newer helper build, uninstall ${packageName} first.`, + hint: 'Retry the command so agent-device inspects and reinstalls its helper.', }), ); }; diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index 87e20c4cf3a..bbbdcc67582 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -22,6 +22,7 @@ import { ANDROID_SNAPSHOT_HELPER_COMMAND_OVERHEAD_MS, ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT, + ANDROID_SNAPSHOT_HELPER_MAX_OUTPUT_BYTES, ANDROID_SNAPSHOT_HELPER_PACKAGE, ANDROID_SNAPSHOT_HELPER_PROTOCOL, ANDROID_SNAPSHOT_HELPER_WAIT_FOR_IDLE_QUIET_MS, @@ -107,6 +108,7 @@ export async function captureAndroidSnapshotWithHelper( { allowFailure: true, timeoutMs: resolved.commandTimeoutMs, + maxBuffer: ANDROID_SNAPSHOT_HELPER_MAX_OUTPUT_BYTES, signal: options.signal, }, ); diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index a4a020de001..37228f5d557 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -2,11 +2,13 @@ import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/err import { inspectInstalledAndroidHelper, installAndroidHelperPackage, + readAndroidHelperBaseApkPath, + readInstalledAndroidHelperVersionCode, verifyAndroidHelperApkChecksum, } from './helper-package-install.ts'; +import { ANDROID_HELPER_INSTALL_STATE_REASONS } from './helper-artifacts.ts'; import { androidAdbResultError, - runAdbShell, type AndroidAdbExecutor, type AndroidAdbProvider, } from './adb-executor.ts'; @@ -16,7 +18,8 @@ import type { AndroidSnapshotHelperInstallResult, } from './snapshot-helper-types.ts'; -const installedSnapshotHelpers = new Map(); +/** The device base APK path whose bytes matched the artifact, by device, package, and artifact. */ +const verifiedSnapshotHelperApkPaths = new Map(); export function forgetAndroidSnapshotHelperInstall(options: { deviceKey: string; @@ -24,7 +27,7 @@ export function forgetAndroidSnapshotHelperInstall(options: { versionCode: number; }): void { const prefix = `${options.deviceKey}\0${options.packageName}\0${options.versionCode}\0`; - for (const cacheKey of installedSnapshotHelpers.keys()) { + for (const cacheKey of verifiedSnapshotHelperApkPaths.keys()) { if (cacheKey.startsWith(prefix)) forgetInstalledSnapshotHelper(cacheKey); } } @@ -44,7 +47,7 @@ export function isAndroidSnapshotHelperNotCurrentError(error: unknown): boolean * @internal Test isolation hook for process-global snapshot helper install cache. */ export function resetAndroidSnapshotHelperInstallCache(): void { - installedSnapshotHelpers.clear(); + verifiedSnapshotHelperApkPaths.clear(); } function getInstallCacheKey( @@ -56,25 +59,9 @@ function getInstallCacheKey( return deviceKey ? `${deviceKey}\0${packageName}\0${versionCode}\0${sha256}` : undefined; } -function rememberInstalledSnapshotHelper( - cacheKey: string | undefined, - installedVersionCode: number, -): void { - if (!cacheKey) return; - // Same-version replacement changes only the sha, so recording this helper as installed must - // evict every other cached decision for the same device+package: a stale 'current' memo for the - // previous binary would otherwise skip the sha re-inspection after the swap. - const [deviceKey, packageName] = cacheKey.split('\0'); - const prefix = `${deviceKey}\0${packageName}\0`; - for (const key of installedSnapshotHelpers.keys()) { - if (key !== cacheKey && key.startsWith(prefix)) installedSnapshotHelpers.delete(key); - } - installedSnapshotHelpers.set(cacheKey, installedVersionCode); -} - function forgetInstalledSnapshotHelper(cacheKey: string | undefined): void { if (cacheKey) { - installedSnapshotHelpers.delete(cacheKey); + verifiedSnapshotHelperApkPaths.delete(cacheKey); } } @@ -84,8 +71,6 @@ export async function ensureAndroidSnapshotHelper(options: { artifact: AndroidSnapshotHelperArtifact; deviceKey?: string; installPolicy?: AndroidSnapshotHelperInstallPolicy; - /** Inspect the device even when the install memo says current; the memo stays for other callers. */ - inspectInstalled?: boolean; timeoutMs?: number; signal?: AbortSignal; }): Promise { @@ -103,33 +88,34 @@ export async function ensureAndroidSnapshotHelper(options: { }; } const installCacheKey = getInstallCacheKey(options.deviceKey, packageName, versionCode, sha256); - const cachedVersionCode = installCacheKey - ? installedSnapshotHelpers.get(installCacheKey) + const verifiedApkPath = installCacheKey + ? verifiedSnapshotHelperApkPaths.get(installCacheKey) : undefined; if ( - installCacheKey && installPolicy !== 'always' && - !options.inspectInstalled && - cachedVersionCode !== undefined + verifiedApkPath !== undefined && + (await readAndroidHelperBaseApkPath(adb, packageName, options.signal, options.timeoutMs)) === + verifiedApkPath ) { return { packageName, versionCode, - installedVersionCode: cachedVersionCode, + installedVersionCode: versionCode, installedSha256: sha256, installed: false, reason: 'current', }; } + forgetInstalledSnapshotHelper(installCacheKey); await verifyAndroidHelperApkChecksum(artifact.apkPath, sha256, 'Android snapshot helper'); const installedState = installPolicy === 'always' ? { - installedVersionCode: await readInstalledVersionCode( + installedVersionCode: await readInstalledAndroidHelperVersionCode( adb, packageName, - options.timeoutMs, options.signal, + options.timeoutMs, ), reason: 'forced' as const, installedSha256: undefined, @@ -144,8 +130,9 @@ export async function ensureAndroidSnapshotHelper(options: { }); const { installedVersionCode, installedSha256, reason } = installedState; - if (reason === 'current') { - rememberInstalledSnapshotHelper(installCacheKey, installedVersionCode); + if (installedState.reason === 'current') { + if (installCacheKey) + verifiedSnapshotHelperApkPaths.set(installCacheKey, installedState.apkPath); return { packageName, versionCode, @@ -172,15 +159,16 @@ export async function ensureAndroidSnapshotHelper(options: { try { result = await installAndroidSnapshotHelper(adb, options.adbProvider ?? adb, artifact.apkPath, { packageName, + uninstallFirst: + reason === ANDROID_HELPER_INSTALL_STATE_REASONS.newer.reason || + (installedVersionCode !== undefined && installedVersionCode > versionCode), timeoutMs: options.timeoutMs, signal: options.signal, }); } catch (error) { - forgetInstalledSnapshotHelper(installCacheKey); throw markAndroidSnapshotHelperInstallFailure(error, { packageName, versionCode }); } if (result.exitCode !== 0) { - forgetInstalledSnapshotHelper(installCacheKey); throw markAndroidSnapshotHelperInstallFailure( androidAdbResultError('Failed to install Android snapshot helper', result, { packageName, @@ -188,8 +176,6 @@ export async function ensureAndroidSnapshotHelper(options: { }), ); } - - rememberInstalledSnapshotHelper(installCacheKey, versionCode); return { packageName, versionCode, @@ -225,33 +211,25 @@ function normalizeAdbProvider( return typeof provider === 'function' ? { exec: provider } : provider; } -async function readInstalledVersionCode( - adb: AndroidAdbExecutor, - packageName: string, - timeoutMs: number | undefined, - signal: AbortSignal | undefined, -): Promise { - const result = await runAdbShell( - adb, - ['cmd', 'package', 'list', 'packages', '--show-versioncode', packageName], - { - allowFailure: true, - timeoutMs, - signal, - }, - ); - if (result.exitCode === 0) { - return parsePackageListVersionCode(`${result.stdout}\n${result.stderr}`, packageName); - } - return undefined; -} - async function installAndroidSnapshotHelper( adb: AndroidAdbExecutor, adbProvider: AndroidAdbProvider | AndroidAdbExecutor, apkPath: string, - options: { packageName: string; timeoutMs?: number; signal?: AbortSignal }, + options: { + packageName: string; + /** `install -r` refuses a versionCode downgrade, so a newer helper is removed first. */ + uninstallFirst: boolean; + timeoutMs?: number; + signal?: AbortSignal; + }, ): Promise>> { + const uninstall = async () => + await adb(['uninstall', options.packageName], { + allowFailure: true, + timeoutMs: options.timeoutMs, + signal: options.signal, + }); + if (options.uninstallFirst) await uninstall(); const install = async () => await installAndroidHelperPackage(apkPath, { allowFailure: true, @@ -266,11 +244,7 @@ async function installAndroidSnapshotHelper( return result; } - const uninstall = await adb(['uninstall', options.packageName], { - allowFailure: true, - timeoutMs: options.timeoutMs, - signal: options.signal, - }); + const uninstalled = await uninstall(); const retry = await install(); if (retry.exitCode === 0) { return retry; @@ -280,8 +254,8 @@ async function installAndroidSnapshotHelper( ...retry, stderr: [ retry.stderr, - uninstall.stderr - ? `Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${uninstall.stderr}` + uninstalled.stderr + ? `Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${uninstalled.stderr}` : '', ] .filter(Boolean) @@ -289,23 +263,6 @@ async function installAndroidSnapshotHelper( }; } -function parsePackageListVersionCode(output: string, packageName: string): number | undefined { - const packagePrefix = `package:${packageName}`; - for (const line of output.split(/\r?\n/)) { - if ( - !line.startsWith(packagePrefix) || - (line.length > packagePrefix.length && !/\s/.test(line[packagePrefix.length] ?? '')) - ) { - continue; - } - const match = /(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(line); - if (match) { - return Number(match[1]); - } - } - return undefined; -} - function isInstallUpdateIncompatible(result: { stdout: string; stderr: string }): boolean { return `${result.stdout}\n${result.stderr}`.includes('INSTALL_FAILED_UPDATE_INCOMPATIBLE'); } diff --git a/packages/platform-android/src/snapshot-helper-session-protocol.ts b/packages/platform-android/src/snapshot-helper-session-protocol.ts index 076f516d3ee..8aaf1ab435d 100644 --- a/packages/platform-android/src/snapshot-helper-session-protocol.ts +++ b/packages/platform-android/src/snapshot-helper-session-protocol.ts @@ -13,6 +13,7 @@ import { readInstrumentationResultNumber, } from './instrumentation-helper.ts'; import { + ANDROID_SNAPSHOT_HELPER_MAX_OUTPUT_BYTES, ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT, ANDROID_SNAPSHOT_HELPER_PROTOCOL, ANDROID_SNAPSHOT_HELPER_SESSION_SOCKET_PREFIX, @@ -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 passed the host byte limit, so the host dropped it. + 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,21 @@ 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.length; + if (responseBytes <= ANDROID_SNAPSHOT_HELPER_MAX_OUTPUT_BYTES) { + return void chunks.push(Buffer.from(chunk)); + } + phase = 'refused'; + cleanup(); + socket.destroy(); + return reject( + new AppError('COMMAND_FAILED', 'Android snapshot helper answer exceeds the size limit', { + reason: SNAPSHOT_HELPER_SESSION_REASONS.responseTooLarge.reason, + limitBytes: ANDROID_SNAPSHOT_HELPER_MAX_OUTPUT_BYTES, + }), + ); + } 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/packages/platform-android/src/snapshot-helper-types.ts b/packages/platform-android/src/snapshot-helper-types.ts index 3ba6491f55d..db520c75114 100644 --- a/packages/platform-android/src/snapshot-helper-types.ts +++ b/packages/platform-android/src/snapshot-helper-types.ts @@ -5,6 +5,7 @@ export type AndroidSnapshotCaptureMode = 'interactive-windows' | 'active-window' export type AndroidSnapshotHelperInstallReason = | 'missing' | 'outdated' + | 'newer' | 'mismatched' | 'unverifiable' | 'forced' @@ -23,6 +24,8 @@ export const ANDROID_SNAPSHOT_HELPER_WAIT_FOR_IDLE_QUIET_MS = 100; export const ANDROID_SNAPSHOT_HELPER_COMMAND_OVERHEAD_MS = 5_000; export const ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS = 5_000; export const ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS = 30_000; +/** The app under test controls the text in helper output, so the host keeps at most this much. */ +export const ANDROID_SNAPSHOT_HELPER_MAX_OUTPUT_BYTES = 32 * 1024 * 1024; /** * The `mode` argument that starts a persistent session, and the only one the host ever sends for one. * A helper build that does not implement it rejects the launch in `onStart`, before it binds 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 94e0642b32e..f62bbfbaaa6 100644 --- a/packages/platform-android/src/ui-hierarchy.ts +++ b/packages/platform-android/src/ui-hierarchy.ts @@ -25,6 +25,7 @@ export type { /** Parsed node metadata plus status/navigation subtree provenance when present. */ export type AndroidUiNodeMetadata = { text: string | null; + textClipped?: boolean; desc: string | null; resourceId: string | null; packageName: string | null; @@ -165,6 +166,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'), @@ -353,6 +355,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/packages/selectors/src/interaction-error.ts b/packages/selectors/src/interaction-error.ts index 99bdbf458ca..28de35550fa 100644 --- a/packages/selectors/src/interaction-error.ts +++ b/packages/selectors/src/interaction-error.ts @@ -69,6 +69,8 @@ export const INTERACTION_ERROR_REASONS = { */ // Every tappable region of the target belongs to one of its interactive children. coveredByInteractiveDescendants: { reason: 'covered_by_interactive_descendants' }, + // The snapshot holds only a prefix of the element text, so `is text`, `get text`, and `find ... get_text` cannot use it. + textClipped: { reason: 'text_clipped' }, } as const satisfies ReasonTable<'interaction'>; /** diff --git a/packages/test-kit/src/index.ts b/packages/test-kit/src/index.ts index 47030a37854..8f4fd2bedbb 100644 --- a/packages/test-kit/src/index.ts +++ b/packages/test-kit/src/index.ts @@ -194,3 +194,4 @@ export { type ValidationCase, type ValidationExpectation, } from './validation-values.ts'; +export { trustedInstalledSnapshotHelperResult } from './installed-helper.fixtures.ts'; diff --git a/packages/test-kit/src/installed-helper.fixtures.ts b/packages/test-kit/src/installed-helper.fixtures.ts new file mode 100644 index 00000000000..88d18a20f4d --- /dev/null +++ b/packages/test-kit/src/installed-helper.fixtures.ts @@ -0,0 +1,27 @@ +import fs from 'node:fs'; + +/** Answers the adb calls that admit an already installed, byte-identical Android helper. */ +export function trustedInstalledSnapshotHelperResult( + args: readonly string[], + artifact: { + apkPath: string; + manifest: { packageName: string; versionCode: number }; + }, +): { exitCode: number; stdout: string; stderr: string } | undefined { + const packageName = artifact.manifest.packageName; + if (args.join(' ').includes('dumpsys package') && args.includes(packageName)) { + return { + exitCode: 0, + stdout: `Package [${packageName}] (0):\n 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; +} 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..a5ae4b0d7f0 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 { trustedInstalledSnapshotHelperResult as installedHelperResult } from '@agent-device/test-kit'; import { fileURLToPath } from 'node:url'; const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; @@ -25,6 +26,12 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti }, }; +export function trustedInstalledSnapshotHelperResult( + args: readonly string[], +): { exitCode: number; stdout: string; stderr: string } | undefined { + return installedHelperResult(args, ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT); +} + 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 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 ''; } diff --git a/test/integration/provider-scenarios/android-find.test.ts b/test/integration/provider-scenarios/android-find.test.ts index 15228f7ff95..72d2f6d8ae4 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'; @@ -228,6 +231,8 @@ function androidFindAdbResult( includeDuplicateAppsRow: boolean, ime: ReturnType, ): { stdout: string; stderr: string; exitCode: number } { + const installed = trustedInstalledSnapshotHelperResult(args); + if (installed) return installed; 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..6c73db2b3f9 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; @@ -89,17 +92,20 @@ export function androidImeLifecycleAdbResult( args: readonly string[], state: AndroidProviderShellState | undefined, ): AndroidImeAdbResult | undefined { - 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. + if (key === 'shell dumpsys package com.callstack.agentdevice.imehelper') { return { - stdout: 'package:com.callstack.agentdevice.imehelper versionCode:999999\n', + stdout: `Package [${IME_PACKAGE}] (0):\n 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/android-longpress-ledger.test.ts b/test/integration/provider-scenarios/android-longpress-ledger.test.ts index cf6876a5a2e..914c374927d 100644 --- a/test/integration/provider-scenarios/android-longpress-ledger.test.ts +++ b/test/integration/provider-scenarios/android-longpress-ledger.test.ts @@ -83,10 +83,10 @@ function createLongPressLedgerAdbProvider(params: { // A dump without a focus line sends the dialog and foreground observations through every // variant they may read, so each one spends its whole budget. if (params.isTracking() && isObservationDump(args)) return ok; - if (args.includes('--show-versioncode') && args.includes(HELPER.packageName)) { + if (args.join(' ').includes('dumpsys package') && args.includes(HELPER.packageName)) { return { ...ok, - stdout: `package:${HELPER.packageName} versionCode:${HELPER.versionCode}\n`, + stdout: `Package [${HELPER.packageName}] (0):\n versionCode=${HELPER.versionCode}\n`, }; } if (args[0] === 'shell' && args[1] === 'pm' && args[2] === 'path') { @@ -142,7 +142,7 @@ function gestureDurationMs(call: LongPressLedgerCall): number | undefined { function assertLongPressLedgerPhaseCoverage(ledger: readonly LongPressLedgerCall[]): void { const printed = `\nLedger:\n${JSON.stringify(ledger, null, 2)}`; const isVersionRead = (call: LongPressLedgerCall) => - call.tool === 'exec' && call.args.includes('--show-versioncode'); + call.tool === 'exec' && call.args.join(' ').includes('dumpsys package'); const isApkPathRead = (call: LongPressLedgerCall) => call.tool === 'exec' && call.args.includes('pm') && call.args.includes('path'); const isGesture = (call: LongPressLedgerCall) => diff --git a/test/integration/provider-scenarios/android-world.ts b/test/integration/provider-scenarios/android-world.ts index e58e7711b5a..9436cb5748b 100644 --- a/test/integration/provider-scenarios/android-world.ts +++ b/test/integration/provider-scenarios/android-world.ts @@ -666,10 +666,7 @@ function androidPackageDumpsysAdbResult(args: string[]): AndroidAdbResult | unde } function androidSnapshotHelperProbeAdbResult(key: string): AndroidAdbResult | undefined { - if ( - key === - 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.snapshothelper' - ) { + if (key === 'shell dumpsys package com.callstack.agentdevice.snapshothelper') { return { stdout: '', stderr: '', exitCode: 1 }; } return undefined; diff --git a/test/integration/provider-scenarios/composite-deadline.test.ts b/test/integration/provider-scenarios/composite-deadline.test.ts index ef2487f230b..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'; @@ -44,12 +47,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 = trustedInstalledSnapshotHelperResult(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 +286,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 = trustedInstalledSnapshotHelperResult(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/test/integration/provider-scenarios/provider-failures.test.ts b/test/integration/provider-scenarios/provider-failures.test.ts index 49253f898d5..da437a9e2cc 100644 --- a/test/integration/provider-scenarios/provider-failures.test.ts +++ b/test/integration/provider-scenarios/provider-failures.test.ts @@ -39,7 +39,9 @@ test('Provider-backed integration normalizes provider failures through the reque ); assert.equal(typeof response.json?.error?.data?.diagnosticId, 'string'); assert.ok( - adbCalls.some((call) => call.includes('--show-versioncode')), + adbCalls.some((call) => + call.join(' ').includes('dumpsys package com.callstack.agentdevice.snapshothelper'), + ), JSON.stringify(adbCalls), ); assert.equal( diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 33c3d3f084f..8820fa0b610 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -553,6 +553,7 @@ These reasons can come from more than one command. | --- | --- | | `missing` | The device has no package installed under the helper's name. | | `outdated` | The installed helper's versionCode is below the bundled artifact's. | +| `newer` | The installed helper's versionCode is above the bundled artifact's, so it is not the trusted build. | | `mismatched` | The installed helper matches the artifact's versionCode but not its APK checksum. | | `unverifiable` | The installed helper's APK checksum could not be read, so its currency stays unproven. | @@ -570,6 +571,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 passed the host byte limit, so the host dropped it. | | `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. | @@ -935,6 +937,7 @@ These reasons can come from more than one command. | `target_disabled` | `find focus` or `find type` resolved to a disabled text field. | | `target_still_moving` | The target did not come to rest before the press; wait for the screen, then retry. | | `covered_by_interactive_descendants` | Every tappable region of the target belongs to one of its interactive children. | +| `text_clipped` | The snapshot holds only a prefix of the element text, so `is text`, `get text`, and `find ... get_text` cannot use it. | | `offscreen_selector` | A selector resolved to an element outside the screen, so nothing was pressed. | | `offscreen_ref` | An @ref resolved to an element outside the screen, so nothing was pressed. |